blob: fb52355bee121095b989270170ac8124e6261942 [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);
624 } else {
625 Arg->dump();
626 error("Unknown leaf value for tree pattern!");
627 return 0;
628 }
629
Chris Lattner32707602005-09-08 23:22:48 +0000630 // Apply the type cast.
631 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000632 return New;
633 }
634
635 // Verify that this is something that makes sense for an operator.
636 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000637 !Operator->isSubClassOf("Instruction") &&
638 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000639 Operator->getName() != "set")
640 error("Unrecognized node '" + Operator->getName() + "'!");
641
Chris Lattneredbd8712005-10-21 01:19:59 +0000642 // Check to see if this is something that is illegal in an input pattern.
643 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
644 Operator->isSubClassOf("SDNodeXForm")))
645 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
646
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000647 std::vector<TreePatternNode*> Children;
648
649 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
650 Init *Arg = Dag->getArg(i);
651 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
652 Children.push_back(ParseTreePattern(DI));
653 Children.back()->setName(Dag->getArgName(i));
654 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
655 Record *R = DefI->getDef();
656 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
657 // TreePatternNode if its own.
658 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
659 Dag->setArg(i, new DagInit(R,
660 std::vector<std::pair<Init*, std::string> >()));
661 --i; // Revisit this node...
662 } else {
663 TreePatternNode *Node = new TreePatternNode(DefI);
664 Node->setName(Dag->getArgName(i));
665 Children.push_back(Node);
666
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000667 // Input argument?
668 if (R->getName() == "node") {
669 if (Dag->getArgName(i).empty())
670 error("'node' argument requires a name to match with operand list");
671 Args.push_back(Dag->getArgName(i));
672 }
673 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000674 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
675 TreePatternNode *Node = new TreePatternNode(II);
676 if (!Dag->getArgName(i).empty())
677 error("Constant int argument should not have a name!");
678 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000679 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000680 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000681 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000682 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000683 error("Unknown leaf value for tree pattern!");
684 }
685 }
686
687 return new TreePatternNode(Operator, Children);
688}
689
Chris Lattner32707602005-09-08 23:22:48 +0000690/// InferAllTypes - Infer/propagate as many types throughout the expression
691/// patterns as possible. Return true if all types are infered, false
692/// otherwise. Throw an exception if a type contradiction is found.
693bool TreePattern::InferAllTypes() {
694 bool MadeChange = true;
695 while (MadeChange) {
696 MadeChange = false;
697 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000698 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000699 }
700
701 bool HasUnresolvedTypes = false;
702 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
703 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
704 return !HasUnresolvedTypes;
705}
706
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000707void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000708 OS << getRecord()->getName();
709 if (!Args.empty()) {
710 OS << "(" << Args[0];
711 for (unsigned i = 1, e = Args.size(); i != e; ++i)
712 OS << ", " << Args[i];
713 OS << ")";
714 }
715 OS << ": ";
716
717 if (Trees.size() > 1)
718 OS << "[\n";
719 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
720 OS << "\t";
721 Trees[i]->print(OS);
722 OS << "\n";
723 }
724
725 if (Trees.size() > 1)
726 OS << "]\n";
727}
728
729void TreePattern::dump() const { print(std::cerr); }
730
731
732
733//===----------------------------------------------------------------------===//
734// DAGISelEmitter implementation
735//
736
Chris Lattnerca559d02005-09-08 21:03:01 +0000737// Parse all of the SDNode definitions for the target, populating SDNodes.
738void DAGISelEmitter::ParseNodeInfo() {
739 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
740 while (!Nodes.empty()) {
741 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
742 Nodes.pop_back();
743 }
744}
745
Chris Lattner24eeeb82005-09-13 21:51:00 +0000746/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
747/// map, and emit them to the file as functions.
748void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
749 OS << "\n// Node transformations.\n";
750 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
751 while (!Xforms.empty()) {
752 Record *XFormNode = Xforms.back();
753 Record *SDNode = XFormNode->getValueAsDef("Opcode");
754 std::string Code = XFormNode->getValueAsCode("XFormFunction");
755 SDNodeXForms.insert(std::make_pair(XFormNode,
756 std::make_pair(SDNode, Code)));
757
Chris Lattner1048b7a2005-09-13 22:03:37 +0000758 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000759 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
760 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
761
Chris Lattner1048b7a2005-09-13 22:03:37 +0000762 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000763 << "(SDNode *" << C2 << ") {\n";
764 if (ClassName != "SDNode")
765 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
766 OS << Code << "\n}\n";
767 }
768
769 Xforms.pop_back();
770 }
771}
772
773
774
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000775/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
776/// file, building up the PatternFragments map. After we've collected them all,
777/// inline fragments together as necessary, so that there are no references left
778/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000779///
780/// This also emits all of the predicate functions to the output file.
781///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000782void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000783 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
784
785 // First step, parse all of the fragments and emit predicate functions.
786 OS << "\n// Predicate functions.\n";
787 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000788 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000789 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000790 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000791
792 // Validate the argument list, converting it to map, to discard duplicates.
793 std::vector<std::string> &Args = P->getArgList();
794 std::set<std::string> OperandsMap(Args.begin(), Args.end());
795
796 if (OperandsMap.count(""))
797 P->error("Cannot have unnamed 'node' values in pattern fragment!");
798
799 // Parse the operands list.
800 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
801 if (OpsList->getNodeType()->getName() != "ops")
802 P->error("Operands list should start with '(ops ... '!");
803
804 // Copy over the arguments.
805 Args.clear();
806 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
807 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
808 static_cast<DefInit*>(OpsList->getArg(j))->
809 getDef()->getName() != "node")
810 P->error("Operands list should all be 'node' values.");
811 if (OpsList->getArgName(j).empty())
812 P->error("Operands list should have names for each operand!");
813 if (!OperandsMap.count(OpsList->getArgName(j)))
814 P->error("'" + OpsList->getArgName(j) +
815 "' does not occur in pattern or was multiply specified!");
816 OperandsMap.erase(OpsList->getArgName(j));
817 Args.push_back(OpsList->getArgName(j));
818 }
819
820 if (!OperandsMap.empty())
821 P->error("Operands list does not contain an entry for operand '" +
822 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000823
824 // If there is a code init for this fragment, emit the predicate code and
825 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000826 std::string Code = Fragments[i]->getValueAsCode("Predicate");
827 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000828 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000829 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000830 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000831 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
832
Chris Lattner1048b7a2005-09-13 22:03:37 +0000833 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000834 << "(SDNode *" << C2 << ") {\n";
835 if (ClassName != "SDNode")
836 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000837 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000838 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000839 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000840
841 // If there is a node transformation corresponding to this, keep track of
842 // it.
843 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
844 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000845 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000846 }
847
848 OS << "\n\n";
849
850 // Now that we've parsed all of the tree fragments, do a closure on them so
851 // that there are not references to PatFrags left inside of them.
852 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
853 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000854 TreePattern *ThePat = I->second;
855 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000856
Chris Lattner32707602005-09-08 23:22:48 +0000857 // Infer as many types as possible. Don't worry about it if we don't infer
858 // all of them, some may depend on the inputs of the pattern.
859 try {
860 ThePat->InferAllTypes();
861 } catch (...) {
862 // If this pattern fragment is not supported by this target (no types can
863 // satisfy its constraints), just ignore it. If the bogus pattern is
864 // actually used by instructions, the type consistency error will be
865 // reported there.
866 }
867
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000868 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000869 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000870 }
871}
872
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000873/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000874/// instruction input. Return true if this is a real use.
875static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000876 std::map<std::string, TreePatternNode*> &InstInputs) {
877 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000878 if (Pat->getName().empty()) {
879 if (Pat->isLeaf()) {
880 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
881 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
882 I->error("Input " + DI->getDef()->getName() + " must be named!");
883
884 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000885 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000886 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000887
888 Record *Rec;
889 if (Pat->isLeaf()) {
890 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
891 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
892 Rec = DI->getDef();
893 } else {
894 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
895 Rec = Pat->getOperator();
896 }
897
898 TreePatternNode *&Slot = InstInputs[Pat->getName()];
899 if (!Slot) {
900 Slot = Pat;
901 } else {
902 Record *SlotRec;
903 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000904 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000905 } else {
906 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
907 SlotRec = Slot->getOperator();
908 }
909
910 // Ensure that the inputs agree if we've already seen this input.
911 if (Rec != SlotRec)
912 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000913 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000914 I->error("All $" + Pat->getName() + " inputs must agree with each other");
915 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000916 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000917}
918
919/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
920/// part of "I", the instruction), computing the set of inputs and outputs of
921/// the pattern. Report errors if we see anything naughty.
922void DAGISelEmitter::
923FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
924 std::map<std::string, TreePatternNode*> &InstInputs,
925 std::map<std::string, Record*> &InstResults) {
926 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000927 bool isUse = HandleUse(I, Pat, InstInputs);
928 if (!isUse && Pat->getTransformFn())
929 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000930 return;
931 } else if (Pat->getOperator()->getName() != "set") {
932 // If this is not a set, verify that the children nodes are not void typed,
933 // and recurse.
934 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000935 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000936 I->error("Cannot have void nodes inside of patterns!");
937 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
938 }
939
940 // If this is a non-leaf node with no children, treat it basically as if
941 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000942 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000943 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000944 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000945
Chris Lattnerf1311842005-09-14 23:05:13 +0000946 if (!isUse && Pat->getTransformFn())
947 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000948 return;
949 }
950
951 // Otherwise, this is a set, validate and collect instruction results.
952 if (Pat->getNumChildren() == 0)
953 I->error("set requires operands!");
954 else if (Pat->getNumChildren() & 1)
955 I->error("set requires an even number of operands");
956
Chris Lattnerf1311842005-09-14 23:05:13 +0000957 if (Pat->getTransformFn())
958 I->error("Cannot specify a transform function on a set node!");
959
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000960 // Check the set destinations.
961 unsigned NumValues = Pat->getNumChildren()/2;
962 for (unsigned i = 0; i != NumValues; ++i) {
963 TreePatternNode *Dest = Pat->getChild(i);
964 if (!Dest->isLeaf())
965 I->error("set destination should be a virtual register!");
966
967 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
968 if (!Val)
969 I->error("set destination should be a virtual register!");
970
971 if (!Val->getDef()->isSubClassOf("RegisterClass"))
972 I->error("set destination should be a virtual register!");
973 if (Dest->getName().empty())
974 I->error("set destination must have a name!");
975 if (InstResults.count(Dest->getName()))
976 I->error("cannot set '" + Dest->getName() +"' multiple times");
977 InstResults[Dest->getName()] = Val->getDef();
978
979 // Verify and collect info from the computation.
980 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
981 InstInputs, InstResults);
982 }
983}
984
985
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000986/// ParseInstructions - Parse all of the instructions, inlining and resolving
987/// any fragments involved. This populates the Instructions list with fully
988/// resolved instructions.
989void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000990 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
991
992 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +0000993 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000994
Chris Lattner0c0cfa72005-10-19 01:27:22 +0000995 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
996 LI = Instrs[i]->getValueAsListInit("Pattern");
997
998 // If there is no pattern, only collect minimal information about the
999 // instruction for its operand list. We have to assume that there is one
1000 // result, as we have no detailed info.
1001 if (!LI || LI->getSize() == 0) {
1002 std::vector<MVT::ValueType> ResultTypes;
1003 std::vector<MVT::ValueType> OperandTypes;
1004
1005 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1006
1007 // Doesn't even define a result?
1008 if (InstInfo.OperandList.size() == 0)
1009 continue;
1010
1011 // Assume the first operand is the result.
1012 ResultTypes.push_back(InstInfo.OperandList[0].Ty);
1013
1014 // The rest are inputs.
1015 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1016 OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1017
1018 // Create and insert the instruction.
1019 Instructions.insert(std::make_pair(Instrs[i],
1020 DAGInstruction(0, ResultTypes, OperandTypes)));
1021 continue; // no pattern.
1022 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001023
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001024 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001025 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001026 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001027 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001028
Chris Lattner95f6b762005-09-08 23:26:30 +00001029 // Infer as many types as possible. If we cannot infer all of them, we can
1030 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001031 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001032 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001033
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001034 // InstInputs - Keep track of all of the inputs of the instruction, along
1035 // with the record they are declared as.
1036 std::map<std::string, TreePatternNode*> InstInputs;
1037
1038 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001039 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001040 std::map<std::string, Record*> InstResults;
1041
Chris Lattner1f39e292005-09-14 00:09:24 +00001042 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001043 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001044 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1045 TreePatternNode *Pat = I->getTree(j);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001046 if (Pat->getExtType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001047 I->dump();
1048 I->error("Top-level forms in instruction pattern should have"
1049 " void types");
1050 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001051
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001052 // Find inputs and outputs, and verify the structure of the uses/defs.
1053 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001054 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001055
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001056 // Now that we have inputs and outputs of the pattern, inspect the operands
1057 // list for the instruction. This determines the order that operands are
1058 // added to the machine instruction the node corresponds to.
1059 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001060
1061 // Parse the operands list from the (ops) list, validating it.
1062 std::vector<std::string> &Args = I->getArgList();
1063 assert(Args.empty() && "Args list should still be empty here!");
1064 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1065
1066 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +00001067 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +00001068 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001069 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001070 I->error("'" + InstResults.begin()->first +
1071 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001072 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001073
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001074 // Check that it exists in InstResults.
1075 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001076 if (R == 0)
1077 I->error("Operand $" + OpName + " should be a set destination: all "
1078 "outputs must occur before inputs in operand list!");
1079
1080 if (CGI.OperandList[i].Rec != R)
1081 I->error("Operand $" + OpName + " class mismatch!");
1082
Chris Lattnerae6d8282005-09-15 21:51:12 +00001083 // Remember the return type.
1084 ResultTypes.push_back(CGI.OperandList[i].Ty);
1085
Chris Lattner39e8af92005-09-14 18:19:25 +00001086 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001087 InstResults.erase(OpName);
1088 }
1089
Chris Lattner0b592252005-09-14 21:59:34 +00001090 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1091 // the copy while we're checking the inputs.
1092 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001093
1094 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +00001095 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001096 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1097 const std::string &OpName = CGI.OperandList[i].Name;
1098 if (OpName.empty())
1099 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1100
Chris Lattner0b592252005-09-14 21:59:34 +00001101 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001102 I->error("Operand $" + OpName +
1103 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001104 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001105 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001106 if (CGI.OperandList[i].Ty != InVal->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001107 I->error("Operand $" + OpName +
1108 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +00001109 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +00001110
Chris Lattner2175c182005-09-14 23:01:59 +00001111 // Construct the result for the dest-pattern operand list.
1112 TreePatternNode *OpNode = InVal->clone();
1113
1114 // No predicate is useful on the result.
1115 OpNode->setPredicateFn("");
1116
1117 // Promote the xform function to be an explicit node if set.
1118 if (Record *Xform = OpNode->getTransformFn()) {
1119 OpNode->setTransformFn(0);
1120 std::vector<TreePatternNode*> Children;
1121 Children.push_back(OpNode);
1122 OpNode = new TreePatternNode(Xform, Children);
1123 }
1124
1125 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001126 }
1127
Chris Lattner0b592252005-09-14 21:59:34 +00001128 if (!InstInputsCheck.empty())
1129 I->error("Input operand $" + InstInputsCheck.begin()->first +
1130 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001131
1132 TreePatternNode *ResultPattern =
1133 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001134
1135 // Create and insert the instruction.
1136 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1137 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1138
1139 // Use a temporary tree pattern to infer all types and make sure that the
1140 // constructed result is correct. This depends on the instruction already
1141 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001142 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001143 Temp.InferAllTypes();
1144
1145 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1146 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001147
Chris Lattner32707602005-09-08 23:22:48 +00001148 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001149 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001150
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001151 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001152 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1153 E = Instructions.end(); II != E; ++II) {
1154 TreePattern *I = II->second.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001155 if (I == 0) continue; // No pattern.
Chris Lattner1f39e292005-09-14 00:09:24 +00001156
1157 if (I->getNumTrees() != 1) {
1158 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1159 continue;
1160 }
1161 TreePatternNode *Pattern = I->getTree(0);
1162 if (Pattern->getOperator()->getName() != "set")
1163 continue; // Not a set (store or something?)
1164
1165 if (Pattern->getNumChildren() != 2)
1166 continue; // Not a set of a single value (not handled so far)
1167
1168 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001169
1170 std::string Reason;
1171 if (!SrcPattern->canPatternMatch(Reason, *this))
1172 I->error("Instruction can never match: " + Reason);
1173
Chris Lattnerae5b3502005-09-15 21:57:35 +00001174 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001175 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001176 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001177}
1178
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001179void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001180 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001181
Chris Lattnerabbb6052005-09-15 21:42:00 +00001182 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001183 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001184 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001185
Chris Lattnerabbb6052005-09-15 21:42:00 +00001186 // Inline pattern fragments into it.
1187 Pattern->InlinePatternFragments();
1188
1189 // Infer as many types as possible. If we cannot infer all of them, we can
1190 // never do anything with this pattern: report it to the user.
1191 if (!Pattern->InferAllTypes())
1192 Pattern->error("Could not infer all types in pattern!");
1193
1194 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1195 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001196
1197 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001198 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001199
1200 // Inline pattern fragments into it.
1201 Result->InlinePatternFragments();
1202
1203 // Infer as many types as possible. If we cannot infer all of them, we can
1204 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001205 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001206 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001207
1208 if (Result->getNumTrees() != 1)
1209 Result->error("Cannot handle instructions producing instructions "
1210 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001211
1212 std::string Reason;
1213 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1214 Pattern->error("Pattern can never match: " + Reason);
1215
Chris Lattnerabbb6052005-09-15 21:42:00 +00001216 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1217 Result->getOnlyTree()));
1218 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001219}
1220
Chris Lattnere46e17b2005-09-29 19:28:10 +00001221/// CombineChildVariants - Given a bunch of permutations of each child of the
1222/// 'operator' node, put them together in all possible ways.
1223static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001224 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001225 std::vector<TreePatternNode*> &OutVariants,
1226 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001227 // Make sure that each operand has at least one variant to choose from.
1228 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1229 if (ChildVariants[i].empty())
1230 return;
1231
Chris Lattnere46e17b2005-09-29 19:28:10 +00001232 // The end result is an all-pairs construction of the resultant pattern.
1233 std::vector<unsigned> Idxs;
1234 Idxs.resize(ChildVariants.size());
1235 bool NotDone = true;
1236 while (NotDone) {
1237 // Create the variant and add it to the output list.
1238 std::vector<TreePatternNode*> NewChildren;
1239 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1240 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1241 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1242
1243 // Copy over properties.
1244 R->setName(Orig->getName());
1245 R->setPredicateFn(Orig->getPredicateFn());
1246 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001247 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001248
1249 // If this pattern cannot every match, do not include it as a variant.
1250 std::string ErrString;
1251 if (!R->canPatternMatch(ErrString, ISE)) {
1252 delete R;
1253 } else {
1254 bool AlreadyExists = false;
1255
1256 // Scan to see if this pattern has already been emitted. We can get
1257 // duplication due to things like commuting:
1258 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1259 // which are the same pattern. Ignore the dups.
1260 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1261 if (R->isIsomorphicTo(OutVariants[i])) {
1262 AlreadyExists = true;
1263 break;
1264 }
1265
1266 if (AlreadyExists)
1267 delete R;
1268 else
1269 OutVariants.push_back(R);
1270 }
1271
1272 // Increment indices to the next permutation.
1273 NotDone = false;
1274 // Look for something we can increment without causing a wrap-around.
1275 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1276 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1277 NotDone = true; // Found something to increment.
1278 break;
1279 }
1280 Idxs[IdxsIdx] = 0;
1281 }
1282 }
1283}
1284
Chris Lattneraf302912005-09-29 22:36:54 +00001285/// CombineChildVariants - A helper function for binary operators.
1286///
1287static void CombineChildVariants(TreePatternNode *Orig,
1288 const std::vector<TreePatternNode*> &LHS,
1289 const std::vector<TreePatternNode*> &RHS,
1290 std::vector<TreePatternNode*> &OutVariants,
1291 DAGISelEmitter &ISE) {
1292 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1293 ChildVariants.push_back(LHS);
1294 ChildVariants.push_back(RHS);
1295 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1296}
1297
1298
1299static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1300 std::vector<TreePatternNode *> &Children) {
1301 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1302 Record *Operator = N->getOperator();
1303
1304 // Only permit raw nodes.
1305 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1306 N->getTransformFn()) {
1307 Children.push_back(N);
1308 return;
1309 }
1310
1311 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1312 Children.push_back(N->getChild(0));
1313 else
1314 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1315
1316 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1317 Children.push_back(N->getChild(1));
1318 else
1319 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1320}
1321
Chris Lattnere46e17b2005-09-29 19:28:10 +00001322/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1323/// the (potentially recursive) pattern by using algebraic laws.
1324///
1325static void GenerateVariantsOf(TreePatternNode *N,
1326 std::vector<TreePatternNode*> &OutVariants,
1327 DAGISelEmitter &ISE) {
1328 // We cannot permute leaves.
1329 if (N->isLeaf()) {
1330 OutVariants.push_back(N);
1331 return;
1332 }
1333
1334 // Look up interesting info about the node.
1335 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1336
1337 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001338 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1339 // Reassociate by pulling together all of the linked operators
1340 std::vector<TreePatternNode*> MaximalChildren;
1341 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1342
1343 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1344 // permutations.
1345 if (MaximalChildren.size() == 3) {
1346 // Find the variants of all of our maximal children.
1347 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1348 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1349 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1350 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1351
1352 // There are only two ways we can permute the tree:
1353 // (A op B) op C and A op (B op C)
1354 // Within these forms, we can also permute A/B/C.
1355
1356 // Generate legal pair permutations of A/B/C.
1357 std::vector<TreePatternNode*> ABVariants;
1358 std::vector<TreePatternNode*> BAVariants;
1359 std::vector<TreePatternNode*> ACVariants;
1360 std::vector<TreePatternNode*> CAVariants;
1361 std::vector<TreePatternNode*> BCVariants;
1362 std::vector<TreePatternNode*> CBVariants;
1363 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1364 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1365 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1366 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1367 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1368 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1369
1370 // Combine those into the result: (x op x) op x
1371 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1372 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1373 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1374 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1375 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1376 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1377
1378 // Combine those into the result: x op (x op x)
1379 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1380 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1381 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1382 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1383 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1384 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1385 return;
1386 }
1387 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001388
1389 // Compute permutations of all children.
1390 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1391 ChildVariants.resize(N->getNumChildren());
1392 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1393 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1394
1395 // Build all permutations based on how the children were formed.
1396 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1397
1398 // If this node is commutative, consider the commuted order.
1399 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1400 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001401 // Consider the commuted order.
1402 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1403 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001404 }
1405}
1406
1407
Chris Lattnere97603f2005-09-28 19:27:25 +00001408// GenerateVariants - Generate variants. For example, commutative patterns can
1409// match multiple ways. Add them to PatternsToMatch as well.
1410void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001411
1412 DEBUG(std::cerr << "Generating instruction variants.\n");
1413
1414 // Loop over all of the patterns we've collected, checking to see if we can
1415 // generate variants of the instruction, through the exploitation of
1416 // identities. This permits the target to provide agressive matching without
1417 // the .td file having to contain tons of variants of instructions.
1418 //
1419 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1420 // intentionally do not reconsider these. Any variants of added patterns have
1421 // already been added.
1422 //
1423 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1424 std::vector<TreePatternNode*> Variants;
1425 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1426
1427 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001428 Variants.erase(Variants.begin()); // Remove the original pattern.
1429
1430 if (Variants.empty()) // No variants for this pattern.
1431 continue;
1432
1433 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1434 PatternsToMatch[i].first->dump();
1435 std::cerr << "\n");
1436
1437 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1438 TreePatternNode *Variant = Variants[v];
1439
1440 DEBUG(std::cerr << " VAR#" << v << ": ";
1441 Variant->dump();
1442 std::cerr << "\n");
1443
1444 // Scan to see if an instruction or explicit pattern already matches this.
1445 bool AlreadyExists = false;
1446 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1447 // Check to see if this variant already exists.
1448 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1449 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1450 AlreadyExists = true;
1451 break;
1452 }
1453 }
1454 // If we already have it, ignore the variant.
1455 if (AlreadyExists) continue;
1456
1457 // Otherwise, add it to the list of patterns we have.
1458 PatternsToMatch.push_back(std::make_pair(Variant,
1459 PatternsToMatch[i].second));
1460 }
1461
1462 DEBUG(std::cerr << "\n");
1463 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001464}
1465
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001466
Chris Lattner05814af2005-09-28 17:57:56 +00001467/// getPatternSize - Return the 'size' of this pattern. We want to match large
1468/// patterns before small ones. This is used to determine the size of a
1469/// pattern.
1470static unsigned getPatternSize(TreePatternNode *P) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001471 assert(isExtIntegerVT(P->getExtType()) ||
1472 isExtFloatingPointVT(P->getExtType()) &&
Chris Lattner05814af2005-09-28 17:57:56 +00001473 "Not a valid pattern node to size!");
1474 unsigned Size = 1; // The node itself.
1475
1476 // Count children in the count if they are also nodes.
1477 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1478 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001479 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Chris Lattner05814af2005-09-28 17:57:56 +00001480 Size += getPatternSize(Child);
Chris Lattner2f041d42005-10-19 04:41:05 +00001481 else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1482 ++Size; // Matches a ConstantSDNode.
1483 }
Chris Lattner05814af2005-09-28 17:57:56 +00001484 }
1485
1486 return Size;
1487}
1488
1489/// getResultPatternCost - Compute the number of instructions for this pattern.
1490/// This is a temporary hack. We should really include the instruction
1491/// latencies in this calculation.
1492static unsigned getResultPatternCost(TreePatternNode *P) {
1493 if (P->isLeaf()) return 0;
1494
1495 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1496 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1497 Cost += getResultPatternCost(P->getChild(i));
1498 return Cost;
1499}
1500
1501// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1502// In particular, we want to match maximal patterns first and lowest cost within
1503// a particular complexity first.
1504struct PatternSortingPredicate {
1505 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1506 DAGISelEmitter::PatternToMatch *RHS) {
1507 unsigned LHSSize = getPatternSize(LHS->first);
1508 unsigned RHSSize = getPatternSize(RHS->first);
1509 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1510 if (LHSSize < RHSSize) return false;
1511
1512 // If the patterns have equal complexity, compare generated instruction cost
1513 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1514 }
1515};
1516
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001517/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1518/// if the match fails. At this point, we already know that the opcode for N
1519/// matches, and the SDNode for the result has the RootName specified name.
1520void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001521 const std::string &RootName,
1522 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001523 unsigned PatternNo, std::ostream &OS) {
1524 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001525
1526 // If this node has a name associated with it, capture it in VarMap. If
1527 // we already saw this in the pattern, emit code to verify dagness.
1528 if (!N->getName().empty()) {
1529 std::string &VarMapEntry = VarMap[N->getName()];
1530 if (VarMapEntry.empty()) {
1531 VarMapEntry = RootName;
1532 } else {
1533 // If we get here, this is a second reference to a specific name. Since
1534 // we already have checked that the first reference is valid, we don't
1535 // have to recursively match it, just check that it's the same as the
1536 // previously named thing.
1537 OS << " if (" << VarMapEntry << " != " << RootName
1538 << ") goto P" << PatternNo << "Fail;\n";
1539 return;
1540 }
1541 }
1542
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001543 // Emit code to load the child nodes and match their contents recursively.
1544 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001545 OS << " SDOperand " << RootName << i <<" = " << RootName
1546 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001547 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001548
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001549 if (!Child->isLeaf()) {
1550 // If it's not a leaf, recursively match.
1551 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001552 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001553 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001554 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001555 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001556 // If this child has a name associated with it, capture it in VarMap. If
1557 // we already saw this in the pattern, emit code to verify dagness.
1558 if (!Child->getName().empty()) {
1559 std::string &VarMapEntry = VarMap[Child->getName()];
1560 if (VarMapEntry.empty()) {
1561 VarMapEntry = RootName + utostr(i);
1562 } else {
1563 // If we get here, this is a second reference to a specific name. Since
1564 // we already have checked that the first reference is valid, we don't
1565 // have to recursively match it, just check that it's the same as the
1566 // previously named thing.
1567 OS << " if (" << VarMapEntry << " != " << RootName << i
1568 << ") goto P" << PatternNo << "Fail;\n";
1569 continue;
1570 }
1571 }
1572
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001573 // Handle leaves of various types.
Chris Lattner2f041d42005-10-19 04:41:05 +00001574 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1575 Record *LeafRec = DI->getDef();
1576 if (LeafRec->isSubClassOf("RegisterClass")) {
1577 // Handle register references. Nothing to do here.
1578 } else if (LeafRec->isSubClassOf("ValueType")) {
1579 // Make sure this is the specified value type.
1580 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1581 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1582 << "Fail;\n";
Chris Lattner1531f202005-10-26 16:59:37 +00001583 } else if (LeafRec->isSubClassOf("CondCode")) {
1584 // Make sure this is the specified cond code.
1585 OS << " if (cast<CondCodeSDNode>(" << RootName << i
Chris Lattnera7ad1982005-10-26 17:02:02 +00001586 << ")->get() != " << "ISD::" << LeafRec->getName()
Chris Lattner1531f202005-10-26 16:59:37 +00001587 << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner2f041d42005-10-19 04:41:05 +00001588 } else {
1589 Child->dump();
1590 assert(0 && "Unknown leaf type!");
1591 }
1592 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1593 OS << " if (!isa<ConstantSDNode>(" << RootName << i << ") ||\n"
1594 << " cast<ConstantSDNode>(" << RootName << i
1595 << ")->getValue() != " << II->getValue() << ")\n"
1596 << " goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001597 } else {
1598 Child->dump();
1599 assert(0 && "Unknown leaf type!");
1600 }
1601 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001602 }
1603
1604 // If there is a node predicate for this, emit the call.
1605 if (!N->getPredicateFn().empty())
1606 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001607 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001608}
1609
Chris Lattner6bc7e512005-09-26 21:53:26 +00001610/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1611/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001612unsigned DAGISelEmitter::
1613CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1614 std::map<std::string,std::string> &VariableMap,
Chris Lattner5024d932005-10-16 01:41:58 +00001615 std::ostream &OS, bool isRoot) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001616 // This is something selected from the pattern we matched.
1617 if (!N->getName().empty()) {
Chris Lattner5024d932005-10-16 01:41:58 +00001618 assert(!isRoot && "Root of pattern cannot be a leaf!");
Chris Lattner6bc7e512005-09-26 21:53:26 +00001619 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001620 assert(!Val.empty() &&
1621 "Variable referenced but not defined and not caught earlier!");
1622 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1623 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001624 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001625 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001626
1627 unsigned ResNo = Ctr++;
1628 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1629 switch (N->getType()) {
1630 default: assert(0 && "Unknown type for constant node!");
1631 case MVT::i1: OS << " bool Tmp"; break;
1632 case MVT::i8: OS << " unsigned char Tmp"; break;
1633 case MVT::i16: OS << " unsigned short Tmp"; break;
1634 case MVT::i32: OS << " unsigned Tmp"; break;
1635 case MVT::i64: OS << " uint64_t Tmp"; break;
1636 }
1637 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1638 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1639 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1640 } else {
1641 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1642 }
1643 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1644 // value if used multiple times by this pattern result.
1645 Val = "Tmp"+utostr(ResNo);
1646 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001647 }
1648
1649 if (N->isLeaf()) {
Chris Lattner4c593092005-10-19 02:07:26 +00001650 // If this is an explicit register reference, handle it.
1651 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1652 unsigned ResNo = Ctr++;
1653 if (DI->getDef()->isSubClassOf("Register")) {
1654 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1655 << getQualifiedName(DI->getDef()) << ", MVT::"
1656 << getEnumName(N->getType())
1657 << ");\n";
1658 return ResNo;
1659 }
Chris Lattner5d5a0562005-10-19 04:30:56 +00001660 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1661 unsigned ResNo = Ctr++;
1662 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1663 << II->getValue() << ", MVT::"
1664 << getEnumName(N->getType())
1665 << ");\n";
1666 return ResNo;
Chris Lattner4c593092005-10-19 02:07:26 +00001667 }
1668
Chris Lattner72fe91c2005-09-24 00:40:24 +00001669 N->dump();
1670 assert(0 && "Unknown leaf type!");
1671 return ~0U;
1672 }
1673
1674 Record *Op = N->getOperator();
1675 if (Op->isSubClassOf("Instruction")) {
1676 // Emit all of the operands.
1677 std::vector<unsigned> Ops;
1678 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1679 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1680
1681 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1682 unsigned ResNo = Ctr++;
1683
Chris Lattner5024d932005-10-16 01:41:58 +00001684 if (!isRoot) {
1685 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1686 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1687 << getEnumName(N->getType());
1688 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1689 OS << ", Tmp" << Ops[i];
1690 OS << ");\n";
1691 } else {
1692 // If this instruction is the root, and if there is only one use of it,
1693 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1694 OS << " if (N.Val->hasOneUse()) {\n";
1695 OS << " CurDAG->SelectNodeTo(N.Val, "
1696 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1697 << getEnumName(N->getType());
1698 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1699 OS << ", Tmp" << Ops[i];
1700 OS << ");\n";
1701 OS << " return N;\n";
1702 OS << " } else {\n";
1703 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
1704 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1705 << getEnumName(N->getType());
1706 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1707 OS << ", Tmp" << Ops[i];
1708 OS << ");\n";
1709 OS << " }\n";
1710 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001711 return ResNo;
1712 } else if (Op->isSubClassOf("SDNodeXForm")) {
1713 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1714 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1715
1716 unsigned ResNo = Ctr++;
1717 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1718 << "(Tmp" << OpVal << ".Val);\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001719 if (isRoot) {
1720 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
1721 OS << " return Tmp" << ResNo << ";\n";
1722 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001723 return ResNo;
1724 } else {
1725 N->dump();
1726 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001727 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001728 }
1729}
1730
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001731/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1732/// type information from it.
1733static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001734 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001735 if (!N->isLeaf())
1736 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1737 RemoveAllTypes(N->getChild(i));
1738}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001739
Chris Lattner7e82f132005-10-15 21:34:21 +00001740/// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1741/// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1742/// 'Pat' may be missing types. If we find an unresolved type to add a check
1743/// for, this returns true otherwise false if Pat has all types.
1744static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1745 const std::string &Prefix, unsigned PatternNo,
1746 std::ostream &OS) {
1747 // Did we find one?
1748 if (!Pat->hasTypeSet()) {
1749 // Move a type over from 'other' to 'pat'.
1750 Pat->setType(Other->getType());
1751 OS << " if (" << Prefix << ".getValueType() != MVT::"
1752 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1753 return true;
1754 } else if (Pat->isLeaf()) {
1755 return false;
1756 }
1757
1758 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1759 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1760 Prefix + utostr(i), PatternNo, OS))
1761 return true;
1762 return false;
1763}
1764
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001765/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1766/// stream to match the pattern, and generate the code for the match if it
1767/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001768void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1769 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001770 static unsigned PatternCount = 0;
1771 unsigned PatternNo = PatternCount++;
1772 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001773 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001774 OS << "\n // Emits: ";
1775 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001776 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001777 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1778 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001779
Chris Lattner8fc35682005-09-23 23:16:51 +00001780 // Emit the matcher, capturing named arguments in VariableMap.
1781 std::map<std::string,std::string> VariableMap;
1782 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001783
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001784 // TP - Get *SOME* tree pattern, we don't care which.
1785 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001786
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001787 // At this point, we know that we structurally match the pattern, but the
1788 // types of the nodes may not match. Figure out the fewest number of type
1789 // comparisons we need to emit. For example, if there is only one integer
1790 // type supported by a target, there should be no type comparisons at all for
1791 // integer patterns!
1792 //
1793 // To figure out the fewest number of type checks needed, clone the pattern,
1794 // remove the types, then perform type inference on the pattern as a whole.
1795 // If there are unresolved types, emit an explicit check for those types,
1796 // apply the type to the tree, then rerun type inference. Iterate until all
1797 // types are resolved.
1798 //
1799 TreePatternNode *Pat = Pattern.first->clone();
1800 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001801
1802 do {
1803 // Resolve/propagate as many types as possible.
1804 try {
1805 bool MadeChange = true;
1806 while (MadeChange)
1807 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1808 } catch (...) {
1809 assert(0 && "Error: could not find consistent types for something we"
1810 " already decided was ok!");
1811 abort();
1812 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001813
Chris Lattner7e82f132005-10-15 21:34:21 +00001814 // Insert a check for an unresolved type and add it to the tree. If we find
1815 // an unresolved type to add a check for, this returns true and we iterate,
1816 // otherwise we are done.
1817 } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001818
Chris Lattner5024d932005-10-16 01:41:58 +00001819 unsigned TmpNo = 0;
1820 CodeGenPatternResult(Pattern.second, TmpNo,
1821 VariableMap, OS, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001822 delete Pat;
1823
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001824 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001825}
1826
Chris Lattner37481472005-09-26 21:59:35 +00001827
1828namespace {
1829 /// CompareByRecordName - An ordering predicate that implements less-than by
1830 /// comparing the names records.
1831 struct CompareByRecordName {
1832 bool operator()(const Record *LHS, const Record *RHS) const {
1833 // Sort by name first.
1834 if (LHS->getName() < RHS->getName()) return true;
1835 // If both names are equal, sort by pointer.
1836 return LHS->getName() == RHS->getName() && LHS < RHS;
1837 }
1838 };
1839}
1840
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001841void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001842 std::string InstNS = Target.inst_begin()->second.Namespace;
1843 if (!InstNS.empty()) InstNS += "::";
1844
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001845 // Emit boilerplate.
1846 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001847 << "SDOperand SelectCode(SDOperand N) {\n"
1848 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001849 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1850 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001851 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001852 << " if (!N.Val->hasOneUse()) {\n"
1853 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1854 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1855 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001856 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001857 << " default: break;\n"
1858 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001859 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001860 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001861 << " case ISD::AssertZext: {\n"
1862 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1863 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1864 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001865 << " }\n"
1866 << " case ISD::TokenFactor:\n"
1867 << " if (N.getNumOperands() == 2) {\n"
1868 << " SDOperand Op0 = Select(N.getOperand(0));\n"
1869 << " SDOperand Op1 = Select(N.getOperand(1));\n"
1870 << " return CodeGenMap[N] =\n"
1871 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
1872 << " } else {\n"
1873 << " std::vector<SDOperand> Ops;\n"
1874 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1875 << " Ops.push_back(Select(N.getOperand(i)));\n"
1876 << " return CodeGenMap[N] = \n"
1877 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
1878 << " }\n"
1879 << " case ISD::CopyFromReg: {\n"
1880 << " SDOperand Chain = Select(N.getOperand(0));\n"
1881 << " if (Chain == N.getOperand(0)) return N; // No change\n"
1882 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
1883 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
1884 << " N.Val->getValueType(0));\n"
1885 << " return New.getValue(N.ResNo);\n"
1886 << " }\n"
1887 << " case ISD::CopyToReg: {\n"
1888 << " SDOperand Chain = Select(N.getOperand(0));\n"
1889 << " SDOperand Reg = N.getOperand(1);\n"
1890 << " SDOperand Val = Select(N.getOperand(2));\n"
1891 << " return CodeGenMap[N] = \n"
1892 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
1893 << " Chain, Reg, Val);\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001894 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001895
Chris Lattner81303322005-09-23 19:36:15 +00001896 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001897 std::map<Record*, std::vector<PatternToMatch*>,
1898 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001899 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1900 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1901 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001902
Chris Lattner3f7e9142005-09-23 20:52:47 +00001903 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001904 for (std::map<Record*, std::vector<PatternToMatch*>,
1905 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1906 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001907 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1908 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1909
1910 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001911
1912 // We want to emit all of the matching code now. However, we want to emit
1913 // the matches in order of minimal cost. Sort the patterns so the least
1914 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001915 std::stable_sort(Patterns.begin(), Patterns.end(),
1916 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001917
Chris Lattner3f7e9142005-09-23 20:52:47 +00001918 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1919 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001920 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001921 }
1922
1923
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001924 OS << " } // end of big switch.\n\n"
1925 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001926 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001927 << " std::cerr << '\\n';\n"
1928 << " abort();\n"
1929 << "}\n";
1930}
1931
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001932void DAGISelEmitter::run(std::ostream &OS) {
1933 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1934 " target", OS);
1935
Chris Lattner1f39e292005-09-14 00:09:24 +00001936 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1937 << "// *** instruction selector class. These functions are really "
1938 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001939
Chris Lattner296dfe32005-09-24 00:50:51 +00001940 OS << "// Instance var to keep track of multiply used nodes that have \n"
1941 << "// already been selected.\n"
1942 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1943
Chris Lattnerca559d02005-09-08 21:03:01 +00001944 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001945 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001946 ParsePatternFragments(OS);
1947 ParseInstructions();
1948 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001949
Chris Lattnere97603f2005-09-28 19:27:25 +00001950 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00001951 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00001952 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001953
Chris Lattnere46e17b2005-09-29 19:28:10 +00001954
1955 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1956 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1957 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1958 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1959 std::cerr << "\n";
1960 });
1961
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001962 // At this point, we have full information about the 'Patterns' we need to
1963 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001964 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001965 EmitInstructionSelector(OS);
1966
1967 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1968 E = PatternFragments.end(); I != E; ++I)
1969 delete I->second;
1970 PatternFragments.clear();
1971
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001972 Instructions.clear();
1973}