blob: 29206ce3b4cddb80be0065939dcec71fbc95a7ce [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 Lattner3c7e18d2005-10-14 06:12:03 +000023// Helpers for working with extended types.
24
25/// FilterVTs - Filter a list of VT's according to a predicate.
26///
27template<typename T>
28static std::vector<MVT::ValueType>
29FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32 if (Filter(InVTs[i]))
33 Result.push_back(InVTs[i]);
34 return Result;
35}
36
37/// isExtIntegerVT - Return true if the specified extended value type is
38/// integer, or isInt.
39static bool isExtIntegerVT(unsigned char VT) {
40 return VT == MVT::isInt ||
41 (VT < MVT::LAST_VALUETYPE && MVT::isInteger((MVT::ValueType)VT));
42}
43
44/// isExtFloatingPointVT - Return true if the specified extended value type is
45/// floating point, or isFP.
46static bool isExtFloatingPointVT(unsigned char VT) {
47 return VT == MVT::isFP ||
48 (VT < MVT::LAST_VALUETYPE && MVT::isFloatingPoint((MVT::ValueType)VT));
49}
50
51//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000052// SDTypeConstraint implementation
53//
54
55SDTypeConstraint::SDTypeConstraint(Record *R) {
56 OperandNo = R->getValueAsInt("OperandNum");
57
58 if (R->isSubClassOf("SDTCisVT")) {
59 ConstraintType = SDTCisVT;
60 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
61 } else if (R->isSubClassOf("SDTCisInt")) {
62 ConstraintType = SDTCisInt;
63 } else if (R->isSubClassOf("SDTCisFP")) {
64 ConstraintType = SDTCisFP;
65 } else if (R->isSubClassOf("SDTCisSameAs")) {
66 ConstraintType = SDTCisSameAs;
67 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
68 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
69 ConstraintType = SDTCisVTSmallerThanOp;
70 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
71 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +000072 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
73 ConstraintType = SDTCisOpSmallerThanOp;
74 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
75 R->getValueAsInt("BigOperandNum");
Chris Lattner33c92e92005-09-08 21:27:15 +000076 } else {
77 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
78 exit(1);
79 }
80}
81
Chris Lattner32707602005-09-08 23:22:48 +000082/// getOperandNum - Return the node corresponding to operand #OpNo in tree
83/// N, which has NumResults results.
84TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
85 TreePatternNode *N,
86 unsigned NumResults) const {
87 assert(NumResults == 1 && "We only work with single result nodes so far!");
88
89 if (OpNo < NumResults)
90 return N; // FIXME: need value #
91 else
92 return N->getChild(OpNo-NumResults);
93}
94
95/// ApplyTypeConstraint - Given a node in a pattern, apply this type
96/// constraint to the nodes operands. This returns true if it makes a
97/// change, false otherwise. If a type contradiction is found, throw an
98/// exception.
99bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
100 const SDNodeInfo &NodeInfo,
101 TreePattern &TP) const {
102 unsigned NumResults = NodeInfo.getNumResults();
103 assert(NumResults == 1 && "We only work with single result nodes so far!");
104
105 // Check that the number of operands is sane.
106 if (NodeInfo.getNumOperands() >= 0) {
107 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
108 TP.error(N->getOperator()->getName() + " node requires exactly " +
109 itostr(NodeInfo.getNumOperands()) + " operands!");
110 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000111
112 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000113
114 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
115
116 switch (ConstraintType) {
117 default: assert(0 && "Unknown constraint type!");
118 case SDTCisVT:
119 // Operand must be a particular type.
120 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000121 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000122 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000123 std::vector<MVT::ValueType> IntVTs =
124 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000125
126 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000127 if (IntVTs.size() == 1)
128 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000129 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000130 }
131 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000132 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000133 std::vector<MVT::ValueType> FPVTs =
134 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000135
136 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000137 if (FPVTs.size() == 1)
138 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000139 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000140 }
Chris Lattner32707602005-09-08 23:22:48 +0000141 case SDTCisSameAs: {
142 TreePatternNode *OtherNode =
143 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000144 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
145 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000146 }
147 case SDTCisVTSmallerThanOp: {
148 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
149 // have an integer type that is smaller than the VT.
150 if (!NodeToApply->isLeaf() ||
151 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
152 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
153 ->isSubClassOf("ValueType"))
154 TP.error(N->getOperator()->getName() + " expects a VT operand!");
155 MVT::ValueType VT =
156 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
157 if (!MVT::isInteger(VT))
158 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
159
160 TreePatternNode *OtherNode =
161 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000162
163 // It must be integer.
164 bool MadeChange = false;
165 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
166
167 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000168 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
169 return false;
170 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000171 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000172 TreePatternNode *BigOperand =
173 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
174
175 // Both operands must be integer or FP, but we don't care which.
176 bool MadeChange = false;
177
178 if (isExtIntegerVT(NodeToApply->getExtType()))
179 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
180 else if (isExtFloatingPointVT(NodeToApply->getExtType()))
181 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
182 if (isExtIntegerVT(BigOperand->getExtType()))
183 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
184 else if (isExtFloatingPointVT(BigOperand->getExtType()))
185 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
186
187 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
188
189 if (isExtIntegerVT(NodeToApply->getExtType())) {
190 VTs = FilterVTs(VTs, MVT::isInteger);
191 } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
192 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
193 } else {
194 VTs.clear();
195 }
196
197 switch (VTs.size()) {
198 default: // Too many VT's to pick from.
199 case 0: break; // No info yet.
200 case 1:
201 // Only one VT of this flavor. Cannot ever satisify the constraints.
202 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
203 case 2:
204 // If we have exactly two possible types, the little operand must be the
205 // small one, the big operand should be the big one. Common with
206 // float/double for example.
207 assert(VTs[0] < VTs[1] && "Should be sorted!");
208 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
209 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
210 break;
211 }
212 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000213 }
Chris Lattner32707602005-09-08 23:22:48 +0000214 }
215 return false;
216}
217
218
Chris Lattner33c92e92005-09-08 21:27:15 +0000219//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000220// SDNodeInfo implementation
221//
222SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
223 EnumName = R->getValueAsString("Opcode");
224 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000225 Record *TypeProfile = R->getValueAsDef("TypeProfile");
226 NumResults = TypeProfile->getValueAsInt("NumResults");
227 NumOperands = TypeProfile->getValueAsInt("NumOperands");
228
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000229 // Parse the properties.
230 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000231 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000232 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
233 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000234 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000235 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000236 Properties |= 1 << SDNPAssociative;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000237 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000238 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000239 << "' on node '" << R->getName() << "'!\n";
240 exit(1);
241 }
242 }
243
244
Chris Lattner33c92e92005-09-08 21:27:15 +0000245 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000246 std::vector<Record*> ConstraintList =
247 TypeProfile->getValueAsListOfDefs("Constraints");
248 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000249}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000250
251//===----------------------------------------------------------------------===//
252// TreePatternNode implementation
253//
254
255TreePatternNode::~TreePatternNode() {
256#if 0 // FIXME: implement refcounted tree nodes!
257 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
258 delete getChild(i);
259#endif
260}
261
Chris Lattner32707602005-09-08 23:22:48 +0000262/// UpdateNodeType - Set the node type of N to VT if VT contains
263/// information. If N already contains a conflicting type, then throw an
264/// exception. This returns true if any information was updated.
265///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000266bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
267 if (VT == MVT::isUnknown || getExtType() == VT) return false;
268 if (getExtType() == MVT::isUnknown) {
Chris Lattner32707602005-09-08 23:22:48 +0000269 setType(VT);
270 return true;
271 }
272
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000273 // If we are told this is to be an int or FP type, and it already is, ignore
274 // the advice.
275 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
276 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
277 return false;
278
279 // If we know this is an int or fp type, and we are told it is a specific one,
280 // take the advice.
281 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
282 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
283 setType(VT);
284 return true;
285 }
286
Chris Lattner1531f202005-10-26 16:59:37 +0000287 if (isLeaf()) {
288 dump();
289 TP.error("Type inference contradiction found in node!");
290 } else {
291 TP.error("Type inference contradiction found in node " +
292 getOperator()->getName() + "!");
293 }
Chris Lattner32707602005-09-08 23:22:48 +0000294 return true; // unreachable
295}
296
297
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000298void TreePatternNode::print(std::ostream &OS) const {
299 if (isLeaf()) {
300 OS << *getLeafValue();
301 } else {
302 OS << "(" << getOperator()->getName();
303 }
304
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000305 switch (getExtType()) {
306 case MVT::Other: OS << ":Other"; break;
307 case MVT::isInt: OS << ":isInt"; break;
308 case MVT::isFP : OS << ":isFP"; break;
309 case MVT::isUnknown: ; /*OS << ":?";*/ break;
310 default: OS << ":" << getType(); break;
311 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000312
313 if (!isLeaf()) {
314 if (getNumChildren() != 0) {
315 OS << " ";
316 getChild(0)->print(OS);
317 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
318 OS << ", ";
319 getChild(i)->print(OS);
320 }
321 }
322 OS << ")";
323 }
324
325 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000326 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000327 if (TransformFn)
328 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000329 if (!getName().empty())
330 OS << ":$" << getName();
331
332}
333void TreePatternNode::dump() const {
334 print(std::cerr);
335}
336
Chris Lattnere46e17b2005-09-29 19:28:10 +0000337/// isIsomorphicTo - Return true if this node is recursively isomorphic to
338/// the specified node. For this comparison, all of the state of the node
339/// is considered, except for the assigned name. Nodes with differing names
340/// that are otherwise identical are considered isomorphic.
341bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
342 if (N == this) return true;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000343 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000344 getPredicateFn() != N->getPredicateFn() ||
345 getTransformFn() != N->getTransformFn())
346 return false;
347
348 if (isLeaf()) {
349 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
350 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
351 return DI->getDef() == NDI->getDef();
352 return getLeafValue() == N->getLeafValue();
353 }
354
355 if (N->getOperator() != getOperator() ||
356 N->getNumChildren() != getNumChildren()) return false;
357 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
358 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
359 return false;
360 return true;
361}
362
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000363/// clone - Make a copy of this tree and all of its children.
364///
365TreePatternNode *TreePatternNode::clone() const {
366 TreePatternNode *New;
367 if (isLeaf()) {
368 New = new TreePatternNode(getLeafValue());
369 } else {
370 std::vector<TreePatternNode*> CChildren;
371 CChildren.reserve(Children.size());
372 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
373 CChildren.push_back(getChild(i)->clone());
374 New = new TreePatternNode(getOperator(), CChildren);
375 }
376 New->setName(getName());
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000377 New->setType(getExtType());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000378 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000379 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000380 return New;
381}
382
Chris Lattner32707602005-09-08 23:22:48 +0000383/// SubstituteFormalArguments - Replace the formal arguments in this tree
384/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000385void TreePatternNode::
386SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
387 if (isLeaf()) return;
388
389 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
390 TreePatternNode *Child = getChild(i);
391 if (Child->isLeaf()) {
392 Init *Val = Child->getLeafValue();
393 if (dynamic_cast<DefInit*>(Val) &&
394 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
395 // We found a use of a formal argument, replace it with its value.
396 Child = ArgMap[Child->getName()];
397 assert(Child && "Couldn't find formal argument!");
398 setChild(i, Child);
399 }
400 } else {
401 getChild(i)->SubstituteFormalArguments(ArgMap);
402 }
403 }
404}
405
406
407/// InlinePatternFragments - If this pattern refers to any pattern
408/// fragments, inline them into place, giving us a pattern without any
409/// PatFrag references.
410TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
411 if (isLeaf()) return this; // nothing to do.
412 Record *Op = getOperator();
413
414 if (!Op->isSubClassOf("PatFrag")) {
415 // Just recursively inline children nodes.
416 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
417 setChild(i, getChild(i)->InlinePatternFragments(TP));
418 return this;
419 }
420
421 // Otherwise, we found a reference to a fragment. First, look up its
422 // TreePattern record.
423 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
424
425 // Verify that we are passing the right number of operands.
426 if (Frag->getNumArgs() != Children.size())
427 TP.error("'" + Op->getName() + "' fragment requires " +
428 utostr(Frag->getNumArgs()) + " operands!");
429
Chris Lattner37937092005-09-09 01:15:01 +0000430 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000431
432 // Resolve formal arguments to their actual value.
433 if (Frag->getNumArgs()) {
434 // Compute the map of formal to actual arguments.
435 std::map<std::string, TreePatternNode*> ArgMap;
436 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
437 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
438
439 FragTree->SubstituteFormalArguments(ArgMap);
440 }
441
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000442 FragTree->setName(getName());
443
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000444 // Get a new copy of this fragment to stitch into here.
445 //delete this; // FIXME: implement refcounting!
446 return FragTree;
447}
448
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000449/// getIntrinsicType - Check to see if the specified record has an intrinsic
450/// type which should be applied to it. This infer the type of register
451/// references from the register file information, for example.
452///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000453static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
454 TreePattern &TP) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000455 // Check to see if this is a register or a register class...
456 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000457 if (NotRegisters) return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000458 return getValueType(R->getValueAsDef("RegType"));
459 } else if (R->isSubClassOf("PatFrag")) {
460 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000461 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000462 } else if (R->isSubClassOf("Register")) {
Chris Lattnerab1bf272005-10-19 01:55:23 +0000463 //const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
464 // TODO: if a register appears in exactly one regclass, we could use that
465 // type info.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000466 return MVT::isUnknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000467 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
468 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000469 return MVT::Other;
470 } else if (R->getName() == "node") {
471 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000472 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000473 }
474
475 TP.error("Unknown node flavor used in pattern: " + R->getName());
476 return MVT::Other;
477}
478
Chris Lattner32707602005-09-08 23:22:48 +0000479/// ApplyTypeConstraints - Apply all of the type constraints relevent to
480/// this node and its children in the tree. This returns true if it makes a
481/// change, false otherwise. If a type contradiction is found, throw an
482/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000483bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
484 if (isLeaf()) {
485 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
486 // If it's a regclass or something else known, include the type.
487 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
488 TP);
489 return false;
490 }
Chris Lattner32707602005-09-08 23:22:48 +0000491
492 // special handling for set, which isn't really an SDNode.
493 if (getOperator()->getName() == "set") {
494 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000495 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
496 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000497
498 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000499 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
500 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000501 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
502 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000503 } else if (getOperator()->isSubClassOf("SDNode")) {
504 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
505
506 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
507 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000508 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000509 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000510 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000511 const DAGInstruction &Inst =
512 TP.getDAGISelEmitter().getInstruction(getOperator());
513
Chris Lattnera28aec12005-09-15 22:23:50 +0000514 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
515 // Apply the result type to the node
516 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
517
518 if (getNumChildren() != Inst.getNumOperands())
519 TP.error("Instruction '" + getOperator()->getName() + " expects " +
520 utostr(Inst.getNumOperands()) + " operands, not " +
521 utostr(getNumChildren()) + " operands!");
522 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
523 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000524 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000525 }
526 return MadeChange;
527 } else {
528 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
529
530 // Node transforms always take one operand, and take and return the same
531 // type.
532 if (getNumChildren() != 1)
533 TP.error("Node transform '" + getOperator()->getName() +
534 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000535 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
536 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000537 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000538 }
Chris Lattner32707602005-09-08 23:22:48 +0000539}
540
Chris Lattnere97603f2005-09-28 19:27:25 +0000541/// canPatternMatch - If it is impossible for this pattern to match on this
542/// target, fill in Reason and return false. Otherwise, return true. This is
543/// used as a santity check for .td files (to prevent people from writing stuff
544/// that can never possibly work), and to prevent the pattern permuter from
545/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000546bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000547 if (isLeaf()) return true;
548
549 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
550 if (!getChild(i)->canPatternMatch(Reason, ISE))
551 return false;
552
553 // If this node is a commutative operator, check that the LHS isn't an
554 // immediate.
555 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
556 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
557 // Scan all of the operands of the node and make sure that only the last one
558 // is a constant node.
559 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
560 if (!getChild(i)->isLeaf() &&
561 getChild(i)->getOperator()->getName() == "imm") {
562 Reason = "Immediate value must be on the RHS of commutative operators!";
563 return false;
564 }
565 }
566
567 return true;
568}
Chris Lattner32707602005-09-08 23:22:48 +0000569
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000570//===----------------------------------------------------------------------===//
571// TreePattern implementation
572//
573
Chris Lattneredbd8712005-10-21 01:19:59 +0000574TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000575 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000576 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000577 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
578 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000579}
580
Chris Lattneredbd8712005-10-21 01:19:59 +0000581TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000582 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000583 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000584 Trees.push_back(ParseTreePattern(Pat));
585}
586
Chris Lattneredbd8712005-10-21 01:19:59 +0000587TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000588 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000589 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000590 Trees.push_back(Pat);
591}
592
593
594
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000595void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000596 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000597 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000598}
599
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000600TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
601 Record *Operator = Dag->getNodeType();
602
603 if (Operator->isSubClassOf("ValueType")) {
604 // If the operator is a ValueType, then this must be "type cast" of a leaf
605 // node.
606 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000607 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000608
609 Init *Arg = Dag->getArg(0);
610 TreePatternNode *New;
611 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000612 Record *R = DI->getDef();
613 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
614 Dag->setArg(0, new DagInit(R,
615 std::vector<std::pair<Init*, std::string> >()));
616 TreePatternNode *TPN = ParseTreePattern(Dag);
617 TPN->setName(Dag->getArgName(0));
618 return TPN;
619 }
620
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000621 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000622 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
623 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000624 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
625 New = new TreePatternNode(II);
626 if (!Dag->getArgName(0).empty())
627 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000628 } else {
629 Arg->dump();
630 error("Unknown leaf value for tree pattern!");
631 return 0;
632 }
633
Chris Lattner32707602005-09-08 23:22:48 +0000634 // Apply the type cast.
635 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000636 return New;
637 }
638
639 // Verify that this is something that makes sense for an operator.
640 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000641 !Operator->isSubClassOf("Instruction") &&
642 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000643 Operator->getName() != "set")
644 error("Unrecognized node '" + Operator->getName() + "'!");
645
Chris Lattneredbd8712005-10-21 01:19:59 +0000646 // Check to see if this is something that is illegal in an input pattern.
647 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
648 Operator->isSubClassOf("SDNodeXForm")))
649 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
650
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000651 std::vector<TreePatternNode*> Children;
652
653 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
654 Init *Arg = Dag->getArg(i);
655 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
656 Children.push_back(ParseTreePattern(DI));
657 Children.back()->setName(Dag->getArgName(i));
658 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
659 Record *R = DefI->getDef();
660 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
661 // TreePatternNode if its own.
662 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
663 Dag->setArg(i, new DagInit(R,
664 std::vector<std::pair<Init*, std::string> >()));
665 --i; // Revisit this node...
666 } else {
667 TreePatternNode *Node = new TreePatternNode(DefI);
668 Node->setName(Dag->getArgName(i));
669 Children.push_back(Node);
670
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000671 // Input argument?
672 if (R->getName() == "node") {
673 if (Dag->getArgName(i).empty())
674 error("'node' argument requires a name to match with operand list");
675 Args.push_back(Dag->getArgName(i));
676 }
677 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000678 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
679 TreePatternNode *Node = new TreePatternNode(II);
680 if (!Dag->getArgName(i).empty())
681 error("Constant int argument should not have a name!");
682 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000683 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000684 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000685 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000686 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000687 error("Unknown leaf value for tree pattern!");
688 }
689 }
690
691 return new TreePatternNode(Operator, Children);
692}
693
Chris Lattner32707602005-09-08 23:22:48 +0000694/// InferAllTypes - Infer/propagate as many types throughout the expression
695/// patterns as possible. Return true if all types are infered, false
696/// otherwise. Throw an exception if a type contradiction is found.
697bool TreePattern::InferAllTypes() {
698 bool MadeChange = true;
699 while (MadeChange) {
700 MadeChange = false;
701 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000702 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000703 }
704
705 bool HasUnresolvedTypes = false;
706 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
707 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
708 return !HasUnresolvedTypes;
709}
710
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000711void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000712 OS << getRecord()->getName();
713 if (!Args.empty()) {
714 OS << "(" << Args[0];
715 for (unsigned i = 1, e = Args.size(); i != e; ++i)
716 OS << ", " << Args[i];
717 OS << ")";
718 }
719 OS << ": ";
720
721 if (Trees.size() > 1)
722 OS << "[\n";
723 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
724 OS << "\t";
725 Trees[i]->print(OS);
726 OS << "\n";
727 }
728
729 if (Trees.size() > 1)
730 OS << "]\n";
731}
732
733void TreePattern::dump() const { print(std::cerr); }
734
735
736
737//===----------------------------------------------------------------------===//
738// DAGISelEmitter implementation
739//
740
Chris Lattnerca559d02005-09-08 21:03:01 +0000741// Parse all of the SDNode definitions for the target, populating SDNodes.
742void DAGISelEmitter::ParseNodeInfo() {
743 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
744 while (!Nodes.empty()) {
745 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
746 Nodes.pop_back();
747 }
748}
749
Chris Lattner24eeeb82005-09-13 21:51:00 +0000750/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
751/// map, and emit them to the file as functions.
752void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
753 OS << "\n// Node transformations.\n";
754 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
755 while (!Xforms.empty()) {
756 Record *XFormNode = Xforms.back();
757 Record *SDNode = XFormNode->getValueAsDef("Opcode");
758 std::string Code = XFormNode->getValueAsCode("XFormFunction");
759 SDNodeXForms.insert(std::make_pair(XFormNode,
760 std::make_pair(SDNode, Code)));
761
Chris Lattner1048b7a2005-09-13 22:03:37 +0000762 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000763 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
764 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
765
Chris Lattner1048b7a2005-09-13 22:03:37 +0000766 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000767 << "(SDNode *" << C2 << ") {\n";
768 if (ClassName != "SDNode")
769 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
770 OS << Code << "\n}\n";
771 }
772
773 Xforms.pop_back();
774 }
775}
776
777
778
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000779/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
780/// file, building up the PatternFragments map. After we've collected them all,
781/// inline fragments together as necessary, so that there are no references left
782/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000783///
784/// This also emits all of the predicate functions to the output file.
785///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000786void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000787 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
788
789 // First step, parse all of the fragments and emit predicate functions.
790 OS << "\n// Predicate functions.\n";
791 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000792 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000793 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000794 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000795
796 // Validate the argument list, converting it to map, to discard duplicates.
797 std::vector<std::string> &Args = P->getArgList();
798 std::set<std::string> OperandsMap(Args.begin(), Args.end());
799
800 if (OperandsMap.count(""))
801 P->error("Cannot have unnamed 'node' values in pattern fragment!");
802
803 // Parse the operands list.
804 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
805 if (OpsList->getNodeType()->getName() != "ops")
806 P->error("Operands list should start with '(ops ... '!");
807
808 // Copy over the arguments.
809 Args.clear();
810 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
811 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
812 static_cast<DefInit*>(OpsList->getArg(j))->
813 getDef()->getName() != "node")
814 P->error("Operands list should all be 'node' values.");
815 if (OpsList->getArgName(j).empty())
816 P->error("Operands list should have names for each operand!");
817 if (!OperandsMap.count(OpsList->getArgName(j)))
818 P->error("'" + OpsList->getArgName(j) +
819 "' does not occur in pattern or was multiply specified!");
820 OperandsMap.erase(OpsList->getArgName(j));
821 Args.push_back(OpsList->getArgName(j));
822 }
823
824 if (!OperandsMap.empty())
825 P->error("Operands list does not contain an entry for operand '" +
826 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000827
828 // If there is a code init for this fragment, emit the predicate code and
829 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000830 std::string Code = Fragments[i]->getValueAsCode("Predicate");
831 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000832 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000833 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000834 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000835 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
836
Chris Lattner1048b7a2005-09-13 22:03:37 +0000837 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000838 << "(SDNode *" << C2 << ") {\n";
839 if (ClassName != "SDNode")
840 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000841 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000842 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000843 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000844
845 // If there is a node transformation corresponding to this, keep track of
846 // it.
847 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
848 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000849 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000850 }
851
852 OS << "\n\n";
853
854 // Now that we've parsed all of the tree fragments, do a closure on them so
855 // that there are not references to PatFrags left inside of them.
856 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
857 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000858 TreePattern *ThePat = I->second;
859 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000860
Chris Lattner32707602005-09-08 23:22:48 +0000861 // Infer as many types as possible. Don't worry about it if we don't infer
862 // all of them, some may depend on the inputs of the pattern.
863 try {
864 ThePat->InferAllTypes();
865 } catch (...) {
866 // If this pattern fragment is not supported by this target (no types can
867 // satisfy its constraints), just ignore it. If the bogus pattern is
868 // actually used by instructions, the type consistency error will be
869 // reported there.
870 }
871
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000872 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000873 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000874 }
875}
876
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000877/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000878/// instruction input. Return true if this is a real use.
879static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000880 std::map<std::string, TreePatternNode*> &InstInputs) {
881 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000882 if (Pat->getName().empty()) {
883 if (Pat->isLeaf()) {
884 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
885 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
886 I->error("Input " + DI->getDef()->getName() + " must be named!");
887
888 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000889 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000890 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000891
892 Record *Rec;
893 if (Pat->isLeaf()) {
894 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
895 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
896 Rec = DI->getDef();
897 } else {
898 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
899 Rec = Pat->getOperator();
900 }
901
902 TreePatternNode *&Slot = InstInputs[Pat->getName()];
903 if (!Slot) {
904 Slot = Pat;
905 } else {
906 Record *SlotRec;
907 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000908 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000909 } else {
910 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
911 SlotRec = Slot->getOperator();
912 }
913
914 // Ensure that the inputs agree if we've already seen this input.
915 if (Rec != SlotRec)
916 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000917 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000918 I->error("All $" + Pat->getName() + " inputs must agree with each other");
919 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000920 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000921}
922
923/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
924/// part of "I", the instruction), computing the set of inputs and outputs of
925/// the pattern. Report errors if we see anything naughty.
926void DAGISelEmitter::
927FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
928 std::map<std::string, TreePatternNode*> &InstInputs,
929 std::map<std::string, Record*> &InstResults) {
930 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000931 bool isUse = HandleUse(I, Pat, InstInputs);
932 if (!isUse && Pat->getTransformFn())
933 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000934 return;
935 } else if (Pat->getOperator()->getName() != "set") {
936 // If this is not a set, verify that the children nodes are not void typed,
937 // and recurse.
938 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000939 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000940 I->error("Cannot have void nodes inside of patterns!");
941 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
942 }
943
944 // If this is a non-leaf node with no children, treat it basically as if
945 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000946 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000947 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000948 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000949
Chris Lattnerf1311842005-09-14 23:05:13 +0000950 if (!isUse && Pat->getTransformFn())
951 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000952 return;
953 }
954
955 // Otherwise, this is a set, validate and collect instruction results.
956 if (Pat->getNumChildren() == 0)
957 I->error("set requires operands!");
958 else if (Pat->getNumChildren() & 1)
959 I->error("set requires an even number of operands");
960
Chris Lattnerf1311842005-09-14 23:05:13 +0000961 if (Pat->getTransformFn())
962 I->error("Cannot specify a transform function on a set node!");
963
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000964 // Check the set destinations.
965 unsigned NumValues = Pat->getNumChildren()/2;
966 for (unsigned i = 0; i != NumValues; ++i) {
967 TreePatternNode *Dest = Pat->getChild(i);
968 if (!Dest->isLeaf())
969 I->error("set destination should be a virtual register!");
970
971 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
972 if (!Val)
973 I->error("set destination should be a virtual register!");
974
975 if (!Val->getDef()->isSubClassOf("RegisterClass"))
976 I->error("set destination should be a virtual register!");
977 if (Dest->getName().empty())
978 I->error("set destination must have a name!");
979 if (InstResults.count(Dest->getName()))
980 I->error("cannot set '" + Dest->getName() +"' multiple times");
981 InstResults[Dest->getName()] = Val->getDef();
982
983 // Verify and collect info from the computation.
984 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
985 InstInputs, InstResults);
986 }
987}
988
989
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000990/// ParseInstructions - Parse all of the instructions, inlining and resolving
991/// any fragments involved. This populates the Instructions list with fully
992/// resolved instructions.
993void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000994 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
995
996 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +0000997 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000998
Chris Lattner0c0cfa72005-10-19 01:27:22 +0000999 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1000 LI = Instrs[i]->getValueAsListInit("Pattern");
1001
1002 // If there is no pattern, only collect minimal information about the
1003 // instruction for its operand list. We have to assume that there is one
1004 // result, as we have no detailed info.
1005 if (!LI || LI->getSize() == 0) {
1006 std::vector<MVT::ValueType> ResultTypes;
1007 std::vector<MVT::ValueType> OperandTypes;
1008
1009 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1010
1011 // Doesn't even define a result?
1012 if (InstInfo.OperandList.size() == 0)
1013 continue;
1014
1015 // Assume the first operand is the result.
1016 ResultTypes.push_back(InstInfo.OperandList[0].Ty);
1017
1018 // The rest are inputs.
1019 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1020 OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1021
1022 // Create and insert the instruction.
1023 Instructions.insert(std::make_pair(Instrs[i],
1024 DAGInstruction(0, ResultTypes, OperandTypes)));
1025 continue; // no pattern.
1026 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001027
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001028 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001029 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001030 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001031 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001032
Chris Lattner95f6b762005-09-08 23:26:30 +00001033 // Infer as many types as possible. If we cannot infer all of them, we can
1034 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001035 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001036 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001037
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001038 // InstInputs - Keep track of all of the inputs of the instruction, along
1039 // with the record they are declared as.
1040 std::map<std::string, TreePatternNode*> InstInputs;
1041
1042 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001043 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001044 std::map<std::string, Record*> InstResults;
1045
Chris Lattner1f39e292005-09-14 00:09:24 +00001046 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001047 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001048 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1049 TreePatternNode *Pat = I->getTree(j);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001050 if (Pat->getExtType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001051 I->dump();
1052 I->error("Top-level forms in instruction pattern should have"
1053 " void types");
1054 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001055
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001056 // Find inputs and outputs, and verify the structure of the uses/defs.
1057 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001058 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001059
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001060 // Now that we have inputs and outputs of the pattern, inspect the operands
1061 // list for the instruction. This determines the order that operands are
1062 // added to the machine instruction the node corresponds to.
1063 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001064
1065 // Parse the operands list from the (ops) list, validating it.
1066 std::vector<std::string> &Args = I->getArgList();
1067 assert(Args.empty() && "Args list should still be empty here!");
1068 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1069
1070 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +00001071 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +00001072 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001073 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001074 I->error("'" + InstResults.begin()->first +
1075 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001076 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001077
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001078 // Check that it exists in InstResults.
1079 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001080 if (R == 0)
1081 I->error("Operand $" + OpName + " should be a set destination: all "
1082 "outputs must occur before inputs in operand list!");
1083
1084 if (CGI.OperandList[i].Rec != R)
1085 I->error("Operand $" + OpName + " class mismatch!");
1086
Chris Lattnerae6d8282005-09-15 21:51:12 +00001087 // Remember the return type.
1088 ResultTypes.push_back(CGI.OperandList[i].Ty);
1089
Chris Lattner39e8af92005-09-14 18:19:25 +00001090 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001091 InstResults.erase(OpName);
1092 }
1093
Chris Lattner0b592252005-09-14 21:59:34 +00001094 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1095 // the copy while we're checking the inputs.
1096 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001097
1098 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +00001099 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001100 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1101 const std::string &OpName = CGI.OperandList[i].Name;
1102 if (OpName.empty())
1103 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1104
Chris Lattner0b592252005-09-14 21:59:34 +00001105 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001106 I->error("Operand $" + OpName +
1107 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001108 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001109 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001110 if (CGI.OperandList[i].Ty != InVal->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001111 I->error("Operand $" + OpName +
1112 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +00001113 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +00001114
Chris Lattner2175c182005-09-14 23:01:59 +00001115 // Construct the result for the dest-pattern operand list.
1116 TreePatternNode *OpNode = InVal->clone();
1117
1118 // No predicate is useful on the result.
1119 OpNode->setPredicateFn("");
1120
1121 // Promote the xform function to be an explicit node if set.
1122 if (Record *Xform = OpNode->getTransformFn()) {
1123 OpNode->setTransformFn(0);
1124 std::vector<TreePatternNode*> Children;
1125 Children.push_back(OpNode);
1126 OpNode = new TreePatternNode(Xform, Children);
1127 }
1128
1129 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001130 }
1131
Chris Lattner0b592252005-09-14 21:59:34 +00001132 if (!InstInputsCheck.empty())
1133 I->error("Input operand $" + InstInputsCheck.begin()->first +
1134 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001135
1136 TreePatternNode *ResultPattern =
1137 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001138
1139 // Create and insert the instruction.
1140 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1141 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1142
1143 // Use a temporary tree pattern to infer all types and make sure that the
1144 // constructed result is correct. This depends on the instruction already
1145 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001146 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001147 Temp.InferAllTypes();
1148
1149 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1150 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001151
Chris Lattner32707602005-09-08 23:22:48 +00001152 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001153 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001154
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001155 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001156 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1157 E = Instructions.end(); II != E; ++II) {
1158 TreePattern *I = II->second.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001159 if (I == 0) continue; // No pattern.
Chris Lattner1f39e292005-09-14 00:09:24 +00001160
1161 if (I->getNumTrees() != 1) {
1162 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1163 continue;
1164 }
1165 TreePatternNode *Pattern = I->getTree(0);
1166 if (Pattern->getOperator()->getName() != "set")
1167 continue; // Not a set (store or something?)
1168
1169 if (Pattern->getNumChildren() != 2)
1170 continue; // Not a set of a single value (not handled so far)
1171
1172 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001173
1174 std::string Reason;
1175 if (!SrcPattern->canPatternMatch(Reason, *this))
1176 I->error("Instruction can never match: " + Reason);
1177
Chris Lattnerae5b3502005-09-15 21:57:35 +00001178 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001179 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001180 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001181}
1182
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001183void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001184 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001185
Chris Lattnerabbb6052005-09-15 21:42:00 +00001186 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001187 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001188 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001189
Chris Lattnerabbb6052005-09-15 21:42:00 +00001190 // Inline pattern fragments into it.
1191 Pattern->InlinePatternFragments();
1192
1193 // Infer as many types as possible. If we cannot infer all of them, we can
1194 // never do anything with this pattern: report it to the user.
1195 if (!Pattern->InferAllTypes())
1196 Pattern->error("Could not infer all types in pattern!");
1197
1198 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1199 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001200
1201 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001202 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001203
1204 // Inline pattern fragments into it.
1205 Result->InlinePatternFragments();
1206
1207 // Infer as many types as possible. If we cannot infer all of them, we can
1208 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001209 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001210 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001211
1212 if (Result->getNumTrees() != 1)
1213 Result->error("Cannot handle instructions producing instructions "
1214 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001215
1216 std::string Reason;
1217 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1218 Pattern->error("Pattern can never match: " + Reason);
1219
Chris Lattnerabbb6052005-09-15 21:42:00 +00001220 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1221 Result->getOnlyTree()));
1222 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001223}
1224
Chris Lattnere46e17b2005-09-29 19:28:10 +00001225/// CombineChildVariants - Given a bunch of permutations of each child of the
1226/// 'operator' node, put them together in all possible ways.
1227static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001228 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001229 std::vector<TreePatternNode*> &OutVariants,
1230 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001231 // Make sure that each operand has at least one variant to choose from.
1232 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1233 if (ChildVariants[i].empty())
1234 return;
1235
Chris Lattnere46e17b2005-09-29 19:28:10 +00001236 // The end result is an all-pairs construction of the resultant pattern.
1237 std::vector<unsigned> Idxs;
1238 Idxs.resize(ChildVariants.size());
1239 bool NotDone = true;
1240 while (NotDone) {
1241 // Create the variant and add it to the output list.
1242 std::vector<TreePatternNode*> NewChildren;
1243 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1244 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1245 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1246
1247 // Copy over properties.
1248 R->setName(Orig->getName());
1249 R->setPredicateFn(Orig->getPredicateFn());
1250 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001251 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001252
1253 // If this pattern cannot every match, do not include it as a variant.
1254 std::string ErrString;
1255 if (!R->canPatternMatch(ErrString, ISE)) {
1256 delete R;
1257 } else {
1258 bool AlreadyExists = false;
1259
1260 // Scan to see if this pattern has already been emitted. We can get
1261 // duplication due to things like commuting:
1262 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1263 // which are the same pattern. Ignore the dups.
1264 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1265 if (R->isIsomorphicTo(OutVariants[i])) {
1266 AlreadyExists = true;
1267 break;
1268 }
1269
1270 if (AlreadyExists)
1271 delete R;
1272 else
1273 OutVariants.push_back(R);
1274 }
1275
1276 // Increment indices to the next permutation.
1277 NotDone = false;
1278 // Look for something we can increment without causing a wrap-around.
1279 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1280 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1281 NotDone = true; // Found something to increment.
1282 break;
1283 }
1284 Idxs[IdxsIdx] = 0;
1285 }
1286 }
1287}
1288
Chris Lattneraf302912005-09-29 22:36:54 +00001289/// CombineChildVariants - A helper function for binary operators.
1290///
1291static void CombineChildVariants(TreePatternNode *Orig,
1292 const std::vector<TreePatternNode*> &LHS,
1293 const std::vector<TreePatternNode*> &RHS,
1294 std::vector<TreePatternNode*> &OutVariants,
1295 DAGISelEmitter &ISE) {
1296 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1297 ChildVariants.push_back(LHS);
1298 ChildVariants.push_back(RHS);
1299 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1300}
1301
1302
1303static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1304 std::vector<TreePatternNode *> &Children) {
1305 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1306 Record *Operator = N->getOperator();
1307
1308 // Only permit raw nodes.
1309 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1310 N->getTransformFn()) {
1311 Children.push_back(N);
1312 return;
1313 }
1314
1315 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1316 Children.push_back(N->getChild(0));
1317 else
1318 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1319
1320 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1321 Children.push_back(N->getChild(1));
1322 else
1323 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1324}
1325
Chris Lattnere46e17b2005-09-29 19:28:10 +00001326/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1327/// the (potentially recursive) pattern by using algebraic laws.
1328///
1329static void GenerateVariantsOf(TreePatternNode *N,
1330 std::vector<TreePatternNode*> &OutVariants,
1331 DAGISelEmitter &ISE) {
1332 // We cannot permute leaves.
1333 if (N->isLeaf()) {
1334 OutVariants.push_back(N);
1335 return;
1336 }
1337
1338 // Look up interesting info about the node.
1339 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1340
1341 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001342 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1343 // Reassociate by pulling together all of the linked operators
1344 std::vector<TreePatternNode*> MaximalChildren;
1345 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1346
1347 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1348 // permutations.
1349 if (MaximalChildren.size() == 3) {
1350 // Find the variants of all of our maximal children.
1351 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1352 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1353 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1354 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1355
1356 // There are only two ways we can permute the tree:
1357 // (A op B) op C and A op (B op C)
1358 // Within these forms, we can also permute A/B/C.
1359
1360 // Generate legal pair permutations of A/B/C.
1361 std::vector<TreePatternNode*> ABVariants;
1362 std::vector<TreePatternNode*> BAVariants;
1363 std::vector<TreePatternNode*> ACVariants;
1364 std::vector<TreePatternNode*> CAVariants;
1365 std::vector<TreePatternNode*> BCVariants;
1366 std::vector<TreePatternNode*> CBVariants;
1367 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1368 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1369 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1370 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1371 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1372 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1373
1374 // Combine those into the result: (x op x) op x
1375 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1376 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1377 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1378 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1379 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1380 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1381
1382 // Combine those into the result: x op (x op x)
1383 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1384 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1385 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1386 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1387 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1388 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1389 return;
1390 }
1391 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001392
1393 // Compute permutations of all children.
1394 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1395 ChildVariants.resize(N->getNumChildren());
1396 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1397 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1398
1399 // Build all permutations based on how the children were formed.
1400 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1401
1402 // If this node is commutative, consider the commuted order.
1403 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1404 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001405 // Consider the commuted order.
1406 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1407 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001408 }
1409}
1410
1411
Chris Lattnere97603f2005-09-28 19:27:25 +00001412// GenerateVariants - Generate variants. For example, commutative patterns can
1413// match multiple ways. Add them to PatternsToMatch as well.
1414void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001415
1416 DEBUG(std::cerr << "Generating instruction variants.\n");
1417
1418 // Loop over all of the patterns we've collected, checking to see if we can
1419 // generate variants of the instruction, through the exploitation of
1420 // identities. This permits the target to provide agressive matching without
1421 // the .td file having to contain tons of variants of instructions.
1422 //
1423 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1424 // intentionally do not reconsider these. Any variants of added patterns have
1425 // already been added.
1426 //
1427 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1428 std::vector<TreePatternNode*> Variants;
1429 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1430
1431 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001432 Variants.erase(Variants.begin()); // Remove the original pattern.
1433
1434 if (Variants.empty()) // No variants for this pattern.
1435 continue;
1436
1437 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1438 PatternsToMatch[i].first->dump();
1439 std::cerr << "\n");
1440
1441 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1442 TreePatternNode *Variant = Variants[v];
1443
1444 DEBUG(std::cerr << " VAR#" << v << ": ";
1445 Variant->dump();
1446 std::cerr << "\n");
1447
1448 // Scan to see if an instruction or explicit pattern already matches this.
1449 bool AlreadyExists = false;
1450 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1451 // Check to see if this variant already exists.
1452 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1453 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1454 AlreadyExists = true;
1455 break;
1456 }
1457 }
1458 // If we already have it, ignore the variant.
1459 if (AlreadyExists) continue;
1460
1461 // Otherwise, add it to the list of patterns we have.
1462 PatternsToMatch.push_back(std::make_pair(Variant,
1463 PatternsToMatch[i].second));
1464 }
1465
1466 DEBUG(std::cerr << "\n");
1467 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001468}
1469
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001470
Chris Lattner05814af2005-09-28 17:57:56 +00001471/// getPatternSize - Return the 'size' of this pattern. We want to match large
1472/// patterns before small ones. This is used to determine the size of a
1473/// pattern.
1474static unsigned getPatternSize(TreePatternNode *P) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001475 assert(isExtIntegerVT(P->getExtType()) ||
1476 isExtFloatingPointVT(P->getExtType()) &&
Chris Lattner05814af2005-09-28 17:57:56 +00001477 "Not a valid pattern node to size!");
1478 unsigned Size = 1; // The node itself.
1479
1480 // Count children in the count if they are also nodes.
1481 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1482 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001483 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Chris Lattner05814af2005-09-28 17:57:56 +00001484 Size += getPatternSize(Child);
Chris Lattner2f041d42005-10-19 04:41:05 +00001485 else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1486 ++Size; // Matches a ConstantSDNode.
1487 }
Chris Lattner05814af2005-09-28 17:57:56 +00001488 }
1489
1490 return Size;
1491}
1492
1493/// getResultPatternCost - Compute the number of instructions for this pattern.
1494/// This is a temporary hack. We should really include the instruction
1495/// latencies in this calculation.
1496static unsigned getResultPatternCost(TreePatternNode *P) {
1497 if (P->isLeaf()) return 0;
1498
1499 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1500 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1501 Cost += getResultPatternCost(P->getChild(i));
1502 return Cost;
1503}
1504
1505// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1506// In particular, we want to match maximal patterns first and lowest cost within
1507// a particular complexity first.
1508struct PatternSortingPredicate {
1509 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1510 DAGISelEmitter::PatternToMatch *RHS) {
1511 unsigned LHSSize = getPatternSize(LHS->first);
1512 unsigned RHSSize = getPatternSize(RHS->first);
1513 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1514 if (LHSSize < RHSSize) return false;
1515
1516 // If the patterns have equal complexity, compare generated instruction cost
1517 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1518 }
1519};
1520
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001521/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1522/// if the match fails. At this point, we already know that the opcode for N
1523/// matches, and the SDNode for the result has the RootName specified name.
1524void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001525 const std::string &RootName,
1526 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001527 unsigned PatternNo, std::ostream &OS) {
Chris Lattner0614b622005-11-02 06:49:14 +00001528 if (N->isLeaf()) {
1529 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1530 OS << " if (cast<ConstantSDNode>(" << RootName
1531 << ")->getSignExtended() != " << II->getValue() << ")\n"
1532 << " goto P" << PatternNo << "Fail;\n";
1533 return;
1534 }
1535 assert(0 && "Cannot match this as a leaf value!");
1536 abort();
1537 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001538
1539 // If this node has a name associated with it, capture it in VarMap. If
1540 // we already saw this in the pattern, emit code to verify dagness.
1541 if (!N->getName().empty()) {
1542 std::string &VarMapEntry = VarMap[N->getName()];
1543 if (VarMapEntry.empty()) {
1544 VarMapEntry = RootName;
1545 } else {
1546 // If we get here, this is a second reference to a specific name. Since
1547 // we already have checked that the first reference is valid, we don't
1548 // have to recursively match it, just check that it's the same as the
1549 // previously named thing.
1550 OS << " if (" << VarMapEntry << " != " << RootName
1551 << ") goto P" << PatternNo << "Fail;\n";
1552 return;
1553 }
1554 }
1555
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001556 // Emit code to load the child nodes and match their contents recursively.
1557 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001558 OS << " SDOperand " << RootName << i <<" = " << RootName
1559 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001560 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001561
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001562 if (!Child->isLeaf()) {
1563 // If it's not a leaf, recursively match.
1564 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001565 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001566 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001567 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001568 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001569 // If this child has a name associated with it, capture it in VarMap. If
1570 // we already saw this in the pattern, emit code to verify dagness.
1571 if (!Child->getName().empty()) {
1572 std::string &VarMapEntry = VarMap[Child->getName()];
1573 if (VarMapEntry.empty()) {
1574 VarMapEntry = RootName + utostr(i);
1575 } else {
1576 // If we get here, this is a second reference to a specific name. Since
1577 // we already have checked that the first reference is valid, we don't
1578 // have to recursively match it, just check that it's the same as the
1579 // previously named thing.
1580 OS << " if (" << VarMapEntry << " != " << RootName << i
1581 << ") goto P" << PatternNo << "Fail;\n";
1582 continue;
1583 }
1584 }
1585
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001586 // Handle leaves of various types.
Chris Lattner2f041d42005-10-19 04:41:05 +00001587 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1588 Record *LeafRec = DI->getDef();
1589 if (LeafRec->isSubClassOf("RegisterClass")) {
1590 // Handle register references. Nothing to do here.
1591 } else if (LeafRec->isSubClassOf("ValueType")) {
1592 // Make sure this is the specified value type.
1593 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1594 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1595 << "Fail;\n";
Chris Lattner1531f202005-10-26 16:59:37 +00001596 } else if (LeafRec->isSubClassOf("CondCode")) {
1597 // Make sure this is the specified cond code.
1598 OS << " if (cast<CondCodeSDNode>(" << RootName << i
Chris Lattnera7ad1982005-10-26 17:02:02 +00001599 << ")->get() != " << "ISD::" << LeafRec->getName()
Chris Lattner1531f202005-10-26 16:59:37 +00001600 << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner2f041d42005-10-19 04:41:05 +00001601 } else {
1602 Child->dump();
1603 assert(0 && "Unknown leaf type!");
1604 }
1605 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1606 OS << " if (!isa<ConstantSDNode>(" << RootName << i << ") ||\n"
1607 << " cast<ConstantSDNode>(" << RootName << i
Chris Lattner9d1a0232005-10-29 16:39:40 +00001608 << ")->getSignExtended() != " << II->getValue() << ")\n"
Chris Lattner2f041d42005-10-19 04:41:05 +00001609 << " goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001610 } else {
1611 Child->dump();
1612 assert(0 && "Unknown leaf type!");
1613 }
1614 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001615 }
1616
1617 // If there is a node predicate for this, emit the call.
1618 if (!N->getPredicateFn().empty())
1619 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001620 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001621}
1622
Chris Lattner6bc7e512005-09-26 21:53:26 +00001623/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1624/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001625unsigned DAGISelEmitter::
1626CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1627 std::map<std::string,std::string> &VariableMap,
Chris Lattner5024d932005-10-16 01:41:58 +00001628 std::ostream &OS, bool isRoot) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001629 // This is something selected from the pattern we matched.
1630 if (!N->getName().empty()) {
Chris Lattner5024d932005-10-16 01:41:58 +00001631 assert(!isRoot && "Root of pattern cannot be a leaf!");
Chris Lattner6bc7e512005-09-26 21:53:26 +00001632 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001633 assert(!Val.empty() &&
1634 "Variable referenced but not defined and not caught earlier!");
1635 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1636 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001637 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001638 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001639
1640 unsigned ResNo = Ctr++;
1641 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1642 switch (N->getType()) {
1643 default: assert(0 && "Unknown type for constant node!");
1644 case MVT::i1: OS << " bool Tmp"; break;
1645 case MVT::i8: OS << " unsigned char Tmp"; break;
1646 case MVT::i16: OS << " unsigned short Tmp"; break;
1647 case MVT::i32: OS << " unsigned Tmp"; break;
1648 case MVT::i64: OS << " uint64_t Tmp"; break;
1649 }
1650 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1651 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1652 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1653 } else {
1654 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1655 }
1656 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1657 // value if used multiple times by this pattern result.
1658 Val = "Tmp"+utostr(ResNo);
1659 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001660 }
1661
1662 if (N->isLeaf()) {
Chris Lattner4c593092005-10-19 02:07:26 +00001663 // If this is an explicit register reference, handle it.
1664 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1665 unsigned ResNo = Ctr++;
1666 if (DI->getDef()->isSubClassOf("Register")) {
1667 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1668 << getQualifiedName(DI->getDef()) << ", MVT::"
1669 << getEnumName(N->getType())
1670 << ");\n";
1671 return ResNo;
1672 }
Chris Lattner5d5a0562005-10-19 04:30:56 +00001673 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1674 unsigned ResNo = Ctr++;
1675 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1676 << II->getValue() << ", MVT::"
1677 << getEnumName(N->getType())
1678 << ");\n";
1679 return ResNo;
Chris Lattner4c593092005-10-19 02:07:26 +00001680 }
1681
Chris Lattner72fe91c2005-09-24 00:40:24 +00001682 N->dump();
1683 assert(0 && "Unknown leaf type!");
1684 return ~0U;
1685 }
1686
1687 Record *Op = N->getOperator();
1688 if (Op->isSubClassOf("Instruction")) {
1689 // Emit all of the operands.
1690 std::vector<unsigned> Ops;
1691 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1692 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1693
1694 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1695 unsigned ResNo = Ctr++;
1696
Chris Lattner5024d932005-10-16 01:41:58 +00001697 if (!isRoot) {
1698 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1699 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1700 << getEnumName(N->getType());
1701 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1702 OS << ", Tmp" << Ops[i];
1703 OS << ");\n";
1704 } else {
1705 // If this instruction is the root, and if there is only one use of it,
1706 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1707 OS << " if (N.Val->hasOneUse()) {\n";
1708 OS << " CurDAG->SelectNodeTo(N.Val, "
1709 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1710 << getEnumName(N->getType());
1711 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1712 OS << ", Tmp" << Ops[i];
1713 OS << ");\n";
1714 OS << " return N;\n";
1715 OS << " } else {\n";
1716 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
1717 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1718 << getEnumName(N->getType());
1719 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1720 OS << ", Tmp" << Ops[i];
1721 OS << ");\n";
1722 OS << " }\n";
1723 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001724 return ResNo;
1725 } else if (Op->isSubClassOf("SDNodeXForm")) {
1726 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1727 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1728
1729 unsigned ResNo = Ctr++;
1730 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1731 << "(Tmp" << OpVal << ".Val);\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001732 if (isRoot) {
1733 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
1734 OS << " return Tmp" << ResNo << ";\n";
1735 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001736 return ResNo;
1737 } else {
1738 N->dump();
1739 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001740 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001741 }
1742}
1743
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001744/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1745/// type information from it.
1746static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001747 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001748 if (!N->isLeaf())
1749 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1750 RemoveAllTypes(N->getChild(i));
1751}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001752
Chris Lattner7e82f132005-10-15 21:34:21 +00001753/// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1754/// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1755/// 'Pat' may be missing types. If we find an unresolved type to add a check
1756/// for, this returns true otherwise false if Pat has all types.
1757static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1758 const std::string &Prefix, unsigned PatternNo,
1759 std::ostream &OS) {
1760 // Did we find one?
1761 if (!Pat->hasTypeSet()) {
1762 // Move a type over from 'other' to 'pat'.
1763 Pat->setType(Other->getType());
1764 OS << " if (" << Prefix << ".getValueType() != MVT::"
1765 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1766 return true;
1767 } else if (Pat->isLeaf()) {
1768 return false;
1769 }
1770
1771 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1772 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1773 Prefix + utostr(i), PatternNo, OS))
1774 return true;
1775 return false;
1776}
1777
Chris Lattner0614b622005-11-02 06:49:14 +00001778Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1779 Record *N = Records.getDef(Name);
1780 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1781 return N;
1782}
1783
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001784/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1785/// stream to match the pattern, and generate the code for the match if it
1786/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001787void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1788 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001789 static unsigned PatternCount = 0;
1790 unsigned PatternNo = PatternCount++;
1791 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001792 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001793 OS << "\n // Emits: ";
1794 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001795 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001796 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1797 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001798
Chris Lattner8fc35682005-09-23 23:16:51 +00001799 // Emit the matcher, capturing named arguments in VariableMap.
1800 std::map<std::string,std::string> VariableMap;
1801 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001802
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001803 // TP - Get *SOME* tree pattern, we don't care which.
1804 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001805
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001806 // At this point, we know that we structurally match the pattern, but the
1807 // types of the nodes may not match. Figure out the fewest number of type
1808 // comparisons we need to emit. For example, if there is only one integer
1809 // type supported by a target, there should be no type comparisons at all for
1810 // integer patterns!
1811 //
1812 // To figure out the fewest number of type checks needed, clone the pattern,
1813 // remove the types, then perform type inference on the pattern as a whole.
1814 // If there are unresolved types, emit an explicit check for those types,
1815 // apply the type to the tree, then rerun type inference. Iterate until all
1816 // types are resolved.
1817 //
1818 TreePatternNode *Pat = Pattern.first->clone();
1819 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001820
1821 do {
1822 // Resolve/propagate as many types as possible.
1823 try {
1824 bool MadeChange = true;
1825 while (MadeChange)
1826 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1827 } catch (...) {
1828 assert(0 && "Error: could not find consistent types for something we"
1829 " already decided was ok!");
1830 abort();
1831 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001832
Chris Lattner7e82f132005-10-15 21:34:21 +00001833 // Insert a check for an unresolved type and add it to the tree. If we find
1834 // an unresolved type to add a check for, this returns true and we iterate,
1835 // otherwise we are done.
1836 } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001837
Chris Lattner5024d932005-10-16 01:41:58 +00001838 unsigned TmpNo = 0;
1839 CodeGenPatternResult(Pattern.second, TmpNo,
1840 VariableMap, OS, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001841 delete Pat;
1842
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001843 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001844}
1845
Chris Lattner37481472005-09-26 21:59:35 +00001846
1847namespace {
1848 /// CompareByRecordName - An ordering predicate that implements less-than by
1849 /// comparing the names records.
1850 struct CompareByRecordName {
1851 bool operator()(const Record *LHS, const Record *RHS) const {
1852 // Sort by name first.
1853 if (LHS->getName() < RHS->getName()) return true;
1854 // If both names are equal, sort by pointer.
1855 return LHS->getName() == RHS->getName() && LHS < RHS;
1856 }
1857 };
1858}
1859
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001860void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001861 std::string InstNS = Target.inst_begin()->second.Namespace;
1862 if (!InstNS.empty()) InstNS += "::";
1863
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001864 // Emit boilerplate.
1865 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001866 << "SDOperand SelectCode(SDOperand N) {\n"
1867 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001868 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1869 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001870 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001871 << " if (!N.Val->hasOneUse()) {\n"
1872 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1873 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1874 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001875 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001876 << " default: break;\n"
1877 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001878 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001879 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001880 << " case ISD::AssertZext: {\n"
1881 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1882 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1883 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001884 << " }\n"
1885 << " case ISD::TokenFactor:\n"
1886 << " if (N.getNumOperands() == 2) {\n"
1887 << " SDOperand Op0 = Select(N.getOperand(0));\n"
1888 << " SDOperand Op1 = Select(N.getOperand(1));\n"
1889 << " return CodeGenMap[N] =\n"
1890 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
1891 << " } else {\n"
1892 << " std::vector<SDOperand> Ops;\n"
1893 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1894 << " Ops.push_back(Select(N.getOperand(i)));\n"
1895 << " return CodeGenMap[N] = \n"
1896 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
1897 << " }\n"
1898 << " case ISD::CopyFromReg: {\n"
1899 << " SDOperand Chain = Select(N.getOperand(0));\n"
1900 << " if (Chain == N.getOperand(0)) return N; // No change\n"
1901 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
1902 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
1903 << " N.Val->getValueType(0));\n"
1904 << " return New.getValue(N.ResNo);\n"
1905 << " }\n"
1906 << " case ISD::CopyToReg: {\n"
1907 << " SDOperand Chain = Select(N.getOperand(0));\n"
1908 << " SDOperand Reg = N.getOperand(1);\n"
1909 << " SDOperand Val = Select(N.getOperand(2));\n"
1910 << " return CodeGenMap[N] = \n"
1911 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
1912 << " Chain, Reg, Val);\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001913 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001914
Chris Lattner81303322005-09-23 19:36:15 +00001915 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001916 std::map<Record*, std::vector<PatternToMatch*>,
1917 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001918 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
Chris Lattner0614b622005-11-02 06:49:14 +00001919 if (!PatternsToMatch[i].first->isLeaf()) {
1920 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1921 .push_back(&PatternsToMatch[i]);
1922 } else {
1923 if (IntInit *II =
1924 dynamic_cast<IntInit*>(PatternsToMatch[i].first->getLeafValue())) {
1925 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
1926 } else {
1927 assert(0 && "Unknown leaf value");
1928 }
1929 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001930
Chris Lattner3f7e9142005-09-23 20:52:47 +00001931 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001932 for (std::map<Record*, std::vector<PatternToMatch*>,
1933 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1934 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001935 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1936 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1937
1938 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001939
1940 // We want to emit all of the matching code now. However, we want to emit
1941 // the matches in order of minimal cost. Sort the patterns so the least
1942 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001943 std::stable_sort(Patterns.begin(), Patterns.end(),
1944 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001945
Chris Lattner3f7e9142005-09-23 20:52:47 +00001946 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1947 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001948 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001949 }
1950
1951
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001952 OS << " } // end of big switch.\n\n"
1953 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001954 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001955 << " std::cerr << '\\n';\n"
1956 << " abort();\n"
1957 << "}\n";
1958}
1959
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001960void DAGISelEmitter::run(std::ostream &OS) {
1961 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1962 " target", OS);
1963
Chris Lattner1f39e292005-09-14 00:09:24 +00001964 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1965 << "// *** instruction selector class. These functions are really "
1966 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001967
Chris Lattner296dfe32005-09-24 00:50:51 +00001968 OS << "// Instance var to keep track of multiply used nodes that have \n"
1969 << "// already been selected.\n"
1970 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1971
Chris Lattnerca559d02005-09-08 21:03:01 +00001972 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001973 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001974 ParsePatternFragments(OS);
1975 ParseInstructions();
1976 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001977
Chris Lattnere97603f2005-09-28 19:27:25 +00001978 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00001979 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00001980 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001981
Chris Lattnere46e17b2005-09-29 19:28:10 +00001982
1983 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1984 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1985 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1986 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1987 std::cerr << "\n";
1988 });
1989
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001990 // At this point, we have full information about the 'Patterns' we need to
1991 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001992 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001993 EmitInstructionSelector(OS);
1994
1995 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1996 E = PatternFragments.end(); I != E; ++I)
1997 delete I->second;
1998 PatternFragments.clear();
1999
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002000 Instructions.clear();
2001}