blob: d0dc799ac000cbbe12341fdd4bf432e642316da5 [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;
231 ListInit *LI = R->getValueAsListInit("Properties");
232 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
233 DefInit *DI = dynamic_cast<DefInit*>(LI->getElement(i));
234 assert(DI && "Properties list must be list of defs!");
235 if (DI->getDef()->getName() == "SDNPCommutative") {
236 Properties |= 1 << SDNPCommutative;
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000237 } else if (DI->getDef()->getName() == "SDNPAssociative") {
238 Properties |= 1 << SDNPAssociative;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000239 } else {
240 std::cerr << "Unknown SD Node property '" << DI->getDef()->getName()
241 << "' on node '" << R->getName() << "'!\n";
242 exit(1);
243 }
244 }
245
246
Chris Lattner33c92e92005-09-08 21:27:15 +0000247 // Parse the type constraints.
248 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
249 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
250 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
251 "Constraints list should contain constraint definitions!");
252 Record *Constraint =
253 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
254 TypeConstraints.push_back(Constraint);
255 }
Chris Lattnerca559d02005-09-08 21:03:01 +0000256}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000257
258//===----------------------------------------------------------------------===//
259// TreePatternNode implementation
260//
261
262TreePatternNode::~TreePatternNode() {
263#if 0 // FIXME: implement refcounted tree nodes!
264 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
265 delete getChild(i);
266#endif
267}
268
Chris Lattner32707602005-09-08 23:22:48 +0000269/// UpdateNodeType - Set the node type of N to VT if VT contains
270/// information. If N already contains a conflicting type, then throw an
271/// exception. This returns true if any information was updated.
272///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000273bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
274 if (VT == MVT::isUnknown || getExtType() == VT) return false;
275 if (getExtType() == MVT::isUnknown) {
Chris Lattner32707602005-09-08 23:22:48 +0000276 setType(VT);
277 return true;
278 }
279
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000280 // If we are told this is to be an int or FP type, and it already is, ignore
281 // the advice.
282 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
283 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
284 return false;
285
286 // If we know this is an int or fp type, and we are told it is a specific one,
287 // take the advice.
288 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
289 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
290 setType(VT);
291 return true;
292 }
293
Chris Lattner32707602005-09-08 23:22:48 +0000294 TP.error("Type inference contradiction found in node " +
295 getOperator()->getName() + "!");
296 return true; // unreachable
297}
298
299
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000300void TreePatternNode::print(std::ostream &OS) const {
301 if (isLeaf()) {
302 OS << *getLeafValue();
303 } else {
304 OS << "(" << getOperator()->getName();
305 }
306
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000307 switch (getExtType()) {
308 case MVT::Other: OS << ":Other"; break;
309 case MVT::isInt: OS << ":isInt"; break;
310 case MVT::isFP : OS << ":isFP"; break;
311 case MVT::isUnknown: ; /*OS << ":?";*/ break;
312 default: OS << ":" << getType(); break;
313 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000314
315 if (!isLeaf()) {
316 if (getNumChildren() != 0) {
317 OS << " ";
318 getChild(0)->print(OS);
319 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
320 OS << ", ";
321 getChild(i)->print(OS);
322 }
323 }
324 OS << ")";
325 }
326
327 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000328 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000329 if (TransformFn)
330 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000331 if (!getName().empty())
332 OS << ":$" << getName();
333
334}
335void TreePatternNode::dump() const {
336 print(std::cerr);
337}
338
Chris Lattnere46e17b2005-09-29 19:28:10 +0000339/// isIsomorphicTo - Return true if this node is recursively isomorphic to
340/// the specified node. For this comparison, all of the state of the node
341/// is considered, except for the assigned name. Nodes with differing names
342/// that are otherwise identical are considered isomorphic.
343bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
344 if (N == this) return true;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000345 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000346 getPredicateFn() != N->getPredicateFn() ||
347 getTransformFn() != N->getTransformFn())
348 return false;
349
350 if (isLeaf()) {
351 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
352 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
353 return DI->getDef() == NDI->getDef();
354 return getLeafValue() == N->getLeafValue();
355 }
356
357 if (N->getOperator() != getOperator() ||
358 N->getNumChildren() != getNumChildren()) return false;
359 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
360 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
361 return false;
362 return true;
363}
364
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000365/// clone - Make a copy of this tree and all of its children.
366///
367TreePatternNode *TreePatternNode::clone() const {
368 TreePatternNode *New;
369 if (isLeaf()) {
370 New = new TreePatternNode(getLeafValue());
371 } else {
372 std::vector<TreePatternNode*> CChildren;
373 CChildren.reserve(Children.size());
374 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
375 CChildren.push_back(getChild(i)->clone());
376 New = new TreePatternNode(getOperator(), CChildren);
377 }
378 New->setName(getName());
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000379 New->setType(getExtType());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000380 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000381 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000382 return New;
383}
384
Chris Lattner32707602005-09-08 23:22:48 +0000385/// SubstituteFormalArguments - Replace the formal arguments in this tree
386/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000387void TreePatternNode::
388SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
389 if (isLeaf()) return;
390
391 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
392 TreePatternNode *Child = getChild(i);
393 if (Child->isLeaf()) {
394 Init *Val = Child->getLeafValue();
395 if (dynamic_cast<DefInit*>(Val) &&
396 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
397 // We found a use of a formal argument, replace it with its value.
398 Child = ArgMap[Child->getName()];
399 assert(Child && "Couldn't find formal argument!");
400 setChild(i, Child);
401 }
402 } else {
403 getChild(i)->SubstituteFormalArguments(ArgMap);
404 }
405 }
406}
407
408
409/// InlinePatternFragments - If this pattern refers to any pattern
410/// fragments, inline them into place, giving us a pattern without any
411/// PatFrag references.
412TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
413 if (isLeaf()) return this; // nothing to do.
414 Record *Op = getOperator();
415
416 if (!Op->isSubClassOf("PatFrag")) {
417 // Just recursively inline children nodes.
418 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
419 setChild(i, getChild(i)->InlinePatternFragments(TP));
420 return this;
421 }
422
423 // Otherwise, we found a reference to a fragment. First, look up its
424 // TreePattern record.
425 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
426
427 // Verify that we are passing the right number of operands.
428 if (Frag->getNumArgs() != Children.size())
429 TP.error("'" + Op->getName() + "' fragment requires " +
430 utostr(Frag->getNumArgs()) + " operands!");
431
Chris Lattner37937092005-09-09 01:15:01 +0000432 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000433
434 // Resolve formal arguments to their actual value.
435 if (Frag->getNumArgs()) {
436 // Compute the map of formal to actual arguments.
437 std::map<std::string, TreePatternNode*> ArgMap;
438 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
439 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
440
441 FragTree->SubstituteFormalArguments(ArgMap);
442 }
443
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000444 FragTree->setName(getName());
445
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000446 // Get a new copy of this fragment to stitch into here.
447 //delete this; // FIXME: implement refcounting!
448 return FragTree;
449}
450
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000451/// getIntrinsicType - Check to see if the specified record has an intrinsic
452/// type which should be applied to it. This infer the type of register
453/// references from the register file information, for example.
454///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000455static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
456 TreePattern &TP) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000457 // Check to see if this is a register or a register class...
458 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000459 if (NotRegisters) return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000460 return getValueType(R->getValueAsDef("RegType"));
461 } 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")) {
465 assert(0 && "Explicit registers not handled here yet!\n");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000466 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000467 } else if (R->isSubClassOf("ValueType")) {
468 // Using a VTSDNode.
469 return MVT::Other;
470 } else if (R->getName() == "node") {
471 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000472 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000473 }
474
475 TP.error("Unknown node flavor used in pattern: " + R->getName());
476 return MVT::Other;
477}
478
Chris Lattner32707602005-09-08 23:22:48 +0000479/// ApplyTypeConstraints - Apply all of the type constraints relevent to
480/// this node and its children in the tree. This returns true if it makes a
481/// change, false otherwise. If a type contradiction is found, throw an
482/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000483bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
484 if (isLeaf()) {
485 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
486 // If it's a regclass or something else known, include the type.
487 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
488 TP);
489 return false;
490 }
Chris Lattner32707602005-09-08 23:22:48 +0000491
492 // special handling for set, which isn't really an SDNode.
493 if (getOperator()->getName() == "set") {
494 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000495 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
496 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000497
498 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000499 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
500 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000501 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
502 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000503 } else if (getOperator()->isSubClassOf("SDNode")) {
504 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
505
506 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
507 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000508 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000509 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000510 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000511 const DAGInstruction &Inst =
512 TP.getDAGISelEmitter().getInstruction(getOperator());
513
Chris Lattnera28aec12005-09-15 22:23:50 +0000514 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
515 // Apply the result type to the node
516 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
517
518 if (getNumChildren() != Inst.getNumOperands())
519 TP.error("Instruction '" + getOperator()->getName() + " expects " +
520 utostr(Inst.getNumOperands()) + " operands, not " +
521 utostr(getNumChildren()) + " operands!");
522 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
523 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000524 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000525 }
526 return MadeChange;
527 } else {
528 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
529
530 // Node transforms always take one operand, and take and return the same
531 // type.
532 if (getNumChildren() != 1)
533 TP.error("Node transform '" + getOperator()->getName() +
534 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000535 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
536 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000537 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000538 }
Chris Lattner32707602005-09-08 23:22:48 +0000539}
540
Chris Lattnere97603f2005-09-28 19:27:25 +0000541/// canPatternMatch - If it is impossible for this pattern to match on this
542/// target, fill in Reason and return false. Otherwise, return true. This is
543/// used as a santity check for .td files (to prevent people from writing stuff
544/// that can never possibly work), and to prevent the pattern permuter from
545/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000546bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000547 if (isLeaf()) return true;
548
549 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
550 if (!getChild(i)->canPatternMatch(Reason, ISE))
551 return false;
552
553 // If this node is a commutative operator, check that the LHS isn't an
554 // immediate.
555 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
556 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
557 // Scan all of the operands of the node and make sure that only the last one
558 // is a constant node.
559 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
560 if (!getChild(i)->isLeaf() &&
561 getChild(i)->getOperator()->getName() == "imm") {
562 Reason = "Immediate value must be on the RHS of commutative operators!";
563 return false;
564 }
565 }
566
567 return true;
568}
Chris Lattner32707602005-09-08 23:22:48 +0000569
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000570//===----------------------------------------------------------------------===//
571// TreePattern implementation
572//
573
Chris Lattnera28aec12005-09-15 22:23:50 +0000574TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000575 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000576 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
577 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000578}
579
Chris Lattnera28aec12005-09-15 22:23:50 +0000580TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
581 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
582 Trees.push_back(ParseTreePattern(Pat));
583}
584
585TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
586 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
587 Trees.push_back(Pat);
588}
589
590
591
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000592void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000593 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000594 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000595}
596
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000597TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
598 Record *Operator = Dag->getNodeType();
599
600 if (Operator->isSubClassOf("ValueType")) {
601 // If the operator is a ValueType, then this must be "type cast" of a leaf
602 // node.
603 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000604 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000605
606 Init *Arg = Dag->getArg(0);
607 TreePatternNode *New;
608 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000609 Record *R = DI->getDef();
610 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
611 Dag->setArg(0, new DagInit(R,
612 std::vector<std::pair<Init*, std::string> >()));
613 TreePatternNode *TPN = ParseTreePattern(Dag);
614 TPN->setName(Dag->getArgName(0));
615 return TPN;
616 }
617
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000618 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000619 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
620 New = ParseTreePattern(DI);
621 } else {
622 Arg->dump();
623 error("Unknown leaf value for tree pattern!");
624 return 0;
625 }
626
Chris Lattner32707602005-09-08 23:22:48 +0000627 // Apply the type cast.
628 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000629 return New;
630 }
631
632 // Verify that this is something that makes sense for an operator.
633 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000634 !Operator->isSubClassOf("Instruction") &&
635 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000636 Operator->getName() != "set")
637 error("Unrecognized node '" + Operator->getName() + "'!");
638
639 std::vector<TreePatternNode*> Children;
640
641 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
642 Init *Arg = Dag->getArg(i);
643 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
644 Children.push_back(ParseTreePattern(DI));
645 Children.back()->setName(Dag->getArgName(i));
646 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
647 Record *R = DefI->getDef();
648 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
649 // TreePatternNode if its own.
650 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
651 Dag->setArg(i, new DagInit(R,
652 std::vector<std::pair<Init*, std::string> >()));
653 --i; // Revisit this node...
654 } else {
655 TreePatternNode *Node = new TreePatternNode(DefI);
656 Node->setName(Dag->getArgName(i));
657 Children.push_back(Node);
658
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000659 // Input argument?
660 if (R->getName() == "node") {
661 if (Dag->getArgName(i).empty())
662 error("'node' argument requires a name to match with operand list");
663 Args.push_back(Dag->getArgName(i));
664 }
665 }
666 } else {
667 Arg->dump();
668 error("Unknown leaf value for tree pattern!");
669 }
670 }
671
672 return new TreePatternNode(Operator, Children);
673}
674
Chris Lattner32707602005-09-08 23:22:48 +0000675/// InferAllTypes - Infer/propagate as many types throughout the expression
676/// patterns as possible. Return true if all types are infered, false
677/// otherwise. Throw an exception if a type contradiction is found.
678bool TreePattern::InferAllTypes() {
679 bool MadeChange = true;
680 while (MadeChange) {
681 MadeChange = false;
682 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000683 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000684 }
685
686 bool HasUnresolvedTypes = false;
687 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
688 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
689 return !HasUnresolvedTypes;
690}
691
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000692void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000693 OS << getRecord()->getName();
694 if (!Args.empty()) {
695 OS << "(" << Args[0];
696 for (unsigned i = 1, e = Args.size(); i != e; ++i)
697 OS << ", " << Args[i];
698 OS << ")";
699 }
700 OS << ": ";
701
702 if (Trees.size() > 1)
703 OS << "[\n";
704 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
705 OS << "\t";
706 Trees[i]->print(OS);
707 OS << "\n";
708 }
709
710 if (Trees.size() > 1)
711 OS << "]\n";
712}
713
714void TreePattern::dump() const { print(std::cerr); }
715
716
717
718//===----------------------------------------------------------------------===//
719// DAGISelEmitter implementation
720//
721
Chris Lattnerca559d02005-09-08 21:03:01 +0000722// Parse all of the SDNode definitions for the target, populating SDNodes.
723void DAGISelEmitter::ParseNodeInfo() {
724 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
725 while (!Nodes.empty()) {
726 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
727 Nodes.pop_back();
728 }
729}
730
Chris Lattner24eeeb82005-09-13 21:51:00 +0000731/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
732/// map, and emit them to the file as functions.
733void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
734 OS << "\n// Node transformations.\n";
735 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
736 while (!Xforms.empty()) {
737 Record *XFormNode = Xforms.back();
738 Record *SDNode = XFormNode->getValueAsDef("Opcode");
739 std::string Code = XFormNode->getValueAsCode("XFormFunction");
740 SDNodeXForms.insert(std::make_pair(XFormNode,
741 std::make_pair(SDNode, Code)));
742
Chris Lattner1048b7a2005-09-13 22:03:37 +0000743 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000744 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
745 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
746
Chris Lattner1048b7a2005-09-13 22:03:37 +0000747 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000748 << "(SDNode *" << C2 << ") {\n";
749 if (ClassName != "SDNode")
750 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
751 OS << Code << "\n}\n";
752 }
753
754 Xforms.pop_back();
755 }
756}
757
758
759
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000760/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
761/// file, building up the PatternFragments map. After we've collected them all,
762/// inline fragments together as necessary, so that there are no references left
763/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000764///
765/// This also emits all of the predicate functions to the output file.
766///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000767void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000768 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
769
770 // First step, parse all of the fragments and emit predicate functions.
771 OS << "\n// Predicate functions.\n";
772 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000773 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
774 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000775 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000776
777 // Validate the argument list, converting it to map, to discard duplicates.
778 std::vector<std::string> &Args = P->getArgList();
779 std::set<std::string> OperandsMap(Args.begin(), Args.end());
780
781 if (OperandsMap.count(""))
782 P->error("Cannot have unnamed 'node' values in pattern fragment!");
783
784 // Parse the operands list.
785 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
786 if (OpsList->getNodeType()->getName() != "ops")
787 P->error("Operands list should start with '(ops ... '!");
788
789 // Copy over the arguments.
790 Args.clear();
791 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
792 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
793 static_cast<DefInit*>(OpsList->getArg(j))->
794 getDef()->getName() != "node")
795 P->error("Operands list should all be 'node' values.");
796 if (OpsList->getArgName(j).empty())
797 P->error("Operands list should have names for each operand!");
798 if (!OperandsMap.count(OpsList->getArgName(j)))
799 P->error("'" + OpsList->getArgName(j) +
800 "' does not occur in pattern or was multiply specified!");
801 OperandsMap.erase(OpsList->getArgName(j));
802 Args.push_back(OpsList->getArgName(j));
803 }
804
805 if (!OperandsMap.empty())
806 P->error("Operands list does not contain an entry for operand '" +
807 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000808
809 // If there is a code init for this fragment, emit the predicate code and
810 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000811 std::string Code = Fragments[i]->getValueAsCode("Predicate");
812 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000813 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000814 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000815 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000816 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
817
Chris Lattner1048b7a2005-09-13 22:03:37 +0000818 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000819 << "(SDNode *" << C2 << ") {\n";
820 if (ClassName != "SDNode")
821 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000822 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000823 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000824 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000825
826 // If there is a node transformation corresponding to this, keep track of
827 // it.
828 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
829 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000830 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000831 }
832
833 OS << "\n\n";
834
835 // Now that we've parsed all of the tree fragments, do a closure on them so
836 // that there are not references to PatFrags left inside of them.
837 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
838 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000839 TreePattern *ThePat = I->second;
840 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000841
Chris Lattner32707602005-09-08 23:22:48 +0000842 // Infer as many types as possible. Don't worry about it if we don't infer
843 // all of them, some may depend on the inputs of the pattern.
844 try {
845 ThePat->InferAllTypes();
846 } catch (...) {
847 // If this pattern fragment is not supported by this target (no types can
848 // satisfy its constraints), just ignore it. If the bogus pattern is
849 // actually used by instructions, the type consistency error will be
850 // reported there.
851 }
852
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000853 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000854 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000855 }
856}
857
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000858/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000859/// instruction input. Return true if this is a real use.
860static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000861 std::map<std::string, TreePatternNode*> &InstInputs) {
862 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000863 if (Pat->getName().empty()) {
864 if (Pat->isLeaf()) {
865 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
866 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
867 I->error("Input " + DI->getDef()->getName() + " must be named!");
868
869 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000870 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000871 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000872
873 Record *Rec;
874 if (Pat->isLeaf()) {
875 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
876 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
877 Rec = DI->getDef();
878 } else {
879 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
880 Rec = Pat->getOperator();
881 }
882
883 TreePatternNode *&Slot = InstInputs[Pat->getName()];
884 if (!Slot) {
885 Slot = Pat;
886 } else {
887 Record *SlotRec;
888 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000889 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000890 } else {
891 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
892 SlotRec = Slot->getOperator();
893 }
894
895 // Ensure that the inputs agree if we've already seen this input.
896 if (Rec != SlotRec)
897 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000898 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000899 I->error("All $" + Pat->getName() + " inputs must agree with each other");
900 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000901 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000902}
903
904/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
905/// part of "I", the instruction), computing the set of inputs and outputs of
906/// the pattern. Report errors if we see anything naughty.
907void DAGISelEmitter::
908FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
909 std::map<std::string, TreePatternNode*> &InstInputs,
910 std::map<std::string, Record*> &InstResults) {
911 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000912 bool isUse = HandleUse(I, Pat, InstInputs);
913 if (!isUse && Pat->getTransformFn())
914 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000915 return;
916 } else if (Pat->getOperator()->getName() != "set") {
917 // If this is not a set, verify that the children nodes are not void typed,
918 // and recurse.
919 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000920 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000921 I->error("Cannot have void nodes inside of patterns!");
922 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
923 }
924
925 // If this is a non-leaf node with no children, treat it basically as if
926 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000927 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000928 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000929 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000930
Chris Lattnerf1311842005-09-14 23:05:13 +0000931 if (!isUse && Pat->getTransformFn())
932 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000933 return;
934 }
935
936 // Otherwise, this is a set, validate and collect instruction results.
937 if (Pat->getNumChildren() == 0)
938 I->error("set requires operands!");
939 else if (Pat->getNumChildren() & 1)
940 I->error("set requires an even number of operands");
941
Chris Lattnerf1311842005-09-14 23:05:13 +0000942 if (Pat->getTransformFn())
943 I->error("Cannot specify a transform function on a set node!");
944
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000945 // Check the set destinations.
946 unsigned NumValues = Pat->getNumChildren()/2;
947 for (unsigned i = 0; i != NumValues; ++i) {
948 TreePatternNode *Dest = Pat->getChild(i);
949 if (!Dest->isLeaf())
950 I->error("set destination should be a virtual register!");
951
952 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
953 if (!Val)
954 I->error("set destination should be a virtual register!");
955
956 if (!Val->getDef()->isSubClassOf("RegisterClass"))
957 I->error("set destination should be a virtual register!");
958 if (Dest->getName().empty())
959 I->error("set destination must have a name!");
960 if (InstResults.count(Dest->getName()))
961 I->error("cannot set '" + Dest->getName() +"' multiple times");
962 InstResults[Dest->getName()] = Val->getDef();
963
964 // Verify and collect info from the computation.
965 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
966 InstInputs, InstResults);
967 }
968}
969
970
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000971/// ParseInstructions - Parse all of the instructions, inlining and resolving
972/// any fragments involved. This populates the Instructions list with fully
973/// resolved instructions.
974void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000975 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
976
977 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +0000978 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000979
Chris Lattner0c0cfa72005-10-19 01:27:22 +0000980 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
981 LI = Instrs[i]->getValueAsListInit("Pattern");
982
983 // If there is no pattern, only collect minimal information about the
984 // instruction for its operand list. We have to assume that there is one
985 // result, as we have no detailed info.
986 if (!LI || LI->getSize() == 0) {
987 std::vector<MVT::ValueType> ResultTypes;
988 std::vector<MVT::ValueType> OperandTypes;
989
990 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
991
992 // Doesn't even define a result?
993 if (InstInfo.OperandList.size() == 0)
994 continue;
995
996 // Assume the first operand is the result.
997 ResultTypes.push_back(InstInfo.OperandList[0].Ty);
998
999 // The rest are inputs.
1000 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1001 OperandTypes.push_back(InstInfo.OperandList[j].Ty);
1002
1003 // Create and insert the instruction.
1004 Instructions.insert(std::make_pair(Instrs[i],
1005 DAGInstruction(0, ResultTypes, OperandTypes)));
1006 continue; // no pattern.
1007 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001008
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001009 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +00001010 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001011 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001012 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001013
Chris Lattner95f6b762005-09-08 23:26:30 +00001014 // Infer as many types as possible. If we cannot infer all of them, we can
1015 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001016 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001017 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001018
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001019 // InstInputs - Keep track of all of the inputs of the instruction, along
1020 // with the record they are declared as.
1021 std::map<std::string, TreePatternNode*> InstInputs;
1022
1023 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001024 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001025 std::map<std::string, Record*> InstResults;
1026
Chris Lattner1f39e292005-09-14 00:09:24 +00001027 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001028 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001029 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1030 TreePatternNode *Pat = I->getTree(j);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001031 if (Pat->getExtType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001032 I->dump();
1033 I->error("Top-level forms in instruction pattern should have"
1034 " void types");
1035 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001036
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001037 // Find inputs and outputs, and verify the structure of the uses/defs.
1038 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001039 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001040
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001041 // Now that we have inputs and outputs of the pattern, inspect the operands
1042 // list for the instruction. This determines the order that operands are
1043 // added to the machine instruction the node corresponds to.
1044 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001045
1046 // Parse the operands list from the (ops) list, validating it.
1047 std::vector<std::string> &Args = I->getArgList();
1048 assert(Args.empty() && "Args list should still be empty here!");
1049 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1050
1051 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +00001052 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +00001053 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001054 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001055 I->error("'" + InstResults.begin()->first +
1056 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001057 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001058
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001059 // Check that it exists in InstResults.
1060 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001061 if (R == 0)
1062 I->error("Operand $" + OpName + " should be a set destination: all "
1063 "outputs must occur before inputs in operand list!");
1064
1065 if (CGI.OperandList[i].Rec != R)
1066 I->error("Operand $" + OpName + " class mismatch!");
1067
Chris Lattnerae6d8282005-09-15 21:51:12 +00001068 // Remember the return type.
1069 ResultTypes.push_back(CGI.OperandList[i].Ty);
1070
Chris Lattner39e8af92005-09-14 18:19:25 +00001071 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001072 InstResults.erase(OpName);
1073 }
1074
Chris Lattner0b592252005-09-14 21:59:34 +00001075 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1076 // the copy while we're checking the inputs.
1077 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001078
1079 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +00001080 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001081 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1082 const std::string &OpName = CGI.OperandList[i].Name;
1083 if (OpName.empty())
1084 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1085
Chris Lattner0b592252005-09-14 21:59:34 +00001086 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001087 I->error("Operand $" + OpName +
1088 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001089 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001090 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001091 if (CGI.OperandList[i].Ty != InVal->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001092 I->error("Operand $" + OpName +
1093 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +00001094 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +00001095
Chris Lattner2175c182005-09-14 23:01:59 +00001096 // Construct the result for the dest-pattern operand list.
1097 TreePatternNode *OpNode = InVal->clone();
1098
1099 // No predicate is useful on the result.
1100 OpNode->setPredicateFn("");
1101
1102 // Promote the xform function to be an explicit node if set.
1103 if (Record *Xform = OpNode->getTransformFn()) {
1104 OpNode->setTransformFn(0);
1105 std::vector<TreePatternNode*> Children;
1106 Children.push_back(OpNode);
1107 OpNode = new TreePatternNode(Xform, Children);
1108 }
1109
1110 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001111 }
1112
Chris Lattner0b592252005-09-14 21:59:34 +00001113 if (!InstInputsCheck.empty())
1114 I->error("Input operand $" + InstInputsCheck.begin()->first +
1115 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001116
1117 TreePatternNode *ResultPattern =
1118 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001119
1120 // Create and insert the instruction.
1121 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
1122 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1123
1124 // Use a temporary tree pattern to infer all types and make sure that the
1125 // constructed result is correct. This depends on the instruction already
1126 // being inserted into the Instructions map.
1127 TreePattern Temp(I->getRecord(), ResultPattern, *this);
1128 Temp.InferAllTypes();
1129
1130 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1131 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001132
Chris Lattner32707602005-09-08 23:22:48 +00001133 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001134 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001135
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001136 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001137 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1138 E = Instructions.end(); II != E; ++II) {
1139 TreePattern *I = II->second.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001140 if (I == 0) continue; // No pattern.
Chris Lattner1f39e292005-09-14 00:09:24 +00001141
1142 if (I->getNumTrees() != 1) {
1143 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1144 continue;
1145 }
1146 TreePatternNode *Pattern = I->getTree(0);
1147 if (Pattern->getOperator()->getName() != "set")
1148 continue; // Not a set (store or something?)
1149
1150 if (Pattern->getNumChildren() != 2)
1151 continue; // Not a set of a single value (not handled so far)
1152
1153 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnere97603f2005-09-28 19:27:25 +00001154
1155 std::string Reason;
1156 if (!SrcPattern->canPatternMatch(Reason, *this))
1157 I->error("Instruction can never match: " + Reason);
1158
Chris Lattnerae5b3502005-09-15 21:57:35 +00001159 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001160 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001161 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001162}
1163
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001164void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001165 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001166
Chris Lattnerabbb6052005-09-15 21:42:00 +00001167 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001168 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1169 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001170
Chris Lattnerabbb6052005-09-15 21:42:00 +00001171 // Inline pattern fragments into it.
1172 Pattern->InlinePatternFragments();
1173
1174 // Infer as many types as possible. If we cannot infer all of them, we can
1175 // never do anything with this pattern: report it to the user.
1176 if (!Pattern->InferAllTypes())
1177 Pattern->error("Could not infer all types in pattern!");
1178
1179 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1180 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001181
1182 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +00001183 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001184
1185 // Inline pattern fragments into it.
1186 Result->InlinePatternFragments();
1187
1188 // Infer as many types as possible. If we cannot infer all of them, we can
1189 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001190 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001191 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001192
1193 if (Result->getNumTrees() != 1)
1194 Result->error("Cannot handle instructions producing instructions "
1195 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001196
1197 std::string Reason;
1198 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1199 Pattern->error("Pattern can never match: " + Reason);
1200
Chris Lattnerabbb6052005-09-15 21:42:00 +00001201 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1202 Result->getOnlyTree()));
1203 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001204}
1205
Chris Lattnere46e17b2005-09-29 19:28:10 +00001206/// CombineChildVariants - Given a bunch of permutations of each child of the
1207/// 'operator' node, put them together in all possible ways.
1208static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001209 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001210 std::vector<TreePatternNode*> &OutVariants,
1211 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001212 // Make sure that each operand has at least one variant to choose from.
1213 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1214 if (ChildVariants[i].empty())
1215 return;
1216
Chris Lattnere46e17b2005-09-29 19:28:10 +00001217 // The end result is an all-pairs construction of the resultant pattern.
1218 std::vector<unsigned> Idxs;
1219 Idxs.resize(ChildVariants.size());
1220 bool NotDone = true;
1221 while (NotDone) {
1222 // Create the variant and add it to the output list.
1223 std::vector<TreePatternNode*> NewChildren;
1224 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1225 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1226 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1227
1228 // Copy over properties.
1229 R->setName(Orig->getName());
1230 R->setPredicateFn(Orig->getPredicateFn());
1231 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001232 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001233
1234 // If this pattern cannot every match, do not include it as a variant.
1235 std::string ErrString;
1236 if (!R->canPatternMatch(ErrString, ISE)) {
1237 delete R;
1238 } else {
1239 bool AlreadyExists = false;
1240
1241 // Scan to see if this pattern has already been emitted. We can get
1242 // duplication due to things like commuting:
1243 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1244 // which are the same pattern. Ignore the dups.
1245 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1246 if (R->isIsomorphicTo(OutVariants[i])) {
1247 AlreadyExists = true;
1248 break;
1249 }
1250
1251 if (AlreadyExists)
1252 delete R;
1253 else
1254 OutVariants.push_back(R);
1255 }
1256
1257 // Increment indices to the next permutation.
1258 NotDone = false;
1259 // Look for something we can increment without causing a wrap-around.
1260 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1261 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1262 NotDone = true; // Found something to increment.
1263 break;
1264 }
1265 Idxs[IdxsIdx] = 0;
1266 }
1267 }
1268}
1269
Chris Lattneraf302912005-09-29 22:36:54 +00001270/// CombineChildVariants - A helper function for binary operators.
1271///
1272static void CombineChildVariants(TreePatternNode *Orig,
1273 const std::vector<TreePatternNode*> &LHS,
1274 const std::vector<TreePatternNode*> &RHS,
1275 std::vector<TreePatternNode*> &OutVariants,
1276 DAGISelEmitter &ISE) {
1277 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1278 ChildVariants.push_back(LHS);
1279 ChildVariants.push_back(RHS);
1280 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1281}
1282
1283
1284static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1285 std::vector<TreePatternNode *> &Children) {
1286 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1287 Record *Operator = N->getOperator();
1288
1289 // Only permit raw nodes.
1290 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1291 N->getTransformFn()) {
1292 Children.push_back(N);
1293 return;
1294 }
1295
1296 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1297 Children.push_back(N->getChild(0));
1298 else
1299 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1300
1301 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1302 Children.push_back(N->getChild(1));
1303 else
1304 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1305}
1306
Chris Lattnere46e17b2005-09-29 19:28:10 +00001307/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1308/// the (potentially recursive) pattern by using algebraic laws.
1309///
1310static void GenerateVariantsOf(TreePatternNode *N,
1311 std::vector<TreePatternNode*> &OutVariants,
1312 DAGISelEmitter &ISE) {
1313 // We cannot permute leaves.
1314 if (N->isLeaf()) {
1315 OutVariants.push_back(N);
1316 return;
1317 }
1318
1319 // Look up interesting info about the node.
1320 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1321
1322 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001323 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1324 // Reassociate by pulling together all of the linked operators
1325 std::vector<TreePatternNode*> MaximalChildren;
1326 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1327
1328 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1329 // permutations.
1330 if (MaximalChildren.size() == 3) {
1331 // Find the variants of all of our maximal children.
1332 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1333 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1334 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1335 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1336
1337 // There are only two ways we can permute the tree:
1338 // (A op B) op C and A op (B op C)
1339 // Within these forms, we can also permute A/B/C.
1340
1341 // Generate legal pair permutations of A/B/C.
1342 std::vector<TreePatternNode*> ABVariants;
1343 std::vector<TreePatternNode*> BAVariants;
1344 std::vector<TreePatternNode*> ACVariants;
1345 std::vector<TreePatternNode*> CAVariants;
1346 std::vector<TreePatternNode*> BCVariants;
1347 std::vector<TreePatternNode*> CBVariants;
1348 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1349 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1350 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1351 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1352 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1353 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1354
1355 // Combine those into the result: (x op x) op x
1356 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1357 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1358 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1359 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1360 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1361 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1362
1363 // Combine those into the result: x op (x op x)
1364 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1365 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1366 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1367 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1368 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1369 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1370 return;
1371 }
1372 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001373
1374 // Compute permutations of all children.
1375 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1376 ChildVariants.resize(N->getNumChildren());
1377 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1378 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1379
1380 // Build all permutations based on how the children were formed.
1381 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1382
1383 // If this node is commutative, consider the commuted order.
1384 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1385 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001386 // Consider the commuted order.
1387 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1388 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001389 }
1390}
1391
1392
Chris Lattnere97603f2005-09-28 19:27:25 +00001393// GenerateVariants - Generate variants. For example, commutative patterns can
1394// match multiple ways. Add them to PatternsToMatch as well.
1395void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001396
1397 DEBUG(std::cerr << "Generating instruction variants.\n");
1398
1399 // Loop over all of the patterns we've collected, checking to see if we can
1400 // generate variants of the instruction, through the exploitation of
1401 // identities. This permits the target to provide agressive matching without
1402 // the .td file having to contain tons of variants of instructions.
1403 //
1404 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1405 // intentionally do not reconsider these. Any variants of added patterns have
1406 // already been added.
1407 //
1408 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1409 std::vector<TreePatternNode*> Variants;
1410 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1411
1412 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001413 Variants.erase(Variants.begin()); // Remove the original pattern.
1414
1415 if (Variants.empty()) // No variants for this pattern.
1416 continue;
1417
1418 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1419 PatternsToMatch[i].first->dump();
1420 std::cerr << "\n");
1421
1422 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1423 TreePatternNode *Variant = Variants[v];
1424
1425 DEBUG(std::cerr << " VAR#" << v << ": ";
1426 Variant->dump();
1427 std::cerr << "\n");
1428
1429 // Scan to see if an instruction or explicit pattern already matches this.
1430 bool AlreadyExists = false;
1431 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1432 // Check to see if this variant already exists.
1433 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1434 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1435 AlreadyExists = true;
1436 break;
1437 }
1438 }
1439 // If we already have it, ignore the variant.
1440 if (AlreadyExists) continue;
1441
1442 // Otherwise, add it to the list of patterns we have.
1443 PatternsToMatch.push_back(std::make_pair(Variant,
1444 PatternsToMatch[i].second));
1445 }
1446
1447 DEBUG(std::cerr << "\n");
1448 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001449}
1450
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001451
Chris Lattner05814af2005-09-28 17:57:56 +00001452/// getPatternSize - Return the 'size' of this pattern. We want to match large
1453/// patterns before small ones. This is used to determine the size of a
1454/// pattern.
1455static unsigned getPatternSize(TreePatternNode *P) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001456 assert(isExtIntegerVT(P->getExtType()) ||
1457 isExtFloatingPointVT(P->getExtType()) &&
Chris Lattner05814af2005-09-28 17:57:56 +00001458 "Not a valid pattern node to size!");
1459 unsigned Size = 1; // The node itself.
1460
1461 // Count children in the count if they are also nodes.
1462 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1463 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001464 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Chris Lattner05814af2005-09-28 17:57:56 +00001465 Size += getPatternSize(Child);
1466 }
1467
1468 return Size;
1469}
1470
1471/// getResultPatternCost - Compute the number of instructions for this pattern.
1472/// This is a temporary hack. We should really include the instruction
1473/// latencies in this calculation.
1474static unsigned getResultPatternCost(TreePatternNode *P) {
1475 if (P->isLeaf()) return 0;
1476
1477 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1478 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1479 Cost += getResultPatternCost(P->getChild(i));
1480 return Cost;
1481}
1482
1483// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1484// In particular, we want to match maximal patterns first and lowest cost within
1485// a particular complexity first.
1486struct PatternSortingPredicate {
1487 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1488 DAGISelEmitter::PatternToMatch *RHS) {
1489 unsigned LHSSize = getPatternSize(LHS->first);
1490 unsigned RHSSize = getPatternSize(RHS->first);
1491 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1492 if (LHSSize < RHSSize) return false;
1493
1494 // If the patterns have equal complexity, compare generated instruction cost
1495 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1496 }
1497};
1498
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001499/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
1500/// if the match fails. At this point, we already know that the opcode for N
1501/// matches, and the SDNode for the result has the RootName specified name.
1502void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001503 const std::string &RootName,
1504 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001505 unsigned PatternNo, std::ostream &OS) {
1506 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001507
1508 // If this node has a name associated with it, capture it in VarMap. If
1509 // we already saw this in the pattern, emit code to verify dagness.
1510 if (!N->getName().empty()) {
1511 std::string &VarMapEntry = VarMap[N->getName()];
1512 if (VarMapEntry.empty()) {
1513 VarMapEntry = RootName;
1514 } else {
1515 // If we get here, this is a second reference to a specific name. Since
1516 // we already have checked that the first reference is valid, we don't
1517 // have to recursively match it, just check that it's the same as the
1518 // previously named thing.
1519 OS << " if (" << VarMapEntry << " != " << RootName
1520 << ") goto P" << PatternNo << "Fail;\n";
1521 return;
1522 }
1523 }
1524
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001525 // Emit code to load the child nodes and match their contents recursively.
1526 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001527 OS << " SDOperand " << RootName << i <<" = " << RootName
1528 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001529 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001530
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001531 if (!Child->isLeaf()) {
1532 // If it's not a leaf, recursively match.
1533 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001534 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001535 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001536 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001537 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001538 // If this child has a name associated with it, capture it in VarMap. If
1539 // we already saw this in the pattern, emit code to verify dagness.
1540 if (!Child->getName().empty()) {
1541 std::string &VarMapEntry = VarMap[Child->getName()];
1542 if (VarMapEntry.empty()) {
1543 VarMapEntry = RootName + utostr(i);
1544 } else {
1545 // If we get here, this is a second reference to a specific name. Since
1546 // we already have checked that the first reference is valid, we don't
1547 // have to recursively match it, just check that it's the same as the
1548 // previously named thing.
1549 OS << " if (" << VarMapEntry << " != " << RootName << i
1550 << ") goto P" << PatternNo << "Fail;\n";
1551 continue;
1552 }
1553 }
1554
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001555 // Handle leaves of various types.
1556 Init *LeafVal = Child->getLeafValue();
1557 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1558 if (LeafRec->isSubClassOf("RegisterClass")) {
1559 // Handle register references. Nothing to do here.
1560 } else if (LeafRec->isSubClassOf("ValueType")) {
1561 // Make sure this is the specified value type.
1562 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1563 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1564 << "Fail;\n";
1565 } else {
1566 Child->dump();
1567 assert(0 && "Unknown leaf type!");
1568 }
1569 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001570 }
1571
1572 // If there is a node predicate for this, emit the call.
1573 if (!N->getPredicateFn().empty())
1574 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001575 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001576}
1577
Chris Lattner6bc7e512005-09-26 21:53:26 +00001578/// CodeGenPatternResult - Emit the action for a pattern. Now that it has
1579/// matched, we actually have to build a DAG!
Chris Lattner72fe91c2005-09-24 00:40:24 +00001580unsigned DAGISelEmitter::
1581CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1582 std::map<std::string,std::string> &VariableMap,
Chris Lattner5024d932005-10-16 01:41:58 +00001583 std::ostream &OS, bool isRoot) {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001584 // This is something selected from the pattern we matched.
1585 if (!N->getName().empty()) {
Chris Lattner5024d932005-10-16 01:41:58 +00001586 assert(!isRoot && "Root of pattern cannot be a leaf!");
Chris Lattner6bc7e512005-09-26 21:53:26 +00001587 std::string &Val = VariableMap[N->getName()];
Chris Lattner72fe91c2005-09-24 00:40:24 +00001588 assert(!Val.empty() &&
1589 "Variable referenced but not defined and not caught earlier!");
1590 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1591 // Already selected this operand, just return the tmpval.
Chris Lattner6bc7e512005-09-26 21:53:26 +00001592 return atoi(Val.c_str()+3);
Chris Lattner72fe91c2005-09-24 00:40:24 +00001593 }
Chris Lattnerf6f94162005-09-28 16:58:06 +00001594
1595 unsigned ResNo = Ctr++;
1596 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1597 switch (N->getType()) {
1598 default: assert(0 && "Unknown type for constant node!");
1599 case MVT::i1: OS << " bool Tmp"; break;
1600 case MVT::i8: OS << " unsigned char Tmp"; break;
1601 case MVT::i16: OS << " unsigned short Tmp"; break;
1602 case MVT::i32: OS << " unsigned Tmp"; break;
1603 case MVT::i64: OS << " uint64_t Tmp"; break;
1604 }
1605 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1606 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1607 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1608 } else {
1609 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1610 }
1611 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1612 // value if used multiple times by this pattern result.
1613 Val = "Tmp"+utostr(ResNo);
1614 return ResNo;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001615 }
1616
1617 if (N->isLeaf()) {
1618 N->dump();
1619 assert(0 && "Unknown leaf type!");
1620 return ~0U;
1621 }
1622
1623 Record *Op = N->getOperator();
1624 if (Op->isSubClassOf("Instruction")) {
1625 // Emit all of the operands.
1626 std::vector<unsigned> Ops;
1627 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1628 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1629
1630 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1631 unsigned ResNo = Ctr++;
1632
Chris Lattner5024d932005-10-16 01:41:58 +00001633 if (!isRoot) {
1634 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1635 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1636 << getEnumName(N->getType());
1637 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1638 OS << ", Tmp" << Ops[i];
1639 OS << ");\n";
1640 } else {
1641 // If this instruction is the root, and if there is only one use of it,
1642 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
1643 OS << " if (N.Val->hasOneUse()) {\n";
1644 OS << " CurDAG->SelectNodeTo(N.Val, "
1645 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1646 << getEnumName(N->getType());
1647 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1648 OS << ", Tmp" << Ops[i];
1649 OS << ");\n";
1650 OS << " return N;\n";
1651 OS << " } else {\n";
1652 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
1653 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1654 << getEnumName(N->getType());
1655 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1656 OS << ", Tmp" << Ops[i];
1657 OS << ");\n";
1658 OS << " }\n";
1659 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001660 return ResNo;
1661 } else if (Op->isSubClassOf("SDNodeXForm")) {
1662 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1663 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1664
1665 unsigned ResNo = Ctr++;
1666 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1667 << "(Tmp" << OpVal << ".Val);\n";
Chris Lattner5024d932005-10-16 01:41:58 +00001668 if (isRoot) {
1669 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
1670 OS << " return Tmp" << ResNo << ";\n";
1671 }
Chris Lattner72fe91c2005-09-24 00:40:24 +00001672 return ResNo;
1673 } else {
1674 N->dump();
1675 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001676 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001677 }
1678}
1679
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001680/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1681/// type information from it.
1682static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001683 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001684 if (!N->isLeaf())
1685 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1686 RemoveAllTypes(N->getChild(i));
1687}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001688
Chris Lattner7e82f132005-10-15 21:34:21 +00001689/// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
1690/// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1691/// 'Pat' may be missing types. If we find an unresolved type to add a check
1692/// for, this returns true otherwise false if Pat has all types.
1693static bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1694 const std::string &Prefix, unsigned PatternNo,
1695 std::ostream &OS) {
1696 // Did we find one?
1697 if (!Pat->hasTypeSet()) {
1698 // Move a type over from 'other' to 'pat'.
1699 Pat->setType(Other->getType());
1700 OS << " if (" << Prefix << ".getValueType() != MVT::"
1701 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
1702 return true;
1703 } else if (Pat->isLeaf()) {
1704 return false;
1705 }
1706
1707 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i)
1708 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1709 Prefix + utostr(i), PatternNo, OS))
1710 return true;
1711 return false;
1712}
1713
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001714/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1715/// stream to match the pattern, and generate the code for the match if it
1716/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001717void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1718 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001719 static unsigned PatternCount = 0;
1720 unsigned PatternNo = PatternCount++;
1721 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001722 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00001723 OS << "\n // Emits: ";
1724 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001725 OS << "\n";
Chris Lattner05814af2005-09-28 17:57:56 +00001726 OS << " // Pattern complexity = " << getPatternSize(Pattern.first)
1727 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001728
Chris Lattner8fc35682005-09-23 23:16:51 +00001729 // Emit the matcher, capturing named arguments in VariableMap.
1730 std::map<std::string,std::string> VariableMap;
1731 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001732
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001733 // TP - Get *SOME* tree pattern, we don't care which.
1734 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001735
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001736 // At this point, we know that we structurally match the pattern, but the
1737 // types of the nodes may not match. Figure out the fewest number of type
1738 // comparisons we need to emit. For example, if there is only one integer
1739 // type supported by a target, there should be no type comparisons at all for
1740 // integer patterns!
1741 //
1742 // To figure out the fewest number of type checks needed, clone the pattern,
1743 // remove the types, then perform type inference on the pattern as a whole.
1744 // If there are unresolved types, emit an explicit check for those types,
1745 // apply the type to the tree, then rerun type inference. Iterate until all
1746 // types are resolved.
1747 //
1748 TreePatternNode *Pat = Pattern.first->clone();
1749 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001750
1751 do {
1752 // Resolve/propagate as many types as possible.
1753 try {
1754 bool MadeChange = true;
1755 while (MadeChange)
1756 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
1757 } catch (...) {
1758 assert(0 && "Error: could not find consistent types for something we"
1759 " already decided was ok!");
1760 abort();
1761 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001762
Chris Lattner7e82f132005-10-15 21:34:21 +00001763 // Insert a check for an unresolved type and add it to the tree. If we find
1764 // an unresolved type to add a check for, this returns true and we iterate,
1765 // otherwise we are done.
1766 } while (InsertOneTypeCheck(Pat, Pattern.first, "N", PatternNo, OS));
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001767
Chris Lattner5024d932005-10-16 01:41:58 +00001768 unsigned TmpNo = 0;
1769 CodeGenPatternResult(Pattern.second, TmpNo,
1770 VariableMap, OS, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001771 delete Pat;
1772
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001773 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001774}
1775
Chris Lattner37481472005-09-26 21:59:35 +00001776
1777namespace {
1778 /// CompareByRecordName - An ordering predicate that implements less-than by
1779 /// comparing the names records.
1780 struct CompareByRecordName {
1781 bool operator()(const Record *LHS, const Record *RHS) const {
1782 // Sort by name first.
1783 if (LHS->getName() < RHS->getName()) return true;
1784 // If both names are equal, sort by pointer.
1785 return LHS->getName() == RHS->getName() && LHS < RHS;
1786 }
1787 };
1788}
1789
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001790void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001791 std::string InstNS = Target.inst_begin()->second.Namespace;
1792 if (!InstNS.empty()) InstNS += "::";
1793
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001794 // Emit boilerplate.
1795 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001796 << "SDOperand SelectCode(SDOperand N) {\n"
1797 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001798 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1799 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001800 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001801 << " if (!N.Val->hasOneUse()) {\n"
1802 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1803 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1804 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001805 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001806 << " default: break;\n"
1807 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001808 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001809 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001810 << " case ISD::AssertZext: {\n"
1811 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
1812 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
1813 << " return Tmp0;\n"
1814 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001815
Chris Lattner81303322005-09-23 19:36:15 +00001816 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00001817 std::map<Record*, std::vector<PatternToMatch*>,
1818 CompareByRecordName> PatternsByOpcode;
Chris Lattner81303322005-09-23 19:36:15 +00001819 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1820 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1821 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001822
Chris Lattner3f7e9142005-09-23 20:52:47 +00001823 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00001824 for (std::map<Record*, std::vector<PatternToMatch*>,
1825 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
1826 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00001827 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1828 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1829
1830 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001831
1832 // We want to emit all of the matching code now. However, we want to emit
1833 // the matches in order of minimal cost. Sort the patterns so the least
1834 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001835 std::stable_sort(Patterns.begin(), Patterns.end(),
1836 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001837
Chris Lattner3f7e9142005-09-23 20:52:47 +00001838 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1839 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001840 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001841 }
1842
1843
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001844 OS << " } // end of big switch.\n\n"
1845 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001846 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001847 << " std::cerr << '\\n';\n"
1848 << " abort();\n"
1849 << "}\n";
1850}
1851
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001852void DAGISelEmitter::run(std::ostream &OS) {
1853 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1854 " target", OS);
1855
Chris Lattner1f39e292005-09-14 00:09:24 +00001856 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1857 << "// *** instruction selector class. These functions are really "
1858 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001859
Chris Lattner296dfe32005-09-24 00:50:51 +00001860 OS << "// Instance var to keep track of multiply used nodes that have \n"
1861 << "// already been selected.\n"
1862 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1863
Chris Lattnerca559d02005-09-08 21:03:01 +00001864 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001865 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001866 ParsePatternFragments(OS);
1867 ParseInstructions();
1868 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001869
Chris Lattnere97603f2005-09-28 19:27:25 +00001870 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00001871 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00001872 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001873
Chris Lattnere46e17b2005-09-29 19:28:10 +00001874
1875 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
1876 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1877 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
1878 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
1879 std::cerr << "\n";
1880 });
1881
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001882 // At this point, we have full information about the 'Patterns' we need to
1883 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001884 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001885 EmitInstructionSelector(OS);
1886
1887 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1888 E = PatternFragments.end(); I != E; ++I)
1889 delete I->second;
1890 PatternFragments.clear();
1891
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001892 Instructions.clear();
1893}