blob: e01e51b15a7c38ace7c26780486be182a3b192c9 [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
Chris Lattnere46e17b2005-09-29 19:28:10 +0000235/// isIsomorphicTo - Return true if this node is recursively isomorphic to
236/// the specified node. For this comparison, all of the state of the node
237/// is considered, except for the assigned name. Nodes with differing names
238/// that are otherwise identical are considered isomorphic.
239bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
240 if (N == this) return true;
241 if (N->isLeaf() != isLeaf() || getType() != N->getType() ||
242 getPredicateFn() != N->getPredicateFn() ||
243 getTransformFn() != N->getTransformFn())
244 return false;
245
246 if (isLeaf()) {
247 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
248 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
249 return DI->getDef() == NDI->getDef();
250 return getLeafValue() == N->getLeafValue();
251 }
252
253 if (N->getOperator() != getOperator() ||
254 N->getNumChildren() != getNumChildren()) return false;
255 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
256 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
257 return false;
258 return true;
259}
260
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000261/// clone - Make a copy of this tree and all of its children.
262///
263TreePatternNode *TreePatternNode::clone() const {
264 TreePatternNode *New;
265 if (isLeaf()) {
266 New = new TreePatternNode(getLeafValue());
267 } else {
268 std::vector<TreePatternNode*> CChildren;
269 CChildren.reserve(Children.size());
270 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
271 CChildren.push_back(getChild(i)->clone());
272 New = new TreePatternNode(getOperator(), CChildren);
273 }
274 New->setName(getName());
275 New->setType(getType());
276 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000277 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000278 return New;
279}
280
Chris Lattner32707602005-09-08 23:22:48 +0000281/// SubstituteFormalArguments - Replace the formal arguments in this tree
282/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000283void TreePatternNode::
284SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
285 if (isLeaf()) return;
286
287 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
288 TreePatternNode *Child = getChild(i);
289 if (Child->isLeaf()) {
290 Init *Val = Child->getLeafValue();
291 if (dynamic_cast<DefInit*>(Val) &&
292 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
293 // We found a use of a formal argument, replace it with its value.
294 Child = ArgMap[Child->getName()];
295 assert(Child && "Couldn't find formal argument!");
296 setChild(i, Child);
297 }
298 } else {
299 getChild(i)->SubstituteFormalArguments(ArgMap);
300 }
301 }
302}
303
304
305/// InlinePatternFragments - If this pattern refers to any pattern
306/// fragments, inline them into place, giving us a pattern without any
307/// PatFrag references.
308TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
309 if (isLeaf()) return this; // nothing to do.
310 Record *Op = getOperator();
311
312 if (!Op->isSubClassOf("PatFrag")) {
313 // Just recursively inline children nodes.
314 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
315 setChild(i, getChild(i)->InlinePatternFragments(TP));
316 return this;
317 }
318
319 // Otherwise, we found a reference to a fragment. First, look up its
320 // TreePattern record.
321 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
322
323 // Verify that we are passing the right number of operands.
324 if (Frag->getNumArgs() != Children.size())
325 TP.error("'" + Op->getName() + "' fragment requires " +
326 utostr(Frag->getNumArgs()) + " operands!");
327
Chris Lattner37937092005-09-09 01:15:01 +0000328 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000329
330 // Resolve formal arguments to their actual value.
331 if (Frag->getNumArgs()) {
332 // Compute the map of formal to actual arguments.
333 std::map<std::string, TreePatternNode*> ArgMap;
334 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
335 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
336
337 FragTree->SubstituteFormalArguments(ArgMap);
338 }
339
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000340 FragTree->setName(getName());
341
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000342 // Get a new copy of this fragment to stitch into here.
343 //delete this; // FIXME: implement refcounting!
344 return FragTree;
345}
346
Chris Lattner32707602005-09-08 23:22:48 +0000347/// ApplyTypeConstraints - Apply all of the type constraints relevent to
348/// this node and its children in the tree. This returns true if it makes a
349/// change, false otherwise. If a type contradiction is found, throw an
350/// exception.
351bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
352 if (isLeaf()) return false;
353
354 // special handling for set, which isn't really an SDNode.
355 if (getOperator()->getName() == "set") {
356 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
357 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
358 MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
359
360 // Types of operands must match.
361 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
362 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
363 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
364 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000365 } else if (getOperator()->isSubClassOf("SDNode")) {
366 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
367
368 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
369 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
370 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
371 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000372 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000373 const DAGInstruction &Inst =
374 TP.getDAGISelEmitter().getInstruction(getOperator());
375
Chris Lattnera28aec12005-09-15 22:23:50 +0000376 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
377 // Apply the result type to the node
378 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
379
380 if (getNumChildren() != Inst.getNumOperands())
381 TP.error("Instruction '" + getOperator()->getName() + " expects " +
382 utostr(Inst.getNumOperands()) + " operands, not " +
383 utostr(getNumChildren()) + " operands!");
384 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
385 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
386 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
387 }
388 return MadeChange;
389 } else {
390 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
391
392 // Node transforms always take one operand, and take and return the same
393 // type.
394 if (getNumChildren() != 1)
395 TP.error("Node transform '" + getOperator()->getName() +
396 "' requires one operand!");
397 bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
398 MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
399 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000400 }
Chris Lattner32707602005-09-08 23:22:48 +0000401}
402
Chris Lattnere97603f2005-09-28 19:27:25 +0000403/// canPatternMatch - If it is impossible for this pattern to match on this
404/// target, fill in Reason and return false. Otherwise, return true. This is
405/// used as a santity check for .td files (to prevent people from writing stuff
406/// that can never possibly work), and to prevent the pattern permuter from
407/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000408bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000409 if (isLeaf()) return true;
410
411 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
412 if (!getChild(i)->canPatternMatch(Reason, ISE))
413 return false;
414
415 // If this node is a commutative operator, check that the LHS isn't an
416 // immediate.
417 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
418 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
419 // Scan all of the operands of the node and make sure that only the last one
420 // is a constant node.
421 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
422 if (!getChild(i)->isLeaf() &&
423 getChild(i)->getOperator()->getName() == "imm") {
424 Reason = "Immediate value must be on the RHS of commutative operators!";
425 return false;
426 }
427 }
428
429 return true;
430}
Chris Lattner32707602005-09-08 23:22:48 +0000431
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000432//===----------------------------------------------------------------------===//
433// TreePattern implementation
434//
435
Chris Lattnera28aec12005-09-15 22:23:50 +0000436TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000437 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000438 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
439 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000440}
441
Chris Lattnera28aec12005-09-15 22:23:50 +0000442TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
443 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
444 Trees.push_back(ParseTreePattern(Pat));
445}
446
447TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
448 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
449 Trees.push_back(Pat);
450}
451
452
453
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000454void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000455 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000456 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000457}
458
459/// getIntrinsicType - Check to see if the specified record has an intrinsic
460/// type which should be applied to it. This infer the type of register
461/// references from the register file information, for example.
462///
463MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
464 // Check to see if this is a register or a register class...
465 if (R->isSubClassOf("RegisterClass"))
466 return getValueType(R->getValueAsDef("RegType"));
467 else if (R->isSubClassOf("PatFrag")) {
Chris Lattner37937092005-09-09 01:15:01 +0000468 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000469 return MVT::LAST_VALUETYPE;
470 } else if (R->isSubClassOf("Register")) {
471 assert(0 && "Explicit registers not handled here yet!\n");
472 return MVT::LAST_VALUETYPE;
473 } else if (R->isSubClassOf("ValueType")) {
474 // Using a VTSDNode.
475 return MVT::Other;
476 } else if (R->getName() == "node") {
477 // Placeholder.
478 return MVT::LAST_VALUETYPE;
479 }
480
Chris Lattner72fe91c2005-09-24 00:40:24 +0000481 error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000482 return MVT::Other;
483}
484
485TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
486 Record *Operator = Dag->getNodeType();
487
488 if (Operator->isSubClassOf("ValueType")) {
489 // If the operator is a ValueType, then this must be "type cast" of a leaf
490 // node.
491 if (Dag->getNumArgs() != 1)
492 error("Type cast only valid for a leaf node!");
493
494 Init *Arg = Dag->getArg(0);
495 TreePatternNode *New;
496 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000497 Record *R = DI->getDef();
498 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
499 Dag->setArg(0, new DagInit(R,
500 std::vector<std::pair<Init*, std::string> >()));
501 TreePatternNode *TPN = ParseTreePattern(Dag);
502 TPN->setName(Dag->getArgName(0));
503 return TPN;
504 }
505
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000506 New = new TreePatternNode(DI);
507 // If it's a regclass or something else known, set the type.
508 New->setType(getIntrinsicType(DI->getDef()));
509 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
510 New = ParseTreePattern(DI);
511 } else {
512 Arg->dump();
513 error("Unknown leaf value for tree pattern!");
514 return 0;
515 }
516
Chris Lattner32707602005-09-08 23:22:48 +0000517 // Apply the type cast.
518 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000519 return New;
520 }
521
522 // Verify that this is something that makes sense for an operator.
523 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000524 !Operator->isSubClassOf("Instruction") &&
525 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000526 Operator->getName() != "set")
527 error("Unrecognized node '" + Operator->getName() + "'!");
528
529 std::vector<TreePatternNode*> Children;
530
531 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
532 Init *Arg = Dag->getArg(i);
533 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
534 Children.push_back(ParseTreePattern(DI));
535 Children.back()->setName(Dag->getArgName(i));
536 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
537 Record *R = DefI->getDef();
538 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
539 // TreePatternNode if its own.
540 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
541 Dag->setArg(i, new DagInit(R,
542 std::vector<std::pair<Init*, std::string> >()));
543 --i; // Revisit this node...
544 } else {
545 TreePatternNode *Node = new TreePatternNode(DefI);
546 Node->setName(Dag->getArgName(i));
547 Children.push_back(Node);
548
549 // If it's a regclass or something else known, set the type.
550 Node->setType(getIntrinsicType(R));
551
552 // Input argument?
553 if (R->getName() == "node") {
554 if (Dag->getArgName(i).empty())
555 error("'node' argument requires a name to match with operand list");
556 Args.push_back(Dag->getArgName(i));
557 }
558 }
559 } else {
560 Arg->dump();
561 error("Unknown leaf value for tree pattern!");
562 }
563 }
564
565 return new TreePatternNode(Operator, Children);
566}
567
Chris Lattner32707602005-09-08 23:22:48 +0000568/// InferAllTypes - Infer/propagate as many types throughout the expression
569/// patterns as possible. Return true if all types are infered, false
570/// otherwise. Throw an exception if a type contradiction is found.
571bool TreePattern::InferAllTypes() {
572 bool MadeChange = true;
573 while (MadeChange) {
574 MadeChange = false;
575 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
576 MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
577 }
578
579 bool HasUnresolvedTypes = false;
580 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
581 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
582 return !HasUnresolvedTypes;
583}
584
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000585void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000586 OS << getRecord()->getName();
587 if (!Args.empty()) {
588 OS << "(" << Args[0];
589 for (unsigned i = 1, e = Args.size(); i != e; ++i)
590 OS << ", " << Args[i];
591 OS << ")";
592 }
593 OS << ": ";
594
595 if (Trees.size() > 1)
596 OS << "[\n";
597 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
598 OS << "\t";
599 Trees[i]->print(OS);
600 OS << "\n";
601 }
602
603 if (Trees.size() > 1)
604 OS << "]\n";
605}
606
607void TreePattern::dump() const { print(std::cerr); }
608
609
610
611//===----------------------------------------------------------------------===//
612// DAGISelEmitter implementation
613//
614
Chris Lattnerca559d02005-09-08 21:03:01 +0000615// Parse all of the SDNode definitions for the target, populating SDNodes.
616void DAGISelEmitter::ParseNodeInfo() {
617 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
618 while (!Nodes.empty()) {
619 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
620 Nodes.pop_back();
621 }
622}
623
Chris Lattner24eeeb82005-09-13 21:51:00 +0000624/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
625/// map, and emit them to the file as functions.
626void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
627 OS << "\n// Node transformations.\n";
628 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
629 while (!Xforms.empty()) {
630 Record *XFormNode = Xforms.back();
631 Record *SDNode = XFormNode->getValueAsDef("Opcode");
632 std::string Code = XFormNode->getValueAsCode("XFormFunction");
633 SDNodeXForms.insert(std::make_pair(XFormNode,
634 std::make_pair(SDNode, Code)));
635
Chris Lattner1048b7a2005-09-13 22:03:37 +0000636 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000637 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
638 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
639
Chris Lattner1048b7a2005-09-13 22:03:37 +0000640 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000641 << "(SDNode *" << C2 << ") {\n";
642 if (ClassName != "SDNode")
643 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
644 OS << Code << "\n}\n";
645 }
646
647 Xforms.pop_back();
648 }
649}
650
651
652
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000653/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
654/// file, building up the PatternFragments map. After we've collected them all,
655/// inline fragments together as necessary, so that there are no references left
656/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000657///
658/// This also emits all of the predicate functions to the output file.
659///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000660void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000661 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
662
663 // First step, parse all of the fragments and emit predicate functions.
664 OS << "\n// Predicate functions.\n";
665 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000666 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
667 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000668 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000669
670 // Validate the argument list, converting it to map, to discard duplicates.
671 std::vector<std::string> &Args = P->getArgList();
672 std::set<std::string> OperandsMap(Args.begin(), Args.end());
673
674 if (OperandsMap.count(""))
675 P->error("Cannot have unnamed 'node' values in pattern fragment!");
676
677 // Parse the operands list.
678 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
679 if (OpsList->getNodeType()->getName() != "ops")
680 P->error("Operands list should start with '(ops ... '!");
681
682 // Copy over the arguments.
683 Args.clear();
684 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
685 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
686 static_cast<DefInit*>(OpsList->getArg(j))->
687 getDef()->getName() != "node")
688 P->error("Operands list should all be 'node' values.");
689 if (OpsList->getArgName(j).empty())
690 P->error("Operands list should have names for each operand!");
691 if (!OperandsMap.count(OpsList->getArgName(j)))
692 P->error("'" + OpsList->getArgName(j) +
693 "' does not occur in pattern or was multiply specified!");
694 OperandsMap.erase(OpsList->getArgName(j));
695 Args.push_back(OpsList->getArgName(j));
696 }
697
698 if (!OperandsMap.empty())
699 P->error("Operands list does not contain an entry for operand '" +
700 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000701
702 // If there is a code init for this fragment, emit the predicate code and
703 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000704 std::string Code = Fragments[i]->getValueAsCode("Predicate");
705 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000706 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000707 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000708 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000709 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
710
Chris Lattner1048b7a2005-09-13 22:03:37 +0000711 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000712 << "(SDNode *" << C2 << ") {\n";
713 if (ClassName != "SDNode")
714 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000715 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000716 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000717 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000718
719 // If there is a node transformation corresponding to this, keep track of
720 // it.
721 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
722 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000723 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000724 }
725
726 OS << "\n\n";
727
728 // Now that we've parsed all of the tree fragments, do a closure on them so
729 // that there are not references to PatFrags left inside of them.
730 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
731 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000732 TreePattern *ThePat = I->second;
733 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000734
Chris Lattner32707602005-09-08 23:22:48 +0000735 // Infer as many types as possible. Don't worry about it if we don't infer
736 // all of them, some may depend on the inputs of the pattern.
737 try {
738 ThePat->InferAllTypes();
739 } catch (...) {
740 // If this pattern fragment is not supported by this target (no types can
741 // satisfy its constraints), just ignore it. If the bogus pattern is
742 // actually used by instructions, the type consistency error will be
743 // reported there.
744 }
745
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000746 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000747 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000748 }
749}
750
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000751/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000752/// instruction input. Return true if this is a real use.
753static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000754 std::map<std::string, TreePatternNode*> &InstInputs) {
755 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000756 if (Pat->getName().empty()) {
757 if (Pat->isLeaf()) {
758 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
759 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
760 I->error("Input " + DI->getDef()->getName() + " must be named!");
761
762 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000763 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000764 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000765
766 Record *Rec;
767 if (Pat->isLeaf()) {
768 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
769 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
770 Rec = DI->getDef();
771 } else {
772 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
773 Rec = Pat->getOperator();
774 }
775
776 TreePatternNode *&Slot = InstInputs[Pat->getName()];
777 if (!Slot) {
778 Slot = Pat;
779 } else {
780 Record *SlotRec;
781 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000782 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000783 } else {
784 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
785 SlotRec = Slot->getOperator();
786 }
787
788 // Ensure that the inputs agree if we've already seen this input.
789 if (Rec != SlotRec)
790 I->error("All $" + Pat->getName() + " inputs must agree with each other");
791 if (Slot->getType() != Pat->getType())
792 I->error("All $" + Pat->getName() + " inputs must agree with each other");
793 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000794 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000795}
796
797/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
798/// part of "I", the instruction), computing the set of inputs and outputs of
799/// the pattern. Report errors if we see anything naughty.
800void DAGISelEmitter::
801FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
802 std::map<std::string, TreePatternNode*> &InstInputs,
803 std::map<std::string, Record*> &InstResults) {
804 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000805 bool isUse = HandleUse(I, Pat, InstInputs);
806 if (!isUse && Pat->getTransformFn())
807 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000808 return;
809 } else if (Pat->getOperator()->getName() != "set") {
810 // If this is not a set, verify that the children nodes are not void typed,
811 // and recurse.
812 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
813 if (Pat->getChild(i)->getType() == MVT::isVoid)
814 I->error("Cannot have void nodes inside of patterns!");
815 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
816 }
817
818 // If this is a non-leaf node with no children, treat it basically as if
819 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000820 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000821 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000822 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000823
Chris Lattnerf1311842005-09-14 23:05:13 +0000824 if (!isUse && Pat->getTransformFn())
825 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000826 return;
827 }
828
829 // Otherwise, this is a set, validate and collect instruction results.
830 if (Pat->getNumChildren() == 0)
831 I->error("set requires operands!");
832 else if (Pat->getNumChildren() & 1)
833 I->error("set requires an even number of operands");
834
Chris Lattnerf1311842005-09-14 23:05:13 +0000835 if (Pat->getTransformFn())
836 I->error("Cannot specify a transform function on a set node!");
837
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000838 // Check the set destinations.
839 unsigned NumValues = Pat->getNumChildren()/2;
840 for (unsigned i = 0; i != NumValues; ++i) {
841 TreePatternNode *Dest = Pat->getChild(i);
842 if (!Dest->isLeaf())
843 I->error("set destination should be a virtual register!");
844
845 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
846 if (!Val)
847 I->error("set destination should be a virtual register!");
848
849 if (!Val->getDef()->isSubClassOf("RegisterClass"))
850 I->error("set destination should be a virtual register!");
851 if (Dest->getName().empty())
852 I->error("set destination must have a name!");
853 if (InstResults.count(Dest->getName()))
854 I->error("cannot set '" + Dest->getName() +"' multiple times");
855 InstResults[Dest->getName()] = Val->getDef();
856
857 // Verify and collect info from the computation.
858 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
859 InstInputs, InstResults);
860 }
861}
862
863
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000864/// ParseInstructions - Parse all of the instructions, inlining and resolving
865/// any fragments involved. This populates the Instructions list with fully
866/// resolved instructions.
867void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000868 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
869
870 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
871 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
872 continue; // no pattern yet, ignore it.
873
874 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
875 if (LI->getSize() == 0) continue; // no pattern.
876
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000877 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000878 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000879 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +0000880 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000881
Chris Lattner95f6b762005-09-08 23:26:30 +0000882 // Infer as many types as possible. If we cannot infer all of them, we can
883 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000884 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +0000885 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000886
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000887 // InstInputs - Keep track of all of the inputs of the instruction, along
888 // with the record they are declared as.
889 std::map<std::string, TreePatternNode*> InstInputs;
890
891 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000892 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000893 std::map<std::string, Record*> InstResults;
894
Chris Lattner1f39e292005-09-14 00:09:24 +0000895 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000896 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +0000897 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
898 TreePatternNode *Pat = I->getTree(j);
899 if (Pat->getType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000900 I->dump();
901 I->error("Top-level forms in instruction pattern should have"
902 " void types");
903 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000904
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000905 // Find inputs and outputs, and verify the structure of the uses/defs.
906 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +0000907 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000908
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000909 // Now that we have inputs and outputs of the pattern, inspect the operands
910 // list for the instruction. This determines the order that operands are
911 // added to the machine instruction the node corresponds to.
912 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +0000913
914 // Parse the operands list from the (ops) list, validating it.
915 std::vector<std::string> &Args = I->getArgList();
916 assert(Args.empty() && "Args list should still be empty here!");
917 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
918
919 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +0000920 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +0000921 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +0000922 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000923 I->error("'" + InstResults.begin()->first +
924 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +0000925 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +0000926
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000927 // Check that it exists in InstResults.
928 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +0000929 if (R == 0)
930 I->error("Operand $" + OpName + " should be a set destination: all "
931 "outputs must occur before inputs in operand list!");
932
933 if (CGI.OperandList[i].Rec != R)
934 I->error("Operand $" + OpName + " class mismatch!");
935
Chris Lattnerae6d8282005-09-15 21:51:12 +0000936 // Remember the return type.
937 ResultTypes.push_back(CGI.OperandList[i].Ty);
938
Chris Lattner39e8af92005-09-14 18:19:25 +0000939 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000940 InstResults.erase(OpName);
941 }
942
Chris Lattner0b592252005-09-14 21:59:34 +0000943 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
944 // the copy while we're checking the inputs.
945 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +0000946
947 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +0000948 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000949 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
950 const std::string &OpName = CGI.OperandList[i].Name;
951 if (OpName.empty())
952 I->error("Operand #" + utostr(i) + " in operands list has no name!");
953
Chris Lattner0b592252005-09-14 21:59:34 +0000954 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000955 I->error("Operand $" + OpName +
956 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +0000957 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +0000958 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000959 if (CGI.OperandList[i].Ty != InVal->getType())
960 I->error("Operand $" + OpName +
961 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +0000962 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +0000963
Chris Lattner2175c182005-09-14 23:01:59 +0000964 // Construct the result for the dest-pattern operand list.
965 TreePatternNode *OpNode = InVal->clone();
966
967 // No predicate is useful on the result.
968 OpNode->setPredicateFn("");
969
970 // Promote the xform function to be an explicit node if set.
971 if (Record *Xform = OpNode->getTransformFn()) {
972 OpNode->setTransformFn(0);
973 std::vector<TreePatternNode*> Children;
974 Children.push_back(OpNode);
975 OpNode = new TreePatternNode(Xform, Children);
976 }
977
978 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +0000979 }
980
Chris Lattner0b592252005-09-14 21:59:34 +0000981 if (!InstInputsCheck.empty())
982 I->error("Input operand $" + InstInputsCheck.begin()->first +
983 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +0000984
985 TreePatternNode *ResultPattern =
986 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +0000987
988 // Create and insert the instruction.
989 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
990 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
991
992 // Use a temporary tree pattern to infer all types and make sure that the
993 // constructed result is correct. This depends on the instruction already
994 // being inserted into the Instructions map.
995 TreePattern Temp(I->getRecord(), ResultPattern, *this);
996 Temp.InferAllTypes();
997
998 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
999 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001000
Chris Lattner32707602005-09-08 23:22:48 +00001001 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001002 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001003
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001004 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001005 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1006 E = Instructions.end(); II != E; ++II) {
1007 TreePattern *I = II->second.getPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001008
1009 if (I->getNumTrees() != 1) {
1010 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1011 continue;
1012 }
1013 TreePatternNode *Pattern = I->getTree(0);
1014 if (Pattern->getOperator()->getName() != "set")
1015 continue; // Not a set (store or something?)
1016
1017 if (Pattern->getNumChildren() != 2)
1018 continue; // Not a set of a single value (not handled so far)
1019
1020 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001021
1022 std::string Reason;
1023 if (!SrcPattern->canPatternMatch(Reason, *this))
1024 I->error("Instruction can never match: " + Reason);
1025
Chris Lattnerae5b3502005-09-15 21:57:35 +00001026 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001027 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001028 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001029}
1030
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001031void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001032 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001033
Chris Lattnerabbb6052005-09-15 21:42:00 +00001034 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001035 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1036 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001037
Chris Lattnerabbb6052005-09-15 21:42:00 +00001038 // Inline pattern fragments into it.
1039 Pattern->InlinePatternFragments();
1040
1041 // Infer as many types as possible. If we cannot infer all of them, we can
1042 // never do anything with this pattern: report it to the user.
1043 if (!Pattern->InferAllTypes())
1044 Pattern->error("Could not infer all types in pattern!");
1045
1046 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1047 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001048
1049 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +00001050 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001051
1052 // Inline pattern fragments into it.
1053 Result->InlinePatternFragments();
1054
1055 // Infer as many types as possible. If we cannot infer all of them, we can
1056 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001057 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001058 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001059
1060 if (Result->getNumTrees() != 1)
1061 Result->error("Cannot handle instructions producing instructions "
1062 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001063
1064 std::string Reason;
1065 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1066 Pattern->error("Pattern can never match: " + Reason);
1067
Chris Lattnerabbb6052005-09-15 21:42:00 +00001068 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1069 Result->getOnlyTree()));
1070 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001071}
1072
Chris Lattnere46e17b2005-09-29 19:28:10 +00001073/// CombineChildVariants - Given a bunch of permutations of each child of the
1074/// 'operator' node, put them together in all possible ways.
1075static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001076 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001077 std::vector<TreePatternNode*> &OutVariants,
1078 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001079 // Make sure that each operand has at least one variant to choose from.
1080 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1081 if (ChildVariants[i].empty())
1082 return;
1083
Chris Lattnere46e17b2005-09-29 19:28:10 +00001084 // The end result is an all-pairs construction of the resultant pattern.
1085 std::vector<unsigned> Idxs;
1086 Idxs.resize(ChildVariants.size());
1087 bool NotDone = true;
1088 while (NotDone) {
1089 // Create the variant and add it to the output list.
1090 std::vector<TreePatternNode*> NewChildren;
1091 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1092 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1093 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1094
1095 // Copy over properties.
1096 R->setName(Orig->getName());
1097 R->setPredicateFn(Orig->getPredicateFn());
1098 R->setTransformFn(Orig->getTransformFn());
1099 R->setType(Orig->getType());
1100
1101 // If this pattern cannot every match, do not include it as a variant.
1102 std::string ErrString;
1103 if (!R->canPatternMatch(ErrString, ISE)) {
1104 delete R;
1105 } else {
1106 bool AlreadyExists = false;
1107
1108 // Scan to see if this pattern has already been emitted. We can get
1109 // duplication due to things like commuting:
1110 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1111 // which are the same pattern. Ignore the dups.
1112 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1113 if (R->isIsomorphicTo(OutVariants[i])) {
1114 AlreadyExists = true;
1115 break;
1116 }
1117
1118 if (AlreadyExists)
1119 delete R;
1120 else
1121 OutVariants.push_back(R);
1122 }
1123
1124 // Increment indices to the next permutation.
1125 NotDone = false;
1126 // Look for something we can increment without causing a wrap-around.
1127 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1128 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1129 NotDone = true; // Found something to increment.
1130 break;
1131 }
1132 Idxs[IdxsIdx] = 0;
1133 }
1134 }
1135}
1136
Chris Lattneraf302912005-09-29 22:36:54 +00001137/// CombineChildVariants - A helper function for binary operators.
1138///
1139static void CombineChildVariants(TreePatternNode *Orig,
1140 const std::vector<TreePatternNode*> &LHS,
1141 const std::vector<TreePatternNode*> &RHS,
1142 std::vector<TreePatternNode*> &OutVariants,
1143 DAGISelEmitter &ISE) {
1144 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1145 ChildVariants.push_back(LHS);
1146 ChildVariants.push_back(RHS);
1147 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1148}
1149
1150
1151static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1152 std::vector<TreePatternNode *> &Children) {
1153 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1154 Record *Operator = N->getOperator();
1155
1156 // Only permit raw nodes.
1157 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1158 N->getTransformFn()) {
1159 Children.push_back(N);
1160 return;
1161 }
1162
1163 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1164 Children.push_back(N->getChild(0));
1165 else
1166 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1167
1168 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1169 Children.push_back(N->getChild(1));
1170 else
1171 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1172}
1173
Chris Lattnere46e17b2005-09-29 19:28:10 +00001174/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1175/// the (potentially recursive) pattern by using algebraic laws.
1176///
1177static void GenerateVariantsOf(TreePatternNode *N,
1178 std::vector<TreePatternNode*> &OutVariants,
1179 DAGISelEmitter &ISE) {
1180 // We cannot permute leaves.
1181 if (N->isLeaf()) {
1182 OutVariants.push_back(N);
1183 return;
1184 }
1185
1186 // Look up interesting info about the node.
1187 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1188
1189 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001190 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1191 // Reassociate by pulling together all of the linked operators
1192 std::vector<TreePatternNode*> MaximalChildren;
1193 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1194
1195 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1196 // permutations.
1197 if (MaximalChildren.size() == 3) {
1198 // Find the variants of all of our maximal children.
1199 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1200 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1201 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1202 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1203
1204 // There are only two ways we can permute the tree:
1205 // (A op B) op C and A op (B op C)
1206 // Within these forms, we can also permute A/B/C.
1207
1208 // Generate legal pair permutations of A/B/C.
1209 std::vector<TreePatternNode*> ABVariants;
1210 std::vector<TreePatternNode*> BAVariants;
1211 std::vector<TreePatternNode*> ACVariants;
1212 std::vector<TreePatternNode*> CAVariants;
1213 std::vector<TreePatternNode*> BCVariants;
1214 std::vector<TreePatternNode*> CBVariants;
1215 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1216 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1217 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1218 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1219 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1220 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1221
1222 // Combine those into the result: (x op x) op x
1223 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1224 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1225 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1226 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1227 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1228 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1229
1230 // Combine those into the result: x op (x op x)
1231 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1232 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1233 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1234 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1235 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1236 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1237 return;
1238 }
1239 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001240
1241 // Compute permutations of all children.
1242 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1243 ChildVariants.resize(N->getNumChildren());
1244 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1245 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1246
1247 // Build all permutations based on how the children were formed.
1248 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1249
1250 // If this node is commutative, consider the commuted order.
1251 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1252 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001253 // Consider the commuted order.
1254 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1255 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001256 }
1257}
1258
1259
Chris Lattnere97603f2005-09-28 19:27:25 +00001260// GenerateVariants - Generate variants. For example, commutative patterns can
1261// match multiple ways. Add them to PatternsToMatch as well.
1262void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001263
1264 DEBUG(std::cerr << "Generating instruction variants.\n");
1265
1266 // Loop over all of the patterns we've collected, checking to see if we can
1267 // generate variants of the instruction, through the exploitation of
1268 // identities. This permits the target to provide agressive matching without
1269 // the .td file having to contain tons of variants of instructions.
1270 //
1271 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1272 // intentionally do not reconsider these. Any variants of added patterns have
1273 // already been added.
1274 //
1275 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1276 std::vector<TreePatternNode*> Variants;
1277 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1278
1279 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001280 Variants.erase(Variants.begin()); // Remove the original pattern.
1281
1282 if (Variants.empty()) // No variants for this pattern.
1283 continue;
1284
1285 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1286 PatternsToMatch[i].first->dump();
1287 std::cerr << "\n");
1288
1289 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1290 TreePatternNode *Variant = Variants[v];
1291
1292 DEBUG(std::cerr << " VAR#" << v << ": ";
1293 Variant->dump();
1294 std::cerr << "\n");
1295
1296 // Scan to see if an instruction or explicit pattern already matches this.
1297 bool AlreadyExists = false;
1298 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1299 // Check to see if this variant already exists.
1300 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1301 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1302 AlreadyExists = true;
1303 break;
1304 }
1305 }
1306 // If we already have it, ignore the variant.
1307 if (AlreadyExists) continue;
1308
1309 // Otherwise, add it to the list of patterns we have.
1310 PatternsToMatch.push_back(std::make_pair(Variant,
1311 PatternsToMatch[i].second));
1312 }
1313
1314 DEBUG(std::cerr << "\n");
1315 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001316}
1317
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001318
Chris Lattner05814af2005-09-28 17:57:56 +00001319/// getPatternSize - Return the 'size' of this pattern. We want to match large
1320/// patterns before small ones. This is used to determine the size of a
1321/// pattern.
1322static unsigned getPatternSize(TreePatternNode *P) {
1323 assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1324 "Not a valid pattern node to size!");
1325 unsigned Size = 1; // The node itself.
1326
1327 // Count children in the count if they are also nodes.
1328 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1329 TreePatternNode *Child = P->getChild(i);
1330 if (!Child->isLeaf() && Child->getType() != MVT::Other)
1331 Size += getPatternSize(Child);
1332 }
1333
1334 return Size;
1335}
1336
1337/// getResultPatternCost - Compute the number of instructions for this pattern.
1338/// This is a temporary hack. We should really include the instruction
1339/// latencies in this calculation.
1340static unsigned getResultPatternCost(TreePatternNode *P) {
1341 if (P->isLeaf()) return 0;
1342
1343 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1344 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1345 Cost += getResultPatternCost(P->getChild(i));
1346 return Cost;
1347}
1348
1349// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1350// In particular, we want to match maximal patterns first and lowest cost within
1351// a particular complexity first.
1352struct PatternSortingPredicate {
1353 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1354 DAGISelEmitter::PatternToMatch *RHS) {
1355 unsigned LHSSize = getPatternSize(LHS->first);
1356 unsigned RHSSize = getPatternSize(RHS->first);
1357 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1358 if (LHSSize < RHSSize) return false;
1359
1360 // If the patterns have equal complexity, compare generated instruction cost
1361 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1362 }
1363};
1364
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001365/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1366/// if the match fails. At this point, we already know that the opcode for N
1367/// matches, and the SDNode for the result has the RootName specified name.
1368void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001369 const std::string &RootName,
1370 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001371 unsigned PatternNo, std::ostream &OS) {
1372 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001373
1374 // If this node has a name associated with it, capture it in VarMap. If
1375 // we already saw this in the pattern, emit code to verify dagness.
1376 if (!N->getName().empty()) {
1377 std::string &VarMapEntry = VarMap[N->getName()];
1378 if (VarMapEntry.empty()) {
1379 VarMapEntry = RootName;
1380 } else {
1381 // If we get here, this is a second reference to a specific name. Since
1382 // we already have checked that the first reference is valid, we don't
1383 // have to recursively match it, just check that it's the same as the
1384 // previously named thing.
1385 OS << " if (" << VarMapEntry << " != " << RootName
1386 << ") goto P" << PatternNo << "Fail;\n";
1387 return;
1388 }
1389 }
1390
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001391 // Emit code to load the child nodes and match their contents recursively.
1392 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001393 OS << " SDOperand " << RootName << i <<" = " << RootName
1394 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001395 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001396
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001397 if (!Child->isLeaf()) {
1398 // If it's not a leaf, recursively match.
1399 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001400 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001401 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001402 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001403 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001404 // If this child has a name associated with it, capture it in VarMap. If
1405 // we already saw this in the pattern, emit code to verify dagness.
1406 if (!Child->getName().empty()) {
1407 std::string &VarMapEntry = VarMap[Child->getName()];
1408 if (VarMapEntry.empty()) {
1409 VarMapEntry = RootName + utostr(i);
1410 } else {
1411 // If we get here, this is a second reference to a specific name. Since
1412 // we already have checked that the first reference is valid, we don't
1413 // have to recursively match it, just check that it's the same as the
1414 // previously named thing.
1415 OS << " if (" << VarMapEntry << " != " << RootName << i
1416 << ") goto P" << PatternNo << "Fail;\n";
1417 continue;
1418 }
1419 }
1420
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001421 // Handle leaves of various types.
1422 Init *LeafVal = Child->getLeafValue();
1423 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1424 if (LeafRec->isSubClassOf("RegisterClass")) {
1425 // Handle register references. Nothing to do here.
1426 } else if (LeafRec->isSubClassOf("ValueType")) {
1427 // Make sure this is the specified value type.
1428 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1429 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1430 << "Fail;\n";
1431 } else {
1432 Child->dump();
1433 assert(0 && "Unknown leaf type!");
1434 }
1435 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001436 }
1437
1438 // If there is a node predicate for this, emit the call.
1439 if (!N->getPredicateFn().empty())
1440 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001441 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001442}
1443
Chris Lattner6bc7e512005-09-26 21:53:26 +00001444/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1445/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001446unsigned DAGISelEmitter::
1447CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1448 std::map<std::string,std::string> &VariableMap,
Chris Lattner6bc7e512005-09-26 21:53:26 +00001449 std::ostream &OS) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001450 // This is something selected from the pattern we matched.
1451 if (!N->getName().empty()) {
Chris Lattner6bc7e512005-09-26 21:53:26 +00001452 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001453 assert(!Val.empty() &&
1454 "Variable referenced but not defined and not caught earlier!");
1455 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1456 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001457 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001458 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001459
1460 unsigned ResNo = Ctr++;
1461 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1462 switch (N->getType()) {
1463 default: assert(0 && "Unknown type for constant node!");
1464 case MVT::i1: OS << " bool Tmp"; break;
1465 case MVT::i8: OS << " unsigned char Tmp"; break;
1466 case MVT::i16: OS << " unsigned short Tmp"; break;
1467 case MVT::i32: OS << " unsigned Tmp"; break;
1468 case MVT::i64: OS << " uint64_t Tmp"; break;
1469 }
1470 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1471 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1472 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1473 } else {
1474 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1475 }
1476 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1477 // value if used multiple times by this pattern result.
1478 Val = "Tmp"+utostr(ResNo);
1479 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001480 }
1481
1482 if (N->isLeaf()) {
1483 N->dump();
1484 assert(0 && "Unknown leaf type!");
1485 return ~0U;
1486 }
1487
1488 Record *Op = N->getOperator();
1489 if (Op->isSubClassOf("Instruction")) {
1490 // Emit all of the operands.
1491 std::vector<unsigned> Ops;
1492 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1493 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1494
1495 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1496 unsigned ResNo = Ctr++;
1497
1498 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1499 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1500 << getEnumName(N->getType());
1501 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1502 OS << ", Tmp" << Ops[i];
1503 OS << ");\n";
1504 return ResNo;
1505 } else if (Op->isSubClassOf("SDNodeXForm")) {
1506 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1507 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1508
1509 unsigned ResNo = Ctr++;
1510 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1511 << "(Tmp" << OpVal << ".Val);\n";
1512 return ResNo;
1513 } else {
1514 N->dump();
1515 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001516 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001517 }
1518}
1519
1520
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001521/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1522/// stream to match the pattern, and generate the code for the match if it
1523/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001524void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1525 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001526 static unsigned PatternCount = 0;
1527 unsigned PatternNo = PatternCount++;
1528 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001529 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001530 OS << "\n // Emits: ";
1531 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001532 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001533 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1534 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001535
Chris Lattner8fc35682005-09-23 23:16:51 +00001536 // Emit the matcher, capturing named arguments in VariableMap.
1537 std::map<std::string,std::string> VariableMap;
1538 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001539
Chris Lattner72fe91c2005-09-24 00:40:24 +00001540 unsigned TmpNo = 0;
1541 unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
Chris Lattner296dfe32005-09-24 00:50:51 +00001542
1543 // Add the result to the map if it has multiple uses.
1544 OS << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
Chris Lattner72fe91c2005-09-24 00:40:24 +00001545 OS << " return Tmp" << Res << ";\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001546 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001547}
1548
Chris Lattner37481472005-09-26 21:59:35 +00001549
1550namespace {
1551 /// CompareByRecordName - An ordering predicate that implements less-than by
1552 /// comparing the names records.
1553 struct CompareByRecordName {
1554 bool operator()(const Record *LHS, const Record *RHS) const {
1555 // Sort by name first.
1556 if (LHS->getName() < RHS->getName()) return true;
1557 // If both names are equal, sort by pointer.
1558 return LHS->getName() == RHS->getName() && LHS < RHS;
1559 }
1560 };
1561}
1562
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001563void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1564 // Emit boilerplate.
1565 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001566 << "SDOperand SelectCode(SDOperand N) {\n"
1567 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1568 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1569 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001570 << " if (!N.Val->hasOneUse()) {\n"
1571 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1572 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1573 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001574 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001575 << " default: break;\n"
1576 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001577 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001578 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001579 << " case ISD::AssertZext: {\n"
1580 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1581 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1582 << " return Tmp0;\n"
1583 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001584
Chris Lattner81303322005-09-23 19:36:15 +00001585 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001586 std::map<Record*, std::vector<PatternToMatch*>,
1587 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001588 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1589 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1590 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001591
Chris Lattner3f7e9142005-09-23 20:52:47 +00001592 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001593 for (std::map<Record*, std::vector<PatternToMatch*>,
1594 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1595 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001596 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1597 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1598
1599 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001600
1601 // We want to emit all of the matching code now. However, we want to emit
1602 // the matches in order of minimal cost. Sort the patterns so the least
1603 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001604 std::stable_sort(Patterns.begin(), Patterns.end(),
1605 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001606
Chris Lattner3f7e9142005-09-23 20:52:47 +00001607 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1608 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001609 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001610 }
1611
1612
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001613 OS << " } // end of big switch.\n\n"
1614 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001615 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001616 << " std::cerr << '\\n';\n"
1617 << " abort();\n"
1618 << "}\n";
1619}
1620
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001621void DAGISelEmitter::run(std::ostream &OS) {
1622 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1623 " target", OS);
1624
Chris Lattner1f39e292005-09-14 00:09:24 +00001625 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1626 << "// *** instruction selector class. These functions are really "
1627 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001628
Chris Lattner296dfe32005-09-24 00:50:51 +00001629 OS << "// Instance var to keep track of multiply used nodes that have \n"
1630 << "// already been selected.\n"
1631 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1632
Chris Lattnerca559d02005-09-08 21:03:01 +00001633 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001634 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001635 ParsePatternFragments(OS);
1636 ParseInstructions();
1637 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001638
Chris Lattnere97603f2005-09-28 19:27:25 +00001639 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00001640 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00001641 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001642
Chris Lattnere46e17b2005-09-29 19:28:10 +00001643
1644 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1645 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1646 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1647 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1648 std::cerr << "\n";
1649 });
1650
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001651 // At this point, we have full information about the 'Patterns' we need to
1652 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001653 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001654 EmitInstructionSelector(OS);
1655
1656 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1657 E = PatternFragments.end(); I != E; ++I)
1658 delete I->second;
1659 PatternFragments.clear();
1660
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001661 Instructions.clear();
1662}