blob: b7aa55843ea790e4660c76338a4da6e9d0cb9a4c [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;
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000148 } else if (DI->getDef()->getName() == "SDNPAssociative") {
149 Properties |= 1 << SDNPAssociative;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000150 } else {
151 std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
152 << "' on node '" << R->getName() << "'!\n";
153 exit(1);
154 }
155 }
156
157
Chris Lattner33c92e92005-09-08 21:27:15 +0000158 // Parse the type constraints.
159 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
160 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
161 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
162 "Constraints list should contain constraint definitions!");
163 Record *Constraint =
164 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
165 TypeConstraints.push_back(Constraint);
166 }
Chris Lattnerca559d02005-09-08 21:03:01 +0000167}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000168
169//===----------------------------------------------------------------------===//
170// TreePatternNode implementation
171//
172
173TreePatternNode::~TreePatternNode() {
174#if 0 // FIXME: implement refcounted tree nodes!
175 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
176 delete getChild(i);
177#endif
178}
179
Chris Lattner32707602005-09-08 23:22:48 +0000180/// UpdateNodeType - Set the node type of N to VT if VT contains
181/// information. If N already contains a conflicting type, then throw an
182/// exception. This returns true if any information was updated.
183///
184bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
185 if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
186 if (getType() == MVT::LAST_VALUETYPE) {
187 setType(VT);
188 return true;
189 }
190
191 TP.error("Type inference contradiction found in node " +
192 getOperator()->getName() + "!");
193 return true; // unreachable
194}
195
196
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000197void TreePatternNode::print(std::ostream &OS) const {
198 if (isLeaf()) {
199 OS << *getLeafValue();
200 } else {
201 OS << "(" << getOperator()->getName();
202 }
203
204 if (getType() == MVT::Other)
205 OS << ":Other";
206 else if (getType() == MVT::LAST_VALUETYPE)
207 ;//OS << ":?";
208 else
209 OS << ":" << getType();
210
211 if (!isLeaf()) {
212 if (getNumChildren() != 0) {
213 OS << " ";
214 getChild(0)->print(OS);
215 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
216 OS << ", ";
217 getChild(i)->print(OS);
218 }
219 }
220 OS << ")";
221 }
222
223 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000224 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000225 if (TransformFn)
226 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000227 if (!getName().empty())
228 OS << ":$" << getName();
229
230}
231void TreePatternNode::dump() const {
232 print(std::cerr);
233}
234
235/// clone - Make a copy of this tree and all of its children.
236///
237TreePatternNode *TreePatternNode::clone() const {
238 TreePatternNode *New;
239 if (isLeaf()) {
240 New = new TreePatternNode(getLeafValue());
241 } else {
242 std::vector<TreePatternNode*> CChildren;
243 CChildren.reserve(Children.size());
244 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
245 CChildren.push_back(getChild(i)->clone());
246 New = new TreePatternNode(getOperator(), CChildren);
247 }
248 New->setName(getName());
249 New->setType(getType());
250 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000251 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000252 return New;
253}
254
Chris Lattner32707602005-09-08 23:22:48 +0000255/// SubstituteFormalArguments - Replace the formal arguments in this tree
256/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000257void TreePatternNode::
258SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
259 if (isLeaf()) return;
260
261 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
262 TreePatternNode *Child = getChild(i);
263 if (Child->isLeaf()) {
264 Init *Val = Child->getLeafValue();
265 if (dynamic_cast<DefInit*>(Val) &&
266 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
267 // We found a use of a formal argument, replace it with its value.
268 Child = ArgMap[Child->getName()];
269 assert(Child && "Couldn't find formal argument!");
270 setChild(i, Child);
271 }
272 } else {
273 getChild(i)->SubstituteFormalArguments(ArgMap);
274 }
275 }
276}
277
278
279/// InlinePatternFragments - If this pattern refers to any pattern
280/// fragments, inline them into place, giving us a pattern without any
281/// PatFrag references.
282TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
283 if (isLeaf()) return this; // nothing to do.
284 Record *Op = getOperator();
285
286 if (!Op->isSubClassOf("PatFrag")) {
287 // Just recursively inline children nodes.
288 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
289 setChild(i, getChild(i)->InlinePatternFragments(TP));
290 return this;
291 }
292
293 // Otherwise, we found a reference to a fragment. First, look up its
294 // TreePattern record.
295 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
296
297 // Verify that we are passing the right number of operands.
298 if (Frag->getNumArgs() != Children.size())
299 TP.error("'" + Op->getName() + "' fragment requires " +
300 utostr(Frag->getNumArgs()) + " operands!");
301
Chris Lattner37937092005-09-09 01:15:01 +0000302 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000303
304 // Resolve formal arguments to their actual value.
305 if (Frag->getNumArgs()) {
306 // Compute the map of formal to actual arguments.
307 std::map<std::string, TreePatternNode*> ArgMap;
308 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
309 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
310
311 FragTree->SubstituteFormalArguments(ArgMap);
312 }
313
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000314 FragTree->setName(getName());
315
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000316 // Get a new copy of this fragment to stitch into here.
317 //delete this; // FIXME: implement refcounting!
318 return FragTree;
319}
320
Chris Lattner32707602005-09-08 23:22:48 +0000321/// ApplyTypeConstraints - Apply all of the type constraints relevent to
322/// this node and its children in the tree. This returns true if it makes a
323/// change, false otherwise. If a type contradiction is found, throw an
324/// exception.
325bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
326 if (isLeaf()) return false;
327
328 // special handling for set, which isn't really an SDNode.
329 if (getOperator()->getName() == "set") {
330 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
331 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
332 MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
333
334 // Types of operands must match.
335 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
336 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
337 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
338 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000339 } else if (getOperator()->isSubClassOf("SDNode")) {
340 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
341
342 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
343 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
344 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
345 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000346 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000347 const DAGInstruction &Inst =
348 TP.getDAGISelEmitter().getInstruction(getOperator());
349
Chris Lattnera28aec12005-09-15 22:23:50 +0000350 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
351 // Apply the result type to the node
352 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
353
354 if (getNumChildren() != Inst.getNumOperands())
355 TP.error("Instruction '" + getOperator()->getName() + " expects " +
356 utostr(Inst.getNumOperands()) + " operands, not " +
357 utostr(getNumChildren()) + " operands!");
358 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
359 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
360 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
361 }
362 return MadeChange;
363 } else {
364 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
365
366 // Node transforms always take one operand, and take and return the same
367 // type.
368 if (getNumChildren() != 1)
369 TP.error("Node transform '" + getOperator()->getName() +
370 "' requires one operand!");
371 bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
372 MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
373 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000374 }
Chris Lattner32707602005-09-08 23:22:48 +0000375}
376
Chris Lattnere97603f2005-09-28 19:27:25 +0000377/// canPatternMatch - If it is impossible for this pattern to match on this
378/// target, fill in Reason and return false. Otherwise, return true. This is
379/// used as a santity check for .td files (to prevent people from writing stuff
380/// that can never possibly work), and to prevent the pattern permuter from
381/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000382bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000383 if (isLeaf()) return true;
384
385 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
386 if (!getChild(i)->canPatternMatch(Reason, ISE))
387 return false;
388
389 // If this node is a commutative operator, check that the LHS isn't an
390 // immediate.
391 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
392 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
393 // Scan all of the operands of the node and make sure that only the last one
394 // is a constant node.
395 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
396 if (!getChild(i)->isLeaf() &&
397 getChild(i)->getOperator()->getName() == "imm") {
398 Reason = "Immediate value must be on the RHS of commutative operators!";
399 return false;
400 }
401 }
402
403 return true;
404}
Chris Lattner32707602005-09-08 23:22:48 +0000405
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000406//===----------------------------------------------------------------------===//
407// TreePattern implementation
408//
409
Chris Lattnera28aec12005-09-15 22:23:50 +0000410TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000411 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000412 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
413 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000414}
415
Chris Lattnera28aec12005-09-15 22:23:50 +0000416TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
417 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
418 Trees.push_back(ParseTreePattern(Pat));
419}
420
421TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
422 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
423 Trees.push_back(Pat);
424}
425
426
427
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000428void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000429 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000430 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000431}
432
433/// getIntrinsicType - Check to see if the specified record has an intrinsic
434/// type which should be applied to it. This infer the type of register
435/// references from the register file information, for example.
436///
437MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
438 // Check to see if this is a register or a register class...
439 if (R->isSubClassOf("RegisterClass"))
440 return getValueType(R->getValueAsDef("RegType"));
441 else if (R->isSubClassOf("PatFrag")) {
Chris Lattner37937092005-09-09 01:15:01 +0000442 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000443 return MVT::LAST_VALUETYPE;
444 } else if (R->isSubClassOf("Register")) {
445 assert(0 && "Explicit registers not handled here yet!\n");
446 return MVT::LAST_VALUETYPE;
447 } else if (R->isSubClassOf("ValueType")) {
448 // Using a VTSDNode.
449 return MVT::Other;
450 } else if (R->getName() == "node") {
451 // Placeholder.
452 return MVT::LAST_VALUETYPE;
453 }
454
Chris Lattner72fe91c2005-09-24 00:40:24 +0000455 error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000456 return MVT::Other;
457}
458
459TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
460 Record *Operator = Dag->getNodeType();
461
462 if (Operator->isSubClassOf("ValueType")) {
463 // If the operator is a ValueType, then this must be "type cast" of a leaf
464 // node.
465 if (Dag->getNumArgs() != 1)
466 error("Type cast only valid for a leaf node!");
467
468 Init *Arg = Dag->getArg(0);
469 TreePatternNode *New;
470 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000471 Record *R = DI->getDef();
472 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
473 Dag->setArg(0, new DagInit(R,
474 std::vector<std::pair<Init*, std::string> >()));
475 TreePatternNode *TPN = ParseTreePattern(Dag);
476 TPN->setName(Dag->getArgName(0));
477 return TPN;
478 }
479
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000480 New = new TreePatternNode(DI);
481 // If it's a regclass or something else known, set the type.
482 New->setType(getIntrinsicType(DI->getDef()));
483 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
484 New = ParseTreePattern(DI);
485 } else {
486 Arg->dump();
487 error("Unknown leaf value for tree pattern!");
488 return 0;
489 }
490
Chris Lattner32707602005-09-08 23:22:48 +0000491 // Apply the type cast.
492 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000493 return New;
494 }
495
496 // Verify that this is something that makes sense for an operator.
497 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000498 !Operator->isSubClassOf("Instruction") &&
499 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000500 Operator->getName() != "set")
501 error("Unrecognized node '" + Operator->getName() + "'!");
502
503 std::vector<TreePatternNode*> Children;
504
505 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
506 Init *Arg = Dag->getArg(i);
507 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
508 Children.push_back(ParseTreePattern(DI));
509 Children.back()->setName(Dag->getArgName(i));
510 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
511 Record *R = DefI->getDef();
512 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
513 // TreePatternNode if its own.
514 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
515 Dag->setArg(i, new DagInit(R,
516 std::vector<std::pair<Init*, std::string> >()));
517 --i; // Revisit this node...
518 } else {
519 TreePatternNode *Node = new TreePatternNode(DefI);
520 Node->setName(Dag->getArgName(i));
521 Children.push_back(Node);
522
523 // If it's a regclass or something else known, set the type.
524 Node->setType(getIntrinsicType(R));
525
526 // Input argument?
527 if (R->getName() == "node") {
528 if (Dag->getArgName(i).empty())
529 error("'node' argument requires a name to match with operand list");
530 Args.push_back(Dag->getArgName(i));
531 }
532 }
533 } else {
534 Arg->dump();
535 error("Unknown leaf value for tree pattern!");
536 }
537 }
538
539 return new TreePatternNode(Operator, Children);
540}
541
Chris Lattner32707602005-09-08 23:22:48 +0000542/// InferAllTypes - Infer/propagate as many types throughout the expression
543/// patterns as possible. Return true if all types are infered, false
544/// otherwise. Throw an exception if a type contradiction is found.
545bool TreePattern::InferAllTypes() {
546 bool MadeChange = true;
547 while (MadeChange) {
548 MadeChange = false;
549 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
550 MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
551 }
552
553 bool HasUnresolvedTypes = false;
554 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
555 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
556 return !HasUnresolvedTypes;
557}
558
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000559void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000560 OS << getRecord()->getName();
561 if (!Args.empty()) {
562 OS << "(" << Args[0];
563 for (unsigned i = 1, e = Args.size(); i != e; ++i)
564 OS << ", " << Args[i];
565 OS << ")";
566 }
567 OS << ": ";
568
569 if (Trees.size() > 1)
570 OS << "[\n";
571 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
572 OS << "\t";
573 Trees[i]->print(OS);
574 OS << "\n";
575 }
576
577 if (Trees.size() > 1)
578 OS << "]\n";
579}
580
581void TreePattern::dump() const { print(std::cerr); }
582
583
584
585//===----------------------------------------------------------------------===//
586// DAGISelEmitter implementation
587//
588
Chris Lattnerca559d02005-09-08 21:03:01 +0000589// Parse all of the SDNode definitions for the target, populating SDNodes.
590void DAGISelEmitter::ParseNodeInfo() {
591 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
592 while (!Nodes.empty()) {
593 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
594 Nodes.pop_back();
595 }
596}
597
Chris Lattner24eeeb82005-09-13 21:51:00 +0000598/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
599/// map, and emit them to the file as functions.
600void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
601 OS << "\n// Node transformations.\n";
602 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
603 while (!Xforms.empty()) {
604 Record *XFormNode = Xforms.back();
605 Record *SDNode = XFormNode->getValueAsDef("Opcode");
606 std::string Code = XFormNode->getValueAsCode("XFormFunction");
607 SDNodeXForms.insert(std::make_pair(XFormNode,
608 std::make_pair(SDNode, Code)));
609
Chris Lattner1048b7a2005-09-13 22:03:37 +0000610 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000611 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
612 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
613
Chris Lattner1048b7a2005-09-13 22:03:37 +0000614 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000615 << "(SDNode *" << C2 << ") {\n";
616 if (ClassName != "SDNode")
617 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
618 OS << Code << "\n}\n";
619 }
620
621 Xforms.pop_back();
622 }
623}
624
625
626
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000627/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
628/// file, building up the PatternFragments map. After we've collected them all,
629/// inline fragments together as necessary, so that there are no references left
630/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000631///
632/// This also emits all of the predicate functions to the output file.
633///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000634void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000635 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
636
637 // First step, parse all of the fragments and emit predicate functions.
638 OS << "\n// Predicate functions.\n";
639 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000640 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
641 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000642 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000643
644 // Validate the argument list, converting it to map, to discard duplicates.
645 std::vector<std::string> &Args = P->getArgList();
646 std::set<std::string> OperandsMap(Args.begin(), Args.end());
647
648 if (OperandsMap.count(""))
649 P->error("Cannot have unnamed 'node' values in pattern fragment!");
650
651 // Parse the operands list.
652 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
653 if (OpsList->getNodeType()->getName() != "ops")
654 P->error("Operands list should start with '(ops ... '!");
655
656 // Copy over the arguments.
657 Args.clear();
658 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
659 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
660 static_cast<DefInit*>(OpsList->getArg(j))->
661 getDef()->getName() != "node")
662 P->error("Operands list should all be 'node' values.");
663 if (OpsList->getArgName(j).empty())
664 P->error("Operands list should have names for each operand!");
665 if (!OperandsMap.count(OpsList->getArgName(j)))
666 P->error("'" + OpsList->getArgName(j) +
667 "' does not occur in pattern or was multiply specified!");
668 OperandsMap.erase(OpsList->getArgName(j));
669 Args.push_back(OpsList->getArgName(j));
670 }
671
672 if (!OperandsMap.empty())
673 P->error("Operands list does not contain an entry for operand '" +
674 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000675
676 // If there is a code init for this fragment, emit the predicate code and
677 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000678 std::string Code = Fragments[i]->getValueAsCode("Predicate");
679 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000680 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000681 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000682 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000683 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
684
Chris Lattner1048b7a2005-09-13 22:03:37 +0000685 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000686 << "(SDNode *" << C2 << ") {\n";
687 if (ClassName != "SDNode")
688 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000689 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000690 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000691 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000692
693 // If there is a node transformation corresponding to this, keep track of
694 // it.
695 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
696 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000697 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000698 }
699
700 OS << "\n\n";
701
702 // Now that we've parsed all of the tree fragments, do a closure on them so
703 // that there are not references to PatFrags left inside of them.
704 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
705 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000706 TreePattern *ThePat = I->second;
707 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000708
Chris Lattner32707602005-09-08 23:22:48 +0000709 // Infer as many types as possible. Don't worry about it if we don't infer
710 // all of them, some may depend on the inputs of the pattern.
711 try {
712 ThePat->InferAllTypes();
713 } catch (...) {
714 // If this pattern fragment is not supported by this target (no types can
715 // satisfy its constraints), just ignore it. If the bogus pattern is
716 // actually used by instructions, the type consistency error will be
717 // reported there.
718 }
719
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000720 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000721 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000722 }
723}
724
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000725/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000726/// instruction input. Return true if this is a real use.
727static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000728 std::map<std::string, TreePatternNode*> &InstInputs) {
729 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000730 if (Pat->getName().empty()) {
731 if (Pat->isLeaf()) {
732 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
733 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
734 I->error("Input " + DI->getDef()->getName() + " must be named!");
735
736 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000737 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000738 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000739
740 Record *Rec;
741 if (Pat->isLeaf()) {
742 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
743 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
744 Rec = DI->getDef();
745 } else {
746 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
747 Rec = Pat->getOperator();
748 }
749
750 TreePatternNode *&Slot = InstInputs[Pat->getName()];
751 if (!Slot) {
752 Slot = Pat;
753 } else {
754 Record *SlotRec;
755 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000756 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000757 } else {
758 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
759 SlotRec = Slot->getOperator();
760 }
761
762 // Ensure that the inputs agree if we've already seen this input.
763 if (Rec != SlotRec)
764 I->error("All $" + Pat->getName() + " inputs must agree with each other");
765 if (Slot->getType() != Pat->getType())
766 I->error("All $" + Pat->getName() + " inputs must agree with each other");
767 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000768 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000769}
770
771/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
772/// part of "I", the instruction), computing the set of inputs and outputs of
773/// the pattern. Report errors if we see anything naughty.
774void DAGISelEmitter::
775FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
776 std::map<std::string, TreePatternNode*> &InstInputs,
777 std::map<std::string, Record*> &InstResults) {
778 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000779 bool isUse = HandleUse(I, Pat, InstInputs);
780 if (!isUse && Pat->getTransformFn())
781 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000782 return;
783 } else if (Pat->getOperator()->getName() != "set") {
784 // If this is not a set, verify that the children nodes are not void typed,
785 // and recurse.
786 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
787 if (Pat->getChild(i)->getType() == MVT::isVoid)
788 I->error("Cannot have void nodes inside of patterns!");
789 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
790 }
791
792 // If this is a non-leaf node with no children, treat it basically as if
793 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000794 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000795 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000796 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000797
Chris Lattnerf1311842005-09-14 23:05:13 +0000798 if (!isUse && Pat->getTransformFn())
799 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000800 return;
801 }
802
803 // Otherwise, this is a set, validate and collect instruction results.
804 if (Pat->getNumChildren() == 0)
805 I->error("set requires operands!");
806 else if (Pat->getNumChildren() & 1)
807 I->error("set requires an even number of operands");
808
Chris Lattnerf1311842005-09-14 23:05:13 +0000809 if (Pat->getTransformFn())
810 I->error("Cannot specify a transform function on a set node!");
811
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000812 // Check the set destinations.
813 unsigned NumValues = Pat->getNumChildren()/2;
814 for (unsigned i = 0; i != NumValues; ++i) {
815 TreePatternNode *Dest = Pat->getChild(i);
816 if (!Dest->isLeaf())
817 I->error("set destination should be a virtual register!");
818
819 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
820 if (!Val)
821 I->error("set destination should be a virtual register!");
822
823 if (!Val->getDef()->isSubClassOf("RegisterClass"))
824 I->error("set destination should be a virtual register!");
825 if (Dest->getName().empty())
826 I->error("set destination must have a name!");
827 if (InstResults.count(Dest->getName()))
828 I->error("cannot set '" + Dest->getName() +"' multiple times");
829 InstResults[Dest->getName()] = Val->getDef();
830
831 // Verify and collect info from the computation.
832 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
833 InstInputs, InstResults);
834 }
835}
836
837
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000838/// ParseInstructions - Parse all of the instructions, inlining and resolving
839/// any fragments involved. This populates the Instructions list with fully
840/// resolved instructions.
841void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000842 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
843
844 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
845 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
846 continue; // no pattern yet, ignore it.
847
848 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
849 if (LI->getSize() == 0) continue; // no pattern.
850
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000851 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000852 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000853 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +0000854 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000855
Chris Lattner95f6b762005-09-08 23:26:30 +0000856 // Infer as many types as possible. If we cannot infer all of them, we can
857 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000858 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +0000859 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000860
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000861 // InstInputs - Keep track of all of the inputs of the instruction, along
862 // with the record they are declared as.
863 std::map<std::string, TreePatternNode*> InstInputs;
864
865 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000866 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000867 std::map<std::string, Record*> InstResults;
868
Chris Lattner1f39e292005-09-14 00:09:24 +0000869 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000870 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +0000871 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
872 TreePatternNode *Pat = I->getTree(j);
873 if (Pat->getType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000874 I->dump();
875 I->error("Top-level forms in instruction pattern should have"
876 " void types");
877 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000878
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000879 // Find inputs and outputs, and verify the structure of the uses/defs.
880 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +0000881 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000882
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000883 // Now that we have inputs and outputs of the pattern, inspect the operands
884 // list for the instruction. This determines the order that operands are
885 // added to the machine instruction the node corresponds to.
886 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +0000887
888 // Parse the operands list from the (ops) list, validating it.
889 std::vector<std::string> &Args = I->getArgList();
890 assert(Args.empty() && "Args list should still be empty here!");
891 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
892
893 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +0000894 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +0000895 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +0000896 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000897 I->error("'" + InstResults.begin()->first +
898 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +0000899 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +0000900
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000901 // Check that it exists in InstResults.
902 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +0000903 if (R == 0)
904 I->error("Operand $" + OpName + " should be a set destination: all "
905 "outputs must occur before inputs in operand list!");
906
907 if (CGI.OperandList[i].Rec != R)
908 I->error("Operand $" + OpName + " class mismatch!");
909
Chris Lattnerae6d8282005-09-15 21:51:12 +0000910 // Remember the return type.
911 ResultTypes.push_back(CGI.OperandList[i].Ty);
912
Chris Lattner39e8af92005-09-14 18:19:25 +0000913 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000914 InstResults.erase(OpName);
915 }
916
Chris Lattner0b592252005-09-14 21:59:34 +0000917 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
918 // the copy while we're checking the inputs.
919 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +0000920
921 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +0000922 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000923 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
924 const std::string &OpName = CGI.OperandList[i].Name;
925 if (OpName.empty())
926 I->error("Operand #" + utostr(i) + " in operands list has no name!");
927
Chris Lattner0b592252005-09-14 21:59:34 +0000928 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000929 I->error("Operand $" + OpName +
930 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +0000931 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +0000932 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000933 if (CGI.OperandList[i].Ty != InVal->getType())
934 I->error("Operand $" + OpName +
935 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +0000936 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +0000937
Chris Lattner2175c182005-09-14 23:01:59 +0000938 // Construct the result for the dest-pattern operand list.
939 TreePatternNode *OpNode = InVal->clone();
940
941 // No predicate is useful on the result.
942 OpNode->setPredicateFn("");
943
944 // Promote the xform function to be an explicit node if set.
945 if (Record *Xform = OpNode->getTransformFn()) {
946 OpNode->setTransformFn(0);
947 std::vector<TreePatternNode*> Children;
948 Children.push_back(OpNode);
949 OpNode = new TreePatternNode(Xform, Children);
950 }
951
952 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +0000953 }
954
Chris Lattner0b592252005-09-14 21:59:34 +0000955 if (!InstInputsCheck.empty())
956 I->error("Input operand $" + InstInputsCheck.begin()->first +
957 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +0000958
959 TreePatternNode *ResultPattern =
960 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +0000961
962 // Create and insert the instruction.
963 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
964 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
965
966 // Use a temporary tree pattern to infer all types and make sure that the
967 // constructed result is correct. This depends on the instruction already
968 // being inserted into the Instructions map.
969 TreePattern Temp(I->getRecord(), ResultPattern, *this);
970 Temp.InferAllTypes();
971
972 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
973 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +0000974
Chris Lattner32707602005-09-08 23:22:48 +0000975 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000976 }
Chris Lattner1f39e292005-09-14 00:09:24 +0000977
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000978 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +0000979 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
980 E = Instructions.end(); II != E; ++II) {
981 TreePattern *I = II->second.getPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +0000982
983 if (I->getNumTrees() != 1) {
984 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
985 continue;
986 }
987 TreePatternNode *Pattern = I->getTree(0);
988 if (Pattern->getOperator()->getName() != "set")
989 continue; // Not a set (store or something?)
990
991 if (Pattern->getNumChildren() != 2)
992 continue; // Not a set of a single value (not handled so far)
993
994 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +0000995
996 std::string Reason;
997 if (!SrcPattern->canPatternMatch(Reason, *this))
998 I->error("Instruction can never match: " + Reason);
999
Chris Lattnerae5b3502005-09-15 21:57:35 +00001000 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001001 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001002 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001003}
1004
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001005void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001006 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001007
Chris Lattnerabbb6052005-09-15 21:42:00 +00001008 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001009 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1010 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001011
Chris Lattnerabbb6052005-09-15 21:42:00 +00001012 // Inline pattern fragments into it.
1013 Pattern->InlinePatternFragments();
1014
1015 // Infer as many types as possible. If we cannot infer all of them, we can
1016 // never do anything with this pattern: report it to the user.
1017 if (!Pattern->InferAllTypes())
1018 Pattern->error("Could not infer all types in pattern!");
1019
1020 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1021 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001022
1023 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +00001024 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001025
1026 // Inline pattern fragments into it.
1027 Result->InlinePatternFragments();
1028
1029 // Infer as many types as possible. If we cannot infer all of them, we can
1030 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001031 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001032 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001033
1034 if (Result->getNumTrees() != 1)
1035 Result->error("Cannot handle instructions producing instructions "
1036 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001037
1038 std::string Reason;
1039 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1040 Pattern->error("Pattern can never match: " + Reason);
1041
Chris Lattnerabbb6052005-09-15 21:42:00 +00001042 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1043 Result->getOnlyTree()));
1044 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001045
1046 DEBUG(std::cerr << "\n\nPARSED PATTERNS TO MATCH:\n\n";
1047 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1048 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1049 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1050 std::cerr << "\n";
1051 });
1052}
1053
Chris Lattnere97603f2005-09-28 19:27:25 +00001054// GenerateVariants - Generate variants. For example, commutative patterns can
1055// match multiple ways. Add them to PatternsToMatch as well.
1056void DAGISelEmitter::GenerateVariants() {
Chris Lattnere97603f2005-09-28 19:27:25 +00001057}
1058
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001059
Chris Lattner05814af2005-09-28 17:57:56 +00001060/// getPatternSize - Return the 'size' of this pattern. We want to match large
1061/// patterns before small ones. This is used to determine the size of a
1062/// pattern.
1063static unsigned getPatternSize(TreePatternNode *P) {
1064 assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1065 "Not a valid pattern node to size!");
1066 unsigned Size = 1; // The node itself.
1067
1068 // Count children in the count if they are also nodes.
1069 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1070 TreePatternNode *Child = P->getChild(i);
1071 if (!Child->isLeaf() && Child->getType() != MVT::Other)
1072 Size += getPatternSize(Child);
1073 }
1074
1075 return Size;
1076}
1077
1078/// getResultPatternCost - Compute the number of instructions for this pattern.
1079/// This is a temporary hack. We should really include the instruction
1080/// latencies in this calculation.
1081static unsigned getResultPatternCost(TreePatternNode *P) {
1082 if (P->isLeaf()) return 0;
1083
1084 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1085 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1086 Cost += getResultPatternCost(P->getChild(i));
1087 return Cost;
1088}
1089
1090// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1091// In particular, we want to match maximal patterns first and lowest cost within
1092// a particular complexity first.
1093struct PatternSortingPredicate {
1094 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1095 DAGISelEmitter::PatternToMatch *RHS) {
1096 unsigned LHSSize = getPatternSize(LHS->first);
1097 unsigned RHSSize = getPatternSize(RHS->first);
1098 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1099 if (LHSSize < RHSSize) return false;
1100
1101 // If the patterns have equal complexity, compare generated instruction cost
1102 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1103 }
1104};
1105
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001106/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1107/// if the match fails. At this point, we already know that the opcode for N
1108/// matches, and the SDNode for the result has the RootName specified name.
1109void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001110 const std::string &RootName,
1111 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001112 unsigned PatternNo, std::ostream &OS) {
1113 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001114
1115 // If this node has a name associated with it, capture it in VarMap. If
1116 // we already saw this in the pattern, emit code to verify dagness.
1117 if (!N->getName().empty()) {
1118 std::string &VarMapEntry = VarMap[N->getName()];
1119 if (VarMapEntry.empty()) {
1120 VarMapEntry = RootName;
1121 } else {
1122 // If we get here, this is a second reference to a specific name. Since
1123 // we already have checked that the first reference is valid, we don't
1124 // have to recursively match it, just check that it's the same as the
1125 // previously named thing.
1126 OS << " if (" << VarMapEntry << " != " << RootName
1127 << ") goto P" << PatternNo << "Fail;\n";
1128 return;
1129 }
1130 }
1131
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001132 // Emit code to load the child nodes and match their contents recursively.
1133 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001134 OS << " SDOperand " << RootName << i <<" = " << RootName
1135 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001136 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001137
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001138 if (!Child->isLeaf()) {
1139 // If it's not a leaf, recursively match.
1140 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001141 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001142 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001143 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001144 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001145 // If this child has a name associated with it, capture it in VarMap. If
1146 // we already saw this in the pattern, emit code to verify dagness.
1147 if (!Child->getName().empty()) {
1148 std::string &VarMapEntry = VarMap[Child->getName()];
1149 if (VarMapEntry.empty()) {
1150 VarMapEntry = RootName + utostr(i);
1151 } else {
1152 // If we get here, this is a second reference to a specific name. Since
1153 // we already have checked that the first reference is valid, we don't
1154 // have to recursively match it, just check that it's the same as the
1155 // previously named thing.
1156 OS << " if (" << VarMapEntry << " != " << RootName << i
1157 << ") goto P" << PatternNo << "Fail;\n";
1158 continue;
1159 }
1160 }
1161
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001162 // Handle leaves of various types.
1163 Init *LeafVal = Child->getLeafValue();
1164 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1165 if (LeafRec->isSubClassOf("RegisterClass")) {
1166 // Handle register references. Nothing to do here.
1167 } else if (LeafRec->isSubClassOf("ValueType")) {
1168 // Make sure this is the specified value type.
1169 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1170 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1171 << "Fail;\n";
1172 } else {
1173 Child->dump();
1174 assert(0 && "Unknown leaf type!");
1175 }
1176 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001177 }
1178
1179 // If there is a node predicate for this, emit the call.
1180 if (!N->getPredicateFn().empty())
1181 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001182 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001183}
1184
Chris Lattner6bc7e512005-09-26 21:53:26 +00001185/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1186/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001187unsigned DAGISelEmitter::
1188CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1189 std::map<std::string,std::string> &VariableMap,
Chris Lattner6bc7e512005-09-26 21:53:26 +00001190 std::ostream &OS) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001191 // This is something selected from the pattern we matched.
1192 if (!N->getName().empty()) {
Chris Lattner6bc7e512005-09-26 21:53:26 +00001193 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001194 assert(!Val.empty() &&
1195 "Variable referenced but not defined and not caught earlier!");
1196 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1197 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001198 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001199 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001200
1201 unsigned ResNo = Ctr++;
1202 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1203 switch (N->getType()) {
1204 default: assert(0 && "Unknown type for constant node!");
1205 case MVT::i1: OS << " bool Tmp"; break;
1206 case MVT::i8: OS << " unsigned char Tmp"; break;
1207 case MVT::i16: OS << " unsigned short Tmp"; break;
1208 case MVT::i32: OS << " unsigned Tmp"; break;
1209 case MVT::i64: OS << " uint64_t Tmp"; break;
1210 }
1211 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1212 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1213 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1214 } else {
1215 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1216 }
1217 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1218 // value if used multiple times by this pattern result.
1219 Val = "Tmp"+utostr(ResNo);
1220 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001221 }
1222
1223 if (N->isLeaf()) {
1224 N->dump();
1225 assert(0 && "Unknown leaf type!");
1226 return ~0U;
1227 }
1228
1229 Record *Op = N->getOperator();
1230 if (Op->isSubClassOf("Instruction")) {
1231 // Emit all of the operands.
1232 std::vector<unsigned> Ops;
1233 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1234 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1235
1236 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1237 unsigned ResNo = Ctr++;
1238
1239 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1240 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1241 << getEnumName(N->getType());
1242 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1243 OS << ", Tmp" << Ops[i];
1244 OS << ");\n";
1245 return ResNo;
1246 } else if (Op->isSubClassOf("SDNodeXForm")) {
1247 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1248 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1249
1250 unsigned ResNo = Ctr++;
1251 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1252 << "(Tmp" << OpVal << ".Val);\n";
1253 return ResNo;
1254 } else {
1255 N->dump();
1256 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001257 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001258 }
1259}
1260
1261
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001262/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1263/// stream to match the pattern, and generate the code for the match if it
1264/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001265void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1266 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001267 static unsigned PatternCount = 0;
1268 unsigned PatternNo = PatternCount++;
1269 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001270 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001271 OS << "\n // Emits: ";
1272 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001273 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001274 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1275 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001276
Chris Lattner8fc35682005-09-23 23:16:51 +00001277 // Emit the matcher, capturing named arguments in VariableMap.
1278 std::map<std::string,std::string> VariableMap;
1279 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001280
Chris Lattner72fe91c2005-09-24 00:40:24 +00001281 unsigned TmpNo = 0;
1282 unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
Chris Lattner296dfe32005-09-24 00:50:51 +00001283
1284 // Add the result to the map if it has multiple uses.
1285 OS << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
Chris Lattner72fe91c2005-09-24 00:40:24 +00001286 OS << " return Tmp" << Res << ";\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001287 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001288}
1289
Chris Lattner37481472005-09-26 21:59:35 +00001290
1291namespace {
1292 /// CompareByRecordName - An ordering predicate that implements less-than by
1293 /// comparing the names records.
1294 struct CompareByRecordName {
1295 bool operator()(const Record *LHS, const Record *RHS) const {
1296 // Sort by name first.
1297 if (LHS->getName() < RHS->getName()) return true;
1298 // If both names are equal, sort by pointer.
1299 return LHS->getName() == RHS->getName() && LHS < RHS;
1300 }
1301 };
1302}
1303
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001304void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1305 // Emit boilerplate.
1306 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001307 << "SDOperand SelectCode(SDOperand N) {\n"
1308 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1309 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1310 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001311 << " if (!N.Val->hasOneUse()) {\n"
1312 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1313 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1314 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001315 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001316 << " default: break;\n"
1317 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001318 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001319 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001320 << " case ISD::AssertZext: {\n"
1321 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1322 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1323 << " return Tmp0;\n"
1324 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001325
Chris Lattner81303322005-09-23 19:36:15 +00001326 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001327 std::map<Record*, std::vector<PatternToMatch*>,
1328 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001329 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1330 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1331 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001332
Chris Lattner3f7e9142005-09-23 20:52:47 +00001333 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001334 for (std::map<Record*, std::vector<PatternToMatch*>,
1335 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1336 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001337 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1338 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1339
1340 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001341
1342 // We want to emit all of the matching code now. However, we want to emit
1343 // the matches in order of minimal cost. Sort the patterns so the least
1344 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001345 std::stable_sort(Patterns.begin(), Patterns.end(),
1346 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001347
Chris Lattner3f7e9142005-09-23 20:52:47 +00001348 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1349 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001350 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001351 }
1352
1353
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001354 OS << " } // end of big switch.\n\n"
1355 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001356 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001357 << " std::cerr << '\\n';\n"
1358 << " abort();\n"
1359 << "}\n";
1360}
1361
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001362void DAGISelEmitter::run(std::ostream &OS) {
1363 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1364 " target", OS);
1365
Chris Lattner1f39e292005-09-14 00:09:24 +00001366 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1367 << "// *** instruction selector class. These functions are really "
1368 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001369
Chris Lattner296dfe32005-09-24 00:50:51 +00001370 OS << "// Instance var to keep track of multiply used nodes that have \n"
1371 << "// already been selected.\n"
1372 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1373
Chris Lattnerca559d02005-09-08 21:03:01 +00001374 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001375 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001376 ParsePatternFragments(OS);
1377 ParseInstructions();
1378 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001379
Chris Lattnere97603f2005-09-28 19:27:25 +00001380 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00001381 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00001382 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001383
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001384 // At this point, we have full information about the 'Patterns' we need to
1385 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001386 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001387 EmitInstructionSelector(OS);
1388
1389 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1390 E = PatternFragments.end(); I != E; ++I)
1391 delete I->second;
1392 PatternFragments.clear();
1393
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001394 Instructions.clear();
1395}