blob: 8e6095c1063fc9fc80dc36f04a480b0e21b62acb [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;
Nate Begeman6510b222005-12-01 04:51:06 +0000458 const CodeGenRegisterClass &RC =
459 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
460 return RC.getValueTypeNum(0);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000461 } else if (R->isSubClassOf("PatFrag")) {
462 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000463 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000464 } else if (R->isSubClassOf("Register")) {
Chris Lattnerab1bf272005-10-19 01:55:23 +0000465 //const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
466 // TODO: if a register appears in exactly one regclass, we could use that
467 // type info.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000468 return MVT::isUnknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000469 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
470 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000471 return MVT::Other;
472 } else if (R->getName() == "node") {
473 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000474 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000475 }
476
477 TP.error("Unknown node flavor used in pattern: " + R->getName());
478 return MVT::Other;
479}
480
Chris Lattner32707602005-09-08 23:22:48 +0000481/// ApplyTypeConstraints - Apply all of the type constraints relevent to
482/// this node and its children in the tree. This returns true if it makes a
483/// change, false otherwise. If a type contradiction is found, throw an
484/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000485bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
486 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000487 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000488 // If it's a regclass or something else known, include the type.
489 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
490 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000491 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
492 // Int inits are always integers. :)
493 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
494
495 if (hasTypeSet()) {
496 unsigned Size = MVT::getSizeInBits(getType());
497 // Make sure that the value is representable for this type.
498 if (Size < 32) {
499 int Val = (II->getValue() << (32-Size)) >> (32-Size);
500 if (Val != II->getValue())
501 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
502 "' is out of range for type 'MVT::" +
503 getEnumName(getType()) + "'!");
504 }
505 }
506
507 return MadeChange;
508 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000509 return false;
510 }
Chris Lattner32707602005-09-08 23:22:48 +0000511
512 // special handling for set, which isn't really an SDNode.
513 if (getOperator()->getName() == "set") {
514 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000515 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
516 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000517
518 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000519 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
520 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000521 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
522 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000523 } else if (getOperator()->isSubClassOf("SDNode")) {
524 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
525
526 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
527 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000528 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000529 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000530 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000531 const DAGInstruction &Inst =
532 TP.getDAGISelEmitter().getInstruction(getOperator());
533
Chris Lattnera28aec12005-09-15 22:23:50 +0000534 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
535 // Apply the result type to the node
Nate Begemanddb39542005-12-01 00:06:14 +0000536 Record *ResultNode = Inst.getResult(0);
537 assert(ResultNode->isSubClassOf("RegisterClass") &&
538 "Operands should be register classes!");
539
540 const CodeGenRegisterClass &RC =
541 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000542
543 // Get the first ValueType in the RegClass, it's as good as any.
544 bool MadeChange = UpdateNodeType(RC.getValueTypeNum(0), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000545
546 if (getNumChildren() != Inst.getNumOperands())
547 TP.error("Instruction '" + getOperator()->getName() + " expects " +
548 utostr(Inst.getNumOperands()) + " operands, not " +
549 utostr(getNumChildren()) + " operands!");
550 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000551 Record *OperandNode = Inst.getOperand(i);
552 MVT::ValueType VT;
553 if (OperandNode->isSubClassOf("RegisterClass")) {
554 const CodeGenRegisterClass &RC =
555 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000556 VT = RC.getValueTypeNum(0);
Nate Begemanddb39542005-12-01 00:06:14 +0000557 } else if (OperandNode->isSubClassOf("Operand")) {
558 VT = getValueType(OperandNode->getValueAsDef("Type"));
559 } else {
560 assert(0 && "Unknown operand type!");
561 abort();
562 }
563
564 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000565 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000566 }
567 return MadeChange;
568 } else {
569 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
570
571 // Node transforms always take one operand, and take and return the same
572 // type.
573 if (getNumChildren() != 1)
574 TP.error("Node transform '" + getOperator()->getName() +
575 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000576 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
577 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000578 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000579 }
Chris Lattner32707602005-09-08 23:22:48 +0000580}
581
Chris Lattnere97603f2005-09-28 19:27:25 +0000582/// canPatternMatch - If it is impossible for this pattern to match on this
583/// target, fill in Reason and return false. Otherwise, return true. This is
584/// used as a santity check for .td files (to prevent people from writing stuff
585/// that can never possibly work), and to prevent the pattern permuter from
586/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000587bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000588 if (isLeaf()) return true;
589
590 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
591 if (!getChild(i)->canPatternMatch(Reason, ISE))
592 return false;
593
594 // If this node is a commutative operator, check that the LHS isn't an
595 // immediate.
596 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
597 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
598 // Scan all of the operands of the node and make sure that only the last one
599 // is a constant node.
600 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
601 if (!getChild(i)->isLeaf() &&
602 getChild(i)->getOperator()->getName() == "imm") {
603 Reason = "Immediate value must be on the RHS of commutative operators!";
604 return false;
605 }
606 }
607
608 return true;
609}
Chris Lattner32707602005-09-08 23:22:48 +0000610
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000611//===----------------------------------------------------------------------===//
612// TreePattern implementation
613//
614
Chris Lattneredbd8712005-10-21 01:19:59 +0000615TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000616 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000617 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000618 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
619 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000620}
621
Chris Lattneredbd8712005-10-21 01:19:59 +0000622TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000623 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000624 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000625 Trees.push_back(ParseTreePattern(Pat));
626}
627
Chris Lattneredbd8712005-10-21 01:19:59 +0000628TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000629 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000630 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000631 Trees.push_back(Pat);
632}
633
634
635
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000636void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000637 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000638 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000639}
640
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000641TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
642 Record *Operator = Dag->getNodeType();
643
644 if (Operator->isSubClassOf("ValueType")) {
645 // If the operator is a ValueType, then this must be "type cast" of a leaf
646 // node.
647 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000648 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000649
650 Init *Arg = Dag->getArg(0);
651 TreePatternNode *New;
652 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000653 Record *R = DI->getDef();
654 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
655 Dag->setArg(0, new DagInit(R,
656 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000657 return ParseTreePattern(Dag);
Chris Lattner72fe91c2005-09-24 00:40:24 +0000658 }
659
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000660 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000661 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
662 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000663 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
664 New = new TreePatternNode(II);
665 if (!Dag->getArgName(0).empty())
666 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000667 } else {
668 Arg->dump();
669 error("Unknown leaf value for tree pattern!");
670 return 0;
671 }
672
Chris Lattner32707602005-09-08 23:22:48 +0000673 // Apply the type cast.
674 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000675 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000676 return New;
677 }
678
679 // Verify that this is something that makes sense for an operator.
680 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000681 !Operator->isSubClassOf("Instruction") &&
682 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000683 Operator->getName() != "set")
684 error("Unrecognized node '" + Operator->getName() + "'!");
685
Chris Lattneredbd8712005-10-21 01:19:59 +0000686 // Check to see if this is something that is illegal in an input pattern.
687 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
688 Operator->isSubClassOf("SDNodeXForm")))
689 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
690
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000691 std::vector<TreePatternNode*> Children;
692
693 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
694 Init *Arg = Dag->getArg(i);
695 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
696 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000697 if (Children.back()->getName().empty())
698 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000699 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
700 Record *R = DefI->getDef();
701 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
702 // TreePatternNode if its own.
703 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
704 Dag->setArg(i, new DagInit(R,
705 std::vector<std::pair<Init*, std::string> >()));
706 --i; // Revisit this node...
707 } else {
708 TreePatternNode *Node = new TreePatternNode(DefI);
709 Node->setName(Dag->getArgName(i));
710 Children.push_back(Node);
711
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000712 // Input argument?
713 if (R->getName() == "node") {
714 if (Dag->getArgName(i).empty())
715 error("'node' argument requires a name to match with operand list");
716 Args.push_back(Dag->getArgName(i));
717 }
718 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000719 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
720 TreePatternNode *Node = new TreePatternNode(II);
721 if (!Dag->getArgName(i).empty())
722 error("Constant int argument should not have a name!");
723 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000724 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000725 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000726 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000727 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000728 error("Unknown leaf value for tree pattern!");
729 }
730 }
731
732 return new TreePatternNode(Operator, Children);
733}
734
Chris Lattner32707602005-09-08 23:22:48 +0000735/// InferAllTypes - Infer/propagate as many types throughout the expression
736/// patterns as possible. Return true if all types are infered, false
737/// otherwise. Throw an exception if a type contradiction is found.
738bool TreePattern::InferAllTypes() {
739 bool MadeChange = true;
740 while (MadeChange) {
741 MadeChange = false;
742 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000743 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000744 }
745
746 bool HasUnresolvedTypes = false;
747 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
748 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
749 return !HasUnresolvedTypes;
750}
751
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000752void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000753 OS << getRecord()->getName();
754 if (!Args.empty()) {
755 OS << "(" << Args[0];
756 for (unsigned i = 1, e = Args.size(); i != e; ++i)
757 OS << ", " << Args[i];
758 OS << ")";
759 }
760 OS << ": ";
761
762 if (Trees.size() > 1)
763 OS << "[\n";
764 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
765 OS << "\t";
766 Trees[i]->print(OS);
767 OS << "\n";
768 }
769
770 if (Trees.size() > 1)
771 OS << "]\n";
772}
773
774void TreePattern::dump() const { print(std::cerr); }
775
776
777
778//===----------------------------------------------------------------------===//
779// DAGISelEmitter implementation
780//
781
Chris Lattnerca559d02005-09-08 21:03:01 +0000782// Parse all of the SDNode definitions for the target, populating SDNodes.
783void DAGISelEmitter::ParseNodeInfo() {
784 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
785 while (!Nodes.empty()) {
786 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
787 Nodes.pop_back();
788 }
789}
790
Chris Lattner24eeeb82005-09-13 21:51:00 +0000791/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
792/// map, and emit them to the file as functions.
793void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
794 OS << "\n// Node transformations.\n";
795 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
796 while (!Xforms.empty()) {
797 Record *XFormNode = Xforms.back();
798 Record *SDNode = XFormNode->getValueAsDef("Opcode");
799 std::string Code = XFormNode->getValueAsCode("XFormFunction");
800 SDNodeXForms.insert(std::make_pair(XFormNode,
801 std::make_pair(SDNode, Code)));
802
Chris Lattner1048b7a2005-09-13 22:03:37 +0000803 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000804 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
805 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
806
Chris Lattner1048b7a2005-09-13 22:03:37 +0000807 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000808 << "(SDNode *" << C2 << ") {\n";
809 if (ClassName != "SDNode")
810 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
811 OS << Code << "\n}\n";
812 }
813
814 Xforms.pop_back();
815 }
816}
817
818
819
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000820/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
821/// file, building up the PatternFragments map. After we've collected them all,
822/// inline fragments together as necessary, so that there are no references left
823/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000824///
825/// This also emits all of the predicate functions to the output file.
826///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000827void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000828 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
829
830 // First step, parse all of the fragments and emit predicate functions.
831 OS << "\n// Predicate functions.\n";
832 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000833 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000834 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000835 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000836
837 // Validate the argument list, converting it to map, to discard duplicates.
838 std::vector<std::string> &Args = P->getArgList();
839 std::set<std::string> OperandsMap(Args.begin(), Args.end());
840
841 if (OperandsMap.count(""))
842 P->error("Cannot have unnamed 'node' values in pattern fragment!");
843
844 // Parse the operands list.
845 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
846 if (OpsList->getNodeType()->getName() != "ops")
847 P->error("Operands list should start with '(ops ... '!");
848
849 // Copy over the arguments.
850 Args.clear();
851 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
852 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
853 static_cast<DefInit*>(OpsList->getArg(j))->
854 getDef()->getName() != "node")
855 P->error("Operands list should all be 'node' values.");
856 if (OpsList->getArgName(j).empty())
857 P->error("Operands list should have names for each operand!");
858 if (!OperandsMap.count(OpsList->getArgName(j)))
859 P->error("'" + OpsList->getArgName(j) +
860 "' does not occur in pattern or was multiply specified!");
861 OperandsMap.erase(OpsList->getArgName(j));
862 Args.push_back(OpsList->getArgName(j));
863 }
864
865 if (!OperandsMap.empty())
866 P->error("Operands list does not contain an entry for operand '" +
867 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000868
869 // If there is a code init for this fragment, emit the predicate code and
870 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000871 std::string Code = Fragments[i]->getValueAsCode("Predicate");
872 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000873 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000874 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000875 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000876 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
877
Chris Lattner1048b7a2005-09-13 22:03:37 +0000878 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000879 << "(SDNode *" << C2 << ") {\n";
880 if (ClassName != "SDNode")
881 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000882 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000883 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000884 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000885
886 // If there is a node transformation corresponding to this, keep track of
887 // it.
888 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
889 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000890 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000891 }
892
893 OS << "\n\n";
894
895 // Now that we've parsed all of the tree fragments, do a closure on them so
896 // that there are not references to PatFrags left inside of them.
897 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
898 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000899 TreePattern *ThePat = I->second;
900 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000901
Chris Lattner32707602005-09-08 23:22:48 +0000902 // Infer as many types as possible. Don't worry about it if we don't infer
903 // all of them, some may depend on the inputs of the pattern.
904 try {
905 ThePat->InferAllTypes();
906 } catch (...) {
907 // If this pattern fragment is not supported by this target (no types can
908 // satisfy its constraints), just ignore it. If the bogus pattern is
909 // actually used by instructions, the type consistency error will be
910 // reported there.
911 }
912
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000913 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000914 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000915 }
916}
917
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000918/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000919/// instruction input. Return true if this is a real use.
920static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000921 std::map<std::string, TreePatternNode*> &InstInputs) {
922 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000923 if (Pat->getName().empty()) {
924 if (Pat->isLeaf()) {
925 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
926 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
927 I->error("Input " + DI->getDef()->getName() + " must be named!");
928
929 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000930 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000931 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000932
933 Record *Rec;
934 if (Pat->isLeaf()) {
935 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
936 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
937 Rec = DI->getDef();
938 } else {
939 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
940 Rec = Pat->getOperator();
941 }
942
943 TreePatternNode *&Slot = InstInputs[Pat->getName()];
944 if (!Slot) {
945 Slot = Pat;
946 } else {
947 Record *SlotRec;
948 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000949 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000950 } else {
951 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
952 SlotRec = Slot->getOperator();
953 }
954
955 // Ensure that the inputs agree if we've already seen this input.
956 if (Rec != SlotRec)
957 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000958 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000959 I->error("All $" + Pat->getName() + " inputs must agree with each other");
960 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000961 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000962}
963
964/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
965/// part of "I", the instruction), computing the set of inputs and outputs of
966/// the pattern. Report errors if we see anything naughty.
967void DAGISelEmitter::
968FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
969 std::map<std::string, TreePatternNode*> &InstInputs,
970 std::map<std::string, Record*> &InstResults) {
971 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000972 bool isUse = HandleUse(I, Pat, InstInputs);
973 if (!isUse && Pat->getTransformFn())
974 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000975 return;
976 } else if (Pat->getOperator()->getName() != "set") {
977 // If this is not a set, verify that the children nodes are not void typed,
978 // and recurse.
979 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000980 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000981 I->error("Cannot have void nodes inside of patterns!");
982 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
983 }
984
985 // If this is a non-leaf node with no children, treat it basically as if
986 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000987 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000988 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000989 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000990
Chris Lattnerf1311842005-09-14 23:05:13 +0000991 if (!isUse && Pat->getTransformFn())
992 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000993 return;
994 }
995
996 // Otherwise, this is a set, validate and collect instruction results.
997 if (Pat->getNumChildren() == 0)
998 I->error("set requires operands!");
999 else if (Pat->getNumChildren() & 1)
1000 I->error("set requires an even number of operands");
1001
Chris Lattnerf1311842005-09-14 23:05:13 +00001002 if (Pat->getTransformFn())
1003 I->error("Cannot specify a transform function on a set node!");
1004
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001005 // Check the set destinations.
1006 unsigned NumValues = Pat->getNumChildren()/2;
1007 for (unsigned i = 0; i != NumValues; ++i) {
1008 TreePatternNode *Dest = Pat->getChild(i);
1009 if (!Dest->isLeaf())
1010 I->error("set destination should be a virtual register!");
1011
1012 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1013 if (!Val)
1014 I->error("set destination should be a virtual register!");
1015
1016 if (!Val->getDef()->isSubClassOf("RegisterClass"))
1017 I->error("set destination should be a virtual register!");
1018 if (Dest->getName().empty())
1019 I->error("set destination must have a name!");
1020 if (InstResults.count(Dest->getName()))
1021 I->error("cannot set '" + Dest->getName() +"' multiple times");
1022 InstResults[Dest->getName()] = Val->getDef();
1023
1024 // Verify and collect info from the computation.
1025 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1026 InstInputs, InstResults);
1027 }
1028}
1029
1030
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001031/// ParseInstructions - Parse all of the instructions, inlining and resolving
1032/// any fragments involved. This populates the Instructions list with fully
1033/// resolved instructions.
1034void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001035 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1036
1037 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001038 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001039
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001040 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1041 LI = Instrs[i]->getValueAsListInit("Pattern");
1042
1043 // If there is no pattern, only collect minimal information about the
1044 // instruction for its operand list. We have to assume that there is one
1045 // result, as we have no detailed info.
1046 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001047 std::vector<Record*> Results;
1048 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001049
1050 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1051
1052 // Doesn't even define a result?
1053 if (InstInfo.OperandList.size() == 0)
1054 continue;
1055
1056 // Assume the first operand is the result.
Nate Begemanddb39542005-12-01 00:06:14 +00001057 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001058
1059 // The rest are inputs.
1060 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
Nate Begemanddb39542005-12-01 00:06:14 +00001061 Operands.push_back(InstInfo.OperandList[j].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001062
1063 // Create and insert the instruction.
1064 Instructions.insert(std::make_pair(Instrs[i],
Nate Begemanddb39542005-12-01 00:06:14 +00001065 DAGInstruction(0, Results, Operands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001066 continue; // no pattern.
1067 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001068
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001069 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001070 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001071 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001072 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001073
Chris Lattner95f6b762005-09-08 23:26:30 +00001074 // Infer as many types as possible. If we cannot infer all of them, we can
1075 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001076 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001077 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001078
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001079 // InstInputs - Keep track of all of the inputs of the instruction, along
1080 // with the record they are declared as.
1081 std::map<std::string, TreePatternNode*> InstInputs;
1082
1083 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001084 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001085 std::map<std::string, Record*> InstResults;
1086
Chris Lattner1f39e292005-09-14 00:09:24 +00001087 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001088 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001089 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1090 TreePatternNode *Pat = I->getTree(j);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001091 if (Pat->getExtType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001092 I->dump();
1093 I->error("Top-level forms in instruction pattern should have"
1094 " void types");
1095 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001096
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001097 // Find inputs and outputs, and verify the structure of the uses/defs.
1098 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001099 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001100
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001101 // Now that we have inputs and outputs of the pattern, inspect the operands
1102 // list for the instruction. This determines the order that operands are
1103 // added to the machine instruction the node corresponds to.
1104 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001105
1106 // Parse the operands list from the (ops) list, validating it.
1107 std::vector<std::string> &Args = I->getArgList();
1108 assert(Args.empty() && "Args list should still be empty here!");
1109 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1110
1111 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001112 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001113 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001114 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001115 I->error("'" + InstResults.begin()->first +
1116 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001117 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001118
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001119 // Check that it exists in InstResults.
1120 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001121 if (R == 0)
1122 I->error("Operand $" + OpName + " should be a set destination: all "
1123 "outputs must occur before inputs in operand list!");
1124
1125 if (CGI.OperandList[i].Rec != R)
1126 I->error("Operand $" + OpName + " class mismatch!");
1127
Chris Lattnerae6d8282005-09-15 21:51:12 +00001128 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001129 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001130
Chris Lattner39e8af92005-09-14 18:19:25 +00001131 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001132 InstResults.erase(OpName);
1133 }
1134
Chris Lattner0b592252005-09-14 21:59:34 +00001135 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1136 // the copy while we're checking the inputs.
1137 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001138
1139 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001140 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001141 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1142 const std::string &OpName = CGI.OperandList[i].Name;
1143 if (OpName.empty())
1144 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1145
Chris Lattner0b592252005-09-14 21:59:34 +00001146 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001147 I->error("Operand $" + OpName +
1148 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001149 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001150 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001151
1152 if (InVal->isLeaf() &&
1153 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1154 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1155 if (CGI.OperandList[i].Rec != InRec)
1156 I->error("Operand $" + OpName +
1157 "'s register class disagrees between the operand and pattern");
1158 }
1159 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001160
Chris Lattner2175c182005-09-14 23:01:59 +00001161 // Construct the result for the dest-pattern operand list.
1162 TreePatternNode *OpNode = InVal->clone();
1163
1164 // No predicate is useful on the result.
1165 OpNode->setPredicateFn("");
1166
1167 // Promote the xform function to be an explicit node if set.
1168 if (Record *Xform = OpNode->getTransformFn()) {
1169 OpNode->setTransformFn(0);
1170 std::vector<TreePatternNode*> Children;
1171 Children.push_back(OpNode);
1172 OpNode = new TreePatternNode(Xform, Children);
1173 }
1174
1175 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001176 }
1177
Chris Lattner0b592252005-09-14 21:59:34 +00001178 if (!InstInputsCheck.empty())
1179 I->error("Input operand $" + InstInputsCheck.begin()->first +
1180 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001181
1182 TreePatternNode *ResultPattern =
1183 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001184
1185 // Create and insert the instruction.
Nate Begemanddb39542005-12-01 00:06:14 +00001186 DAGInstruction TheInst(I, Results, Operands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001187 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1188
1189 // Use a temporary tree pattern to infer all types and make sure that the
1190 // constructed result is correct. This depends on the instruction already
1191 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001192 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001193 Temp.InferAllTypes();
1194
1195 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1196 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001197
Chris Lattner32707602005-09-08 23:22:48 +00001198 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001199 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001200
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001201 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001202 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1203 E = Instructions.end(); II != E; ++II) {
1204 TreePattern *I = II->second.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001205 if (I == 0) continue; // No pattern.
Chris Lattner1f39e292005-09-14 00:09:24 +00001206
1207 if (I->getNumTrees() != 1) {
1208 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1209 continue;
1210 }
1211 TreePatternNode *Pattern = I->getTree(0);
1212 if (Pattern->getOperator()->getName() != "set")
1213 continue; // Not a set (store or something?)
1214
1215 if (Pattern->getNumChildren() != 2)
1216 continue; // Not a set of a single value (not handled so far)
1217
1218 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001219
1220 std::string Reason;
1221 if (!SrcPattern->canPatternMatch(Reason, *this))
1222 I->error("Instruction can never match: " + Reason);
1223
Chris Lattnerae5b3502005-09-15 21:57:35 +00001224 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001225 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001226 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001227}
1228
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001229void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001230 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001231
Chris Lattnerabbb6052005-09-15 21:42:00 +00001232 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001233 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001234 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001235
Chris Lattnerabbb6052005-09-15 21:42:00 +00001236 // Inline pattern fragments into it.
1237 Pattern->InlinePatternFragments();
1238
1239 // Infer as many types as possible. If we cannot infer all of them, we can
1240 // never do anything with this pattern: report it to the user.
1241 if (!Pattern->InferAllTypes())
1242 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001243
1244 // Validate that the input pattern is correct.
1245 {
1246 std::map<std::string, TreePatternNode*> InstInputs;
1247 std::map<std::string, Record*> InstResults;
1248 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1249 InstInputs, InstResults);
1250 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001251
1252 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1253 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001254
1255 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001256 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001257
1258 // Inline pattern fragments into it.
1259 Result->InlinePatternFragments();
1260
1261 // Infer as many types as possible. If we cannot infer all of them, we can
1262 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001263 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001264 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001265
1266 if (Result->getNumTrees() != 1)
1267 Result->error("Cannot handle instructions producing instructions "
1268 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001269
1270 std::string Reason;
1271 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1272 Pattern->error("Pattern can never match: " + Reason);
1273
Chris Lattnerabbb6052005-09-15 21:42:00 +00001274 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1275 Result->getOnlyTree()));
1276 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001277}
1278
Chris Lattnere46e17b2005-09-29 19:28:10 +00001279/// CombineChildVariants - Given a bunch of permutations of each child of the
1280/// 'operator' node, put them together in all possible ways.
1281static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001282 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001283 std::vector<TreePatternNode*> &OutVariants,
1284 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001285 // Make sure that each operand has at least one variant to choose from.
1286 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1287 if (ChildVariants[i].empty())
1288 return;
1289
Chris Lattnere46e17b2005-09-29 19:28:10 +00001290 // The end result is an all-pairs construction of the resultant pattern.
1291 std::vector<unsigned> Idxs;
1292 Idxs.resize(ChildVariants.size());
1293 bool NotDone = true;
1294 while (NotDone) {
1295 // Create the variant and add it to the output list.
1296 std::vector<TreePatternNode*> NewChildren;
1297 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1298 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1299 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1300
1301 // Copy over properties.
1302 R->setName(Orig->getName());
1303 R->setPredicateFn(Orig->getPredicateFn());
1304 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001305 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001306
1307 // If this pattern cannot every match, do not include it as a variant.
1308 std::string ErrString;
1309 if (!R->canPatternMatch(ErrString, ISE)) {
1310 delete R;
1311 } else {
1312 bool AlreadyExists = false;
1313
1314 // Scan to see if this pattern has already been emitted. We can get
1315 // duplication due to things like commuting:
1316 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1317 // which are the same pattern. Ignore the dups.
1318 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1319 if (R->isIsomorphicTo(OutVariants[i])) {
1320 AlreadyExists = true;
1321 break;
1322 }
1323
1324 if (AlreadyExists)
1325 delete R;
1326 else
1327 OutVariants.push_back(R);
1328 }
1329
1330 // Increment indices to the next permutation.
1331 NotDone = false;
1332 // Look for something we can increment without causing a wrap-around.
1333 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1334 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1335 NotDone = true; // Found something to increment.
1336 break;
1337 }
1338 Idxs[IdxsIdx] = 0;
1339 }
1340 }
1341}
1342
Chris Lattneraf302912005-09-29 22:36:54 +00001343/// CombineChildVariants - A helper function for binary operators.
1344///
1345static void CombineChildVariants(TreePatternNode *Orig,
1346 const std::vector<TreePatternNode*> &LHS,
1347 const std::vector<TreePatternNode*> &RHS,
1348 std::vector<TreePatternNode*> &OutVariants,
1349 DAGISelEmitter &ISE) {
1350 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1351 ChildVariants.push_back(LHS);
1352 ChildVariants.push_back(RHS);
1353 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1354}
1355
1356
1357static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1358 std::vector<TreePatternNode *> &Children) {
1359 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1360 Record *Operator = N->getOperator();
1361
1362 // Only permit raw nodes.
1363 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1364 N->getTransformFn()) {
1365 Children.push_back(N);
1366 return;
1367 }
1368
1369 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1370 Children.push_back(N->getChild(0));
1371 else
1372 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1373
1374 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1375 Children.push_back(N->getChild(1));
1376 else
1377 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1378}
1379
Chris Lattnere46e17b2005-09-29 19:28:10 +00001380/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1381/// the (potentially recursive) pattern by using algebraic laws.
1382///
1383static void GenerateVariantsOf(TreePatternNode *N,
1384 std::vector<TreePatternNode*> &OutVariants,
1385 DAGISelEmitter &ISE) {
1386 // We cannot permute leaves.
1387 if (N->isLeaf()) {
1388 OutVariants.push_back(N);
1389 return;
1390 }
1391
1392 // Look up interesting info about the node.
1393 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1394
1395 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001396 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1397 // Reassociate by pulling together all of the linked operators
1398 std::vector<TreePatternNode*> MaximalChildren;
1399 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1400
1401 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1402 // permutations.
1403 if (MaximalChildren.size() == 3) {
1404 // Find the variants of all of our maximal children.
1405 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1406 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1407 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1408 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1409
1410 // There are only two ways we can permute the tree:
1411 // (A op B) op C and A op (B op C)
1412 // Within these forms, we can also permute A/B/C.
1413
1414 // Generate legal pair permutations of A/B/C.
1415 std::vector<TreePatternNode*> ABVariants;
1416 std::vector<TreePatternNode*> BAVariants;
1417 std::vector<TreePatternNode*> ACVariants;
1418 std::vector<TreePatternNode*> CAVariants;
1419 std::vector<TreePatternNode*> BCVariants;
1420 std::vector<TreePatternNode*> CBVariants;
1421 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1422 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1423 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1424 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1425 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1426 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1427
1428 // Combine those into the result: (x op x) op x
1429 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1430 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1431 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1432 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1433 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1434 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1435
1436 // Combine those into the result: x op (x op x)
1437 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1438 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1439 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1440 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1441 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1442 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1443 return;
1444 }
1445 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001446
1447 // Compute permutations of all children.
1448 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1449 ChildVariants.resize(N->getNumChildren());
1450 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1451 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1452
1453 // Build all permutations based on how the children were formed.
1454 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1455
1456 // If this node is commutative, consider the commuted order.
1457 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1458 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001459 // Consider the commuted order.
1460 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1461 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001462 }
1463}
1464
1465
Chris Lattnere97603f2005-09-28 19:27:25 +00001466// GenerateVariants - Generate variants. For example, commutative patterns can
1467// match multiple ways. Add them to PatternsToMatch as well.
1468void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001469
1470 DEBUG(std::cerr << "Generating instruction variants.\n");
1471
1472 // Loop over all of the patterns we've collected, checking to see if we can
1473 // generate variants of the instruction, through the exploitation of
1474 // identities. This permits the target to provide agressive matching without
1475 // the .td file having to contain tons of variants of instructions.
1476 //
1477 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1478 // intentionally do not reconsider these. Any variants of added patterns have
1479 // already been added.
1480 //
1481 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1482 std::vector<TreePatternNode*> Variants;
1483 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1484
1485 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001486 Variants.erase(Variants.begin()); // Remove the original pattern.
1487
1488 if (Variants.empty()) // No variants for this pattern.
1489 continue;
1490
1491 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1492 PatternsToMatch[i].first->dump();
1493 std::cerr << "\n");
1494
1495 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1496 TreePatternNode *Variant = Variants[v];
1497
1498 DEBUG(std::cerr << " VAR#" << v << ": ";
1499 Variant->dump();
1500 std::cerr << "\n");
1501
1502 // Scan to see if an instruction or explicit pattern already matches this.
1503 bool AlreadyExists = false;
1504 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1505 // Check to see if this variant already exists.
1506 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1507 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1508 AlreadyExists = true;
1509 break;
1510 }
1511 }
1512 // If we already have it, ignore the variant.
1513 if (AlreadyExists) continue;
1514
1515 // Otherwise, add it to the list of patterns we have.
1516 PatternsToMatch.push_back(std::make_pair(Variant,
1517 PatternsToMatch[i].second));
1518 }
1519
1520 DEBUG(std::cerr << "\n");
1521 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001522}
1523
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001524
Chris Lattner05814af2005-09-28 17:57:56 +00001525/// getPatternSize - Return the 'size' of this pattern. We want to match large
1526/// patterns before small ones. This is used to determine the size of a
1527/// pattern.
1528static unsigned getPatternSize(TreePatternNode *P) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001529 assert(isExtIntegerVT(P->getExtType()) ||
1530 isExtFloatingPointVT(P->getExtType()) &&
Chris Lattner05814af2005-09-28 17:57:56 +00001531 "Not a valid pattern node to size!");
1532 unsigned Size = 1; // The node itself.
1533
1534 // Count children in the count if they are also nodes.
1535 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1536 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001537 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Chris Lattner05814af2005-09-28 17:57:56 +00001538 Size += getPatternSize(Child);
Chris Lattner2f041d42005-10-19 04:41:05 +00001539 else if (Child->isLeaf() && dynamic_cast<IntInit*>(Child->getLeafValue())) {
1540 ++Size; // Matches a ConstantSDNode.
1541 }
Chris Lattner05814af2005-09-28 17:57:56 +00001542 }
1543
1544 return Size;
1545}
1546
1547/// getResultPatternCost - Compute the number of instructions for this pattern.
1548/// This is a temporary hack. We should really include the instruction
1549/// latencies in this calculation.
1550static unsigned getResultPatternCost(TreePatternNode *P) {
1551 if (P->isLeaf()) return 0;
1552
1553 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1554 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1555 Cost += getResultPatternCost(P->getChild(i));
1556 return Cost;
1557}
1558
1559// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1560// In particular, we want to match maximal patterns first and lowest cost within
1561// a particular complexity first.
1562struct PatternSortingPredicate {
1563 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1564 DAGISelEmitter::PatternToMatch *RHS) {
1565 unsigned LHSSize = getPatternSize(LHS->first);
1566 unsigned RHSSize = getPatternSize(RHS->first);
1567 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1568 if (LHSSize < RHSSize) return false;
1569
1570 // If the patterns have equal complexity, compare generated instruction cost
1571 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1572 }
1573};
1574
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001575/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1576/// if the match fails. At this point, we already know that the opcode for N
1577/// matches, and the SDNode for the result has the RootName specified name.
1578void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001579 const std::string &RootName,
Evan Cheng66a48bb2005-12-01 00:18:45 +00001580 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001581 unsigned PatternNo, std::ostream &OS) {
Chris Lattner0614b622005-11-02 06:49:14 +00001582 if (N->isLeaf()) {
1583 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1584 OS << " if (cast<ConstantSDNode>(" << RootName
1585 << ")->getSignExtended() != " << II->getValue() << ")\n"
1586 << " goto P" << PatternNo << "Fail;\n";
1587 return;
1588 }
1589 assert(0 && "Cannot match this as a leaf value!");
1590 abort();
1591 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001592
1593 // If this node has a name associated with it, capture it in VarMap. If
1594 // we already saw this in the pattern, emit code to verify dagness.
1595 if (!N->getName().empty()) {
1596 std::string &VarMapEntry = VarMap[N->getName()];
1597 if (VarMapEntry.empty()) {
1598 VarMapEntry = RootName;
1599 } else {
1600 // If we get here, this is a second reference to a specific name. Since
1601 // we already have checked that the first reference is valid, we don't
1602 // have to recursively match it, just check that it's the same as the
1603 // previously named thing.
1604 OS << " if (" << VarMapEntry << " != " << RootName
1605 << ") goto P" << PatternNo << "Fail;\n";
1606 return;
1607 }
1608 }
1609
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001610 // Emit code to load the child nodes and match their contents recursively.
1611 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001612 OS << " SDOperand " << RootName << i <<" = " << RootName
1613 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001614 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001615
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001616 if (!Child->isLeaf()) {
1617 // If it's not a leaf, recursively match.
1618 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001619 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001620 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001621 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001622 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001623 // If this child has a name associated with it, capture it in VarMap. If
1624 // we already saw this in the pattern, emit code to verify dagness.
1625 if (!Child->getName().empty()) {
1626 std::string &VarMapEntry = VarMap[Child->getName()];
1627 if (VarMapEntry.empty()) {
1628 VarMapEntry = RootName + utostr(i);
1629 } else {
1630 // If we get here, this is a second reference to a specific name. Since
1631 // we already have checked that the first reference is valid, we don't
1632 // have to recursively match it, just check that it's the same as the
1633 // previously named thing.
1634 OS << " if (" << VarMapEntry << " != " << RootName << i
1635 << ") goto P" << PatternNo << "Fail;\n";
1636 continue;
1637 }
1638 }
1639
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001640 // Handle leaves of various types.
Chris Lattner2f041d42005-10-19 04:41:05 +00001641 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1642 Record *LeafRec = DI->getDef();
Evan Cheng66a48bb2005-12-01 00:18:45 +00001643 if (LeafRec->isSubClassOf("RegisterClass") ||
1644 LeafRec->isSubClassOf("Register")) {
Chris Lattner2f041d42005-10-19 04:41:05 +00001645 // Handle register references. Nothing to do here.
1646 } else if (LeafRec->isSubClassOf("ValueType")) {
1647 // Make sure this is the specified value type.
1648 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1649 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1650 << "Fail;\n";
Chris Lattner1531f202005-10-26 16:59:37 +00001651 } else if (LeafRec->isSubClassOf("CondCode")) {
1652 // Make sure this is the specified cond code.
1653 OS << " if (cast<CondCodeSDNode>(" << RootName << i
Chris Lattnera7ad1982005-10-26 17:02:02 +00001654 << ")->get() != " << "ISD::" << LeafRec->getName()
Chris Lattner1531f202005-10-26 16:59:37 +00001655 << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner2f041d42005-10-19 04:41:05 +00001656 } else {
1657 Child->dump();
1658 assert(0 && "Unknown leaf type!");
1659 }
1660 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1661 OS << " if (!isa<ConstantSDNode>(" << RootName << i << ") ||\n"
1662 << " cast<ConstantSDNode>(" << RootName << i
Chris Lattner9d1a0232005-10-29 16:39:40 +00001663 << ")->getSignExtended() != " << II->getValue() << ")\n"
Chris Lattner2f041d42005-10-19 04:41:05 +00001664 << " goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001665 } else {
1666 Child->dump();
1667 assert(0 && "Unknown leaf type!");
1668 }
1669 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001670 }
1671
1672 // If there is a node predicate for this, emit the call.
1673 if (!N->getPredicateFn().empty())
1674 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001675 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001676}
1677
Nate Begeman6510b222005-12-01 04:51:06 +00001678/// getRegisterValueType - Look up and return the first ValueType of specified
1679/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001680static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1681 const std::vector<CodeGenRegisterClass> &RegisterClasses =
1682 T.getRegisterClasses();
1683
1684 for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) {
1685 const CodeGenRegisterClass &RC = RegisterClasses[i];
1686 for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
1687 if (R == RC.Elements[ei]) {
Nate Begeman6510b222005-12-01 04:51:06 +00001688 return RC.getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001689 }
1690 }
1691 }
1692
1693 return MVT::Other;
1694}
1695
1696
1697/// EmitCopyToRegsForPattern - Emit the flag operands for the DAG that will be
1698/// built in CodeGenPatternResult.
1699void DAGISelEmitter::EmitCopyToRegsForPattern(TreePatternNode *N,
1700 const std::string &RootName,
1701 std::ostream &OS, bool &InFlag) {
1702 const CodeGenTarget &T = getTargetInfo();
1703 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1704 TreePatternNode *Child = N->getChild(i);
1705 if (!Child->isLeaf()) {
1706 EmitCopyToRegsForPattern(Child, RootName + utostr(i), OS, InFlag);
1707 } else {
1708 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1709 Record *RR = DI->getDef();
1710 if (RR->isSubClassOf("Register")) {
1711 MVT::ValueType RVT = getRegisterValueType(RR, T);
1712 if (!InFlag) {
1713 OS << " SDOperand InFlag; // Null incoming flag value.\n";
1714 InFlag = true;
1715 }
1716 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
1717 << ", CurDAG->getRegister(" << getQualifiedName(RR)
1718 << ", MVT::" << getEnumName(RVT) << ")"
1719 << ", " << RootName << i << ", InFlag).getValue(1);\n";
1720
1721 }
1722 }
1723 }
1724 }
1725}
1726
Chris Lattner6bc7e512005-09-26 21:53:26 +00001727/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1728/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001729unsigned DAGISelEmitter::
1730CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1731 std::map<std::string,std::string> &VariableMap,
Evan Cheng66a48bb2005-12-01 00:18:45 +00001732 std::ostream &OS, bool InFlag, bool isRoot) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001733 // This is something selected from the pattern we matched.
1734 if (!N->getName().empty()) {
Chris Lattner5024d932005-10-16 01:41:58 +00001735 assert(!isRoot && "Root of pattern cannot be a leaf!");
Chris Lattner6bc7e512005-09-26 21:53:26 +00001736 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001737 assert(!Val.empty() &&
1738 "Variable referenced but not defined and not caught earlier!");
1739 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1740 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001741 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001742 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001743
1744 unsigned ResNo = Ctr++;
1745 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1746 switch (N->getType()) {
1747 default: assert(0 && "Unknown type for constant node!");
1748 case MVT::i1: OS << " bool Tmp"; break;
1749 case MVT::i8: OS << " unsigned char Tmp"; break;
1750 case MVT::i16: OS << " unsigned short Tmp"; break;
1751 case MVT::i32: OS << " unsigned Tmp"; break;
1752 case MVT::i64: OS << " uint64_t Tmp"; break;
1753 }
1754 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1755 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1756 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
Chris Lattnerb120a642005-11-17 07:39:45 +00001757 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1758 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
Chris Lattnerf6f94162005-09-28 16:58:06 +00001759 } else {
1760 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1761 }
1762 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1763 // value if used multiple times by this pattern result.
1764 Val = "Tmp"+utostr(ResNo);
1765 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001766 }
1767
1768 if (N->isLeaf()) {
Chris Lattner4c593092005-10-19 02:07:26 +00001769 // If this is an explicit register reference, handle it.
1770 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1771 unsigned ResNo = Ctr++;
1772 if (DI->getDef()->isSubClassOf("Register")) {
1773 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1774 << getQualifiedName(DI->getDef()) << ", MVT::"
1775 << getEnumName(N->getType())
1776 << ");\n";
1777 return ResNo;
1778 }
Chris Lattner5d5a0562005-10-19 04:30:56 +00001779 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1780 unsigned ResNo = Ctr++;
1781 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1782 << II->getValue() << ", MVT::"
1783 << getEnumName(N->getType())
1784 << ");\n";
1785 return ResNo;
Chris Lattner4c593092005-10-19 02:07:26 +00001786 }
1787
Chris Lattner72fe91c2005-09-24 00:40:24 +00001788 N->dump();
1789 assert(0 && "Unknown leaf type!");
1790 return ~0U;
1791 }
1792
1793 Record *Op = N->getOperator();
1794 if (Op->isSubClassOf("Instruction")) {
1795 // Emit all of the operands.
1796 std::vector<unsigned> Ops;
1797 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Evan Cheng66a48bb2005-12-01 00:18:45 +00001798 Ops.push_back(CodeGenPatternResult(N->getChild(i),
1799 Ctr, VariableMap, OS, InFlag));
Chris Lattner72fe91c2005-09-24 00:40:24 +00001800
1801 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1802 unsigned ResNo = Ctr++;
1803
Chris Lattner5024d932005-10-16 01:41:58 +00001804 if (!isRoot) {
1805 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1806 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1807 << getEnumName(N->getType());
1808 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1809 OS << ", Tmp" << Ops[i];
1810 OS << ");\n";
1811 } else {
1812 // If this instruction is the root, and if there is only one use of it,
1813 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1814 OS << " if (N.Val->hasOneUse()) {\n";
Chris Lattner5d28ffd2005-11-30 23:08:45 +00001815 OS << " return CurDAG->SelectNodeTo(N.Val, "
Chris Lattner5024d932005-10-16 01:41:58 +00001816 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1817 << getEnumName(N->getType());
1818 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1819 OS << ", Tmp" << Ops[i];
Evan Cheng66a48bb2005-12-01 00:18:45 +00001820 if (InFlag)
1821 OS << ", InFlag";
Chris Lattner5024d932005-10-16 01:41:58 +00001822 OS << ");\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001823 OS << " } else {\n";
1824 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
1825 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1826 << getEnumName(N->getType());
1827 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1828 OS << ", Tmp" << Ops[i];
Evan Cheng66a48bb2005-12-01 00:18:45 +00001829 if (InFlag)
1830 OS << ", InFlag";
Chris Lattner5024d932005-10-16 01:41:58 +00001831 OS << ");\n";
1832 OS << " }\n";
1833 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001834 return ResNo;
1835 } else if (Op->isSubClassOf("SDNodeXForm")) {
1836 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng66a48bb2005-12-01 00:18:45 +00001837 unsigned OpVal = CodeGenPatternResult(N->getChild(0),
1838 Ctr, VariableMap, OS, InFlag);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001839
1840 unsigned ResNo = Ctr++;
1841 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1842 << "(Tmp" << OpVal << ".Val);\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001843 if (isRoot) {
1844 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
1845 OS << " return Tmp" << ResNo << ";\n";
1846 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001847 return ResNo;
1848 } else {
1849 N->dump();
1850 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001851 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001852 }
1853}
1854
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001855/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1856/// type information from it.
1857static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001858 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001859 if (!N->isLeaf())
1860 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1861 RemoveAllTypes(N->getChild(i));
1862}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001863
Chris Lattner7e82f132005-10-15 21:34:21 +00001864/// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1865/// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1866/// 'Pat' may be missing types. If we find an unresolved type to add a check
1867/// for, this returns true otherwise false if Pat has all types.
1868static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1869 const std::string &Prefix, unsigned PatternNo,
1870 std::ostream &OS) {
1871 // Did we find one?
1872 if (!Pat->hasTypeSet()) {
1873 // Move a type over from 'other' to 'pat'.
1874 Pat->setType(Other->getType());
1875 OS << " if (" << Prefix << ".getValueType() != MVT::"
1876 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1877 return true;
1878 } else if (Pat->isLeaf()) {
1879 return false;
1880 }
1881
1882 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1883 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1884 Prefix + utostr(i), PatternNo, OS))
1885 return true;
1886 return false;
1887}
1888
Chris Lattner0614b622005-11-02 06:49:14 +00001889Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1890 Record *N = Records.getDef(Name);
1891 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1892 return N;
1893}
1894
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001895/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1896/// stream to match the pattern, and generate the code for the match if it
1897/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001898void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1899 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001900 static unsigned PatternCount = 0;
1901 unsigned PatternNo = PatternCount++;
1902 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001903 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001904 OS << "\n // Emits: ";
1905 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001906 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001907 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1908 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001909
Chris Lattner8fc35682005-09-23 23:16:51 +00001910 // Emit the matcher, capturing named arguments in VariableMap.
1911 std::map<std::string,std::string> VariableMap;
1912 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001913
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001914 // TP - Get *SOME* tree pattern, we don't care which.
1915 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001916
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001917 // At this point, we know that we structurally match the pattern, but the
1918 // types of the nodes may not match. Figure out the fewest number of type
1919 // comparisons we need to emit. For example, if there is only one integer
1920 // type supported by a target, there should be no type comparisons at all for
1921 // integer patterns!
1922 //
1923 // To figure out the fewest number of type checks needed, clone the pattern,
1924 // remove the types, then perform type inference on the pattern as a whole.
1925 // If there are unresolved types, emit an explicit check for those types,
1926 // apply the type to the tree, then rerun type inference. Iterate until all
1927 // types are resolved.
1928 //
1929 TreePatternNode *Pat = Pattern.first->clone();
1930 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001931
1932 do {
1933 // Resolve/propagate as many types as possible.
1934 try {
1935 bool MadeChange = true;
1936 while (MadeChange)
1937 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1938 } catch (...) {
1939 assert(0 && "Error: could not find consistent types for something we"
1940 " already decided was ok!");
1941 abort();
1942 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001943
Chris Lattner7e82f132005-10-15 21:34:21 +00001944 // Insert a check for an unresolved type and add it to the tree. If we find
1945 // an unresolved type to add a check for, this returns true and we iterate,
1946 // otherwise we are done.
1947 } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
Evan Cheng66a48bb2005-12-01 00:18:45 +00001948
1949 bool InFlag = false;
1950 EmitCopyToRegsForPattern(Pattern.first, "N", OS, InFlag);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001951
Chris Lattner5024d932005-10-16 01:41:58 +00001952 unsigned TmpNo = 0;
Evan Cheng66a48bb2005-12-01 00:18:45 +00001953 CodeGenPatternResult(Pattern.second,
1954 TmpNo, VariableMap, OS, InFlag, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001955 delete Pat;
1956
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001957 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001958}
1959
Chris Lattner37481472005-09-26 21:59:35 +00001960
1961namespace {
1962 /// CompareByRecordName - An ordering predicate that implements less-than by
1963 /// comparing the names records.
1964 struct CompareByRecordName {
1965 bool operator()(const Record *LHS, const Record *RHS) const {
1966 // Sort by name first.
1967 if (LHS->getName() < RHS->getName()) return true;
1968 // If both names are equal, sort by pointer.
1969 return LHS->getName() == RHS->getName() && LHS < RHS;
1970 }
1971 };
1972}
1973
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001974void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001975 std::string InstNS = Target.inst_begin()->second.Namespace;
1976 if (!InstNS.empty()) InstNS += "::";
1977
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001978 // Emit boilerplate.
1979 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001980 << "SDOperand SelectCode(SDOperand N) {\n"
1981 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001982 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1983 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001984 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001985 << " if (!N.Val->hasOneUse()) {\n"
1986 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1987 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1988 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001989 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001990 << " default: break;\n"
1991 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001992 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001993 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001994 << " case ISD::AssertZext: {\n"
1995 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1996 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1997 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001998 << " }\n"
1999 << " case ISD::TokenFactor:\n"
2000 << " if (N.getNumOperands() == 2) {\n"
2001 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2002 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2003 << " return CodeGenMap[N] =\n"
2004 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2005 << " } else {\n"
2006 << " std::vector<SDOperand> Ops;\n"
2007 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2008 << " Ops.push_back(Select(N.getOperand(i)));\n"
2009 << " return CodeGenMap[N] = \n"
2010 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2011 << " }\n"
2012 << " case ISD::CopyFromReg: {\n"
2013 << " SDOperand Chain = Select(N.getOperand(0));\n"
2014 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2015 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
2016 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
2017 << " N.Val->getValueType(0));\n"
2018 << " return New.getValue(N.ResNo);\n"
2019 << " }\n"
2020 << " case ISD::CopyToReg: {\n"
2021 << " SDOperand Chain = Select(N.getOperand(0));\n"
2022 << " SDOperand Reg = N.getOperand(1);\n"
2023 << " SDOperand Val = Select(N.getOperand(2));\n"
2024 << " return CodeGenMap[N] = \n"
2025 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
2026 << " Chain, Reg, Val);\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002027 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002028
Chris Lattner81303322005-09-23 19:36:15 +00002029 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00002030 std::map<Record*, std::vector<PatternToMatch*>,
2031 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00002032 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
Chris Lattner0614b622005-11-02 06:49:14 +00002033 if (!PatternsToMatch[i].first->isLeaf()) {
2034 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
2035 .push_back(&PatternsToMatch[i]);
2036 } else {
2037 if (IntInit *II =
2038 dynamic_cast<IntInit*>(PatternsToMatch[i].first->getLeafValue())) {
2039 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2040 } else {
Evan Cheng76021f02005-11-29 18:44:58 +00002041 std::cerr << "Unrecognized opcode '";
2042 PatternsToMatch[i].first->dump();
2043 std::cerr << "' on tree pattern '";
2044 std::cerr << PatternsToMatch[i].second->getOperator()->getName();
2045 std::cerr << "'!\n";
2046 exit(1);
Chris Lattner0614b622005-11-02 06:49:14 +00002047 }
2048 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002049
Chris Lattner3f7e9142005-09-23 20:52:47 +00002050 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00002051 for (std::map<Record*, std::vector<PatternToMatch*>,
2052 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2053 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002054 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2055 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2056
2057 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002058
2059 // We want to emit all of the matching code now. However, we want to emit
2060 // the matches in order of minimal cost. Sort the patterns so the least
2061 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002062 std::stable_sort(Patterns.begin(), Patterns.end(),
2063 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00002064
Chris Lattner3f7e9142005-09-23 20:52:47 +00002065 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2066 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002067 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00002068 }
2069
2070
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002071 OS << " } // end of big switch.\n\n"
2072 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002073 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002074 << " std::cerr << '\\n';\n"
2075 << " abort();\n"
2076 << "}\n";
2077}
2078
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002079void DAGISelEmitter::run(std::ostream &OS) {
2080 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2081 " target", OS);
2082
Chris Lattner1f39e292005-09-14 00:09:24 +00002083 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2084 << "// *** instruction selector class. These functions are really "
2085 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002086
Chris Lattner296dfe32005-09-24 00:50:51 +00002087 OS << "// Instance var to keep track of multiply used nodes that have \n"
2088 << "// already been selected.\n"
2089 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2090
Chris Lattnerca559d02005-09-08 21:03:01 +00002091 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002092 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002093 ParsePatternFragments(OS);
2094 ParseInstructions();
2095 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002096
Chris Lattnere97603f2005-09-28 19:27:25 +00002097 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002098 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002099 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002100
Chris Lattnere46e17b2005-09-29 19:28:10 +00002101
2102 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2103 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2104 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
2105 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
2106 std::cerr << "\n";
2107 });
2108
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002109 // At this point, we have full information about the 'Patterns' we need to
2110 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002111 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002112 EmitInstructionSelector(OS);
2113
2114 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2115 E = PatternFragments.end(); I != E; ++I)
2116 delete I->second;
2117 PatternFragments.clear();
2118
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002119 Instructions.clear();
2120}