blob: f663c551334134c2f2b7f8cc9a9c0377488a98dc [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 {
Evan Cheng1c3d19e2005-12-04 08:18:16 +000087 assert(NumResults <= 1 &&
88 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +000089
90 if (OpNo < NumResults)
91 return N; // FIXME: need value #
92 else
93 return N->getChild(OpNo-NumResults);
94}
95
96/// ApplyTypeConstraint - Given a node in a pattern, apply this type
97/// constraint to the nodes operands. This returns true if it makes a
98/// change, false otherwise. If a type contradiction is found, throw an
99/// exception.
100bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
101 const SDNodeInfo &NodeInfo,
102 TreePattern &TP) const {
103 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000104 assert(NumResults <= 1 &&
105 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000106
107 // Check that the number of operands is sane.
108 if (NodeInfo.getNumOperands() >= 0) {
109 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
110 TP.error(N->getOperator()->getName() + " node requires exactly " +
111 itostr(NodeInfo.getNumOperands()) + " operands!");
112 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000113
114 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000115
116 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
117
118 switch (ConstraintType) {
119 default: assert(0 && "Unknown constraint type!");
120 case SDTCisVT:
121 // Operand must be a particular type.
122 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000123 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000124 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000125 std::vector<MVT::ValueType> IntVTs =
126 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000127
128 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000129 if (IntVTs.size() == 1)
130 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000131 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000132 }
133 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000134 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000135 std::vector<MVT::ValueType> FPVTs =
136 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000137
138 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000139 if (FPVTs.size() == 1)
140 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000141 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000142 }
Chris Lattner32707602005-09-08 23:22:48 +0000143 case SDTCisSameAs: {
144 TreePatternNode *OtherNode =
145 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000146 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
147 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000148 }
149 case SDTCisVTSmallerThanOp: {
150 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
151 // have an integer type that is smaller than the VT.
152 if (!NodeToApply->isLeaf() ||
153 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
154 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
155 ->isSubClassOf("ValueType"))
156 TP.error(N->getOperator()->getName() + " expects a VT operand!");
157 MVT::ValueType VT =
158 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
159 if (!MVT::isInteger(VT))
160 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
161
162 TreePatternNode *OtherNode =
163 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000164
165 // It must be integer.
166 bool MadeChange = false;
167 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
168
169 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000170 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
171 return false;
172 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000173 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000174 TreePatternNode *BigOperand =
175 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
176
177 // Both operands must be integer or FP, but we don't care which.
178 bool MadeChange = false;
179
180 if (isExtIntegerVT(NodeToApply->getExtType()))
181 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
182 else if (isExtFloatingPointVT(NodeToApply->getExtType()))
183 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
184 if (isExtIntegerVT(BigOperand->getExtType()))
185 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
186 else if (isExtFloatingPointVT(BigOperand->getExtType()))
187 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
188
189 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
190
191 if (isExtIntegerVT(NodeToApply->getExtType())) {
192 VTs = FilterVTs(VTs, MVT::isInteger);
193 } else if (isExtFloatingPointVT(NodeToApply->getExtType())) {
194 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
195 } else {
196 VTs.clear();
197 }
198
199 switch (VTs.size()) {
200 default: // Too many VT's to pick from.
201 case 0: break; // No info yet.
202 case 1:
203 // Only one VT of this flavor. Cannot ever satisify the constraints.
204 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
205 case 2:
206 // If we have exactly two possible types, the little operand must be the
207 // small one, the big operand should be the big one. Common with
208 // float/double for example.
209 assert(VTs[0] < VTs[1] && "Should be sorted!");
210 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
211 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
212 break;
213 }
214 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000215 }
Chris Lattner32707602005-09-08 23:22:48 +0000216 }
217 return false;
218}
219
220
Chris Lattner33c92e92005-09-08 21:27:15 +0000221//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000222// SDNodeInfo implementation
223//
224SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
225 EnumName = R->getValueAsString("Opcode");
226 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000227 Record *TypeProfile = R->getValueAsDef("TypeProfile");
228 NumResults = TypeProfile->getValueAsInt("NumResults");
229 NumOperands = TypeProfile->getValueAsInt("NumOperands");
230
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000231 // Parse the properties.
232 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000233 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000234 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
235 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000236 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000237 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000238 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000239 } else if (PropList[i]->getName() == "SDNPHasChain") {
240 Properties |= 1 << SDNPHasChain;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000241 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000242 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000243 << "' on node '" << R->getName() << "'!\n";
244 exit(1);
245 }
246 }
247
248
Chris Lattner33c92e92005-09-08 21:27:15 +0000249 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000250 std::vector<Record*> ConstraintList =
251 TypeProfile->getValueAsListOfDefs("Constraints");
252 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000253}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000254
255//===----------------------------------------------------------------------===//
256// TreePatternNode implementation
257//
258
259TreePatternNode::~TreePatternNode() {
260#if 0 // FIXME: implement refcounted tree nodes!
261 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
262 delete getChild(i);
263#endif
264}
265
Chris Lattner32707602005-09-08 23:22:48 +0000266/// UpdateNodeType - Set the node type of N to VT if VT contains
267/// information. If N already contains a conflicting type, then throw an
268/// exception. This returns true if any information was updated.
269///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000270bool TreePatternNode::UpdateNodeType(unsigned char VT, TreePattern &TP) {
271 if (VT == MVT::isUnknown || getExtType() == VT) return false;
272 if (getExtType() == MVT::isUnknown) {
Chris Lattner32707602005-09-08 23:22:48 +0000273 setType(VT);
274 return true;
275 }
276
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000277 // If we are told this is to be an int or FP type, and it already is, ignore
278 // the advice.
279 if ((VT == MVT::isInt && isExtIntegerVT(getExtType())) ||
280 (VT == MVT::isFP && isExtFloatingPointVT(getExtType())))
281 return false;
282
283 // If we know this is an int or fp type, and we are told it is a specific one,
284 // take the advice.
285 if ((getExtType() == MVT::isInt && isExtIntegerVT(VT)) ||
286 (getExtType() == MVT::isFP && isExtFloatingPointVT(VT))) {
287 setType(VT);
288 return true;
289 }
290
Chris Lattner1531f202005-10-26 16:59:37 +0000291 if (isLeaf()) {
292 dump();
293 TP.error("Type inference contradiction found in node!");
294 } else {
295 TP.error("Type inference contradiction found in node " +
296 getOperator()->getName() + "!");
297 }
Chris Lattner32707602005-09-08 23:22:48 +0000298 return true; // unreachable
299}
300
301
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000302void TreePatternNode::print(std::ostream &OS) const {
303 if (isLeaf()) {
304 OS << *getLeafValue();
305 } else {
306 OS << "(" << getOperator()->getName();
307 }
308
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000309 switch (getExtType()) {
310 case MVT::Other: OS << ":Other"; break;
311 case MVT::isInt: OS << ":isInt"; break;
312 case MVT::isFP : OS << ":isFP"; break;
313 case MVT::isUnknown: ; /*OS << ":?";*/ break;
314 default: OS << ":" << getType(); break;
315 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000316
317 if (!isLeaf()) {
318 if (getNumChildren() != 0) {
319 OS << " ";
320 getChild(0)->print(OS);
321 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
322 OS << ", ";
323 getChild(i)->print(OS);
324 }
325 }
326 OS << ")";
327 }
328
329 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000330 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000331 if (TransformFn)
332 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000333 if (!getName().empty())
334 OS << ":$" << getName();
335
336}
337void TreePatternNode::dump() const {
338 print(std::cerr);
339}
340
Chris Lattnere46e17b2005-09-29 19:28:10 +0000341/// isIsomorphicTo - Return true if this node is recursively isomorphic to
342/// the specified node. For this comparison, all of the state of the node
343/// is considered, except for the assigned name. Nodes with differing names
344/// that are otherwise identical are considered isomorphic.
345bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
346 if (N == this) return true;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000347 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000348 getPredicateFn() != N->getPredicateFn() ||
349 getTransformFn() != N->getTransformFn())
350 return false;
351
352 if (isLeaf()) {
353 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
354 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
355 return DI->getDef() == NDI->getDef();
356 return getLeafValue() == N->getLeafValue();
357 }
358
359 if (N->getOperator() != getOperator() ||
360 N->getNumChildren() != getNumChildren()) return false;
361 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
362 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
363 return false;
364 return true;
365}
366
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000367/// clone - Make a copy of this tree and all of its children.
368///
369TreePatternNode *TreePatternNode::clone() const {
370 TreePatternNode *New;
371 if (isLeaf()) {
372 New = new TreePatternNode(getLeafValue());
373 } else {
374 std::vector<TreePatternNode*> CChildren;
375 CChildren.reserve(Children.size());
376 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
377 CChildren.push_back(getChild(i)->clone());
378 New = new TreePatternNode(getOperator(), CChildren);
379 }
380 New->setName(getName());
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000381 New->setType(getExtType());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000382 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000383 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000384 return New;
385}
386
Chris Lattner32707602005-09-08 23:22:48 +0000387/// SubstituteFormalArguments - Replace the formal arguments in this tree
388/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000389void TreePatternNode::
390SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
391 if (isLeaf()) return;
392
393 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
394 TreePatternNode *Child = getChild(i);
395 if (Child->isLeaf()) {
396 Init *Val = Child->getLeafValue();
397 if (dynamic_cast<DefInit*>(Val) &&
398 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
399 // We found a use of a formal argument, replace it with its value.
400 Child = ArgMap[Child->getName()];
401 assert(Child && "Couldn't find formal argument!");
402 setChild(i, Child);
403 }
404 } else {
405 getChild(i)->SubstituteFormalArguments(ArgMap);
406 }
407 }
408}
409
410
411/// InlinePatternFragments - If this pattern refers to any pattern
412/// fragments, inline them into place, giving us a pattern without any
413/// PatFrag references.
414TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
415 if (isLeaf()) return this; // nothing to do.
416 Record *Op = getOperator();
417
418 if (!Op->isSubClassOf("PatFrag")) {
419 // Just recursively inline children nodes.
420 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
421 setChild(i, getChild(i)->InlinePatternFragments(TP));
422 return this;
423 }
424
425 // Otherwise, we found a reference to a fragment. First, look up its
426 // TreePattern record.
427 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
428
429 // Verify that we are passing the right number of operands.
430 if (Frag->getNumArgs() != Children.size())
431 TP.error("'" + Op->getName() + "' fragment requires " +
432 utostr(Frag->getNumArgs()) + " operands!");
433
Chris Lattner37937092005-09-09 01:15:01 +0000434 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000435
436 // Resolve formal arguments to their actual value.
437 if (Frag->getNumArgs()) {
438 // Compute the map of formal to actual arguments.
439 std::map<std::string, TreePatternNode*> ArgMap;
440 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
441 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
442
443 FragTree->SubstituteFormalArguments(ArgMap);
444 }
445
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000446 FragTree->setName(getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000447 FragTree->UpdateNodeType(getExtType(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000448
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000449 // Get a new copy of this fragment to stitch into here.
450 //delete this; // FIXME: implement refcounting!
451 return FragTree;
452}
453
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000454/// getIntrinsicType - Check to see if the specified record has an intrinsic
455/// type which should be applied to it. This infer the type of register
456/// references from the register file information, for example.
457///
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000458static unsigned char getIntrinsicType(Record *R, bool NotRegisters,
459 TreePattern &TP) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000460 // Check to see if this is a register or a register class...
461 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000462 if (NotRegisters) return MVT::isUnknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000463 const CodeGenRegisterClass &RC =
464 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
465 return RC.getValueTypeNum(0);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000466 } else if (R->isSubClassOf("PatFrag")) {
467 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000468 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000469 } else if (R->isSubClassOf("Register")) {
Chris Lattner22faeab2005-12-05 02:36:37 +0000470 // If the register appears in exactly one regclass, and the regclass has one
471 // value type, use it as the known type.
472 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
473 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
474 if (RC->getNumValueTypes() == 1)
475 return RC->getValueTypeNum(0);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000476 return MVT::isUnknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000477 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
478 // Using a VTSDNode or CondCodeSDNode.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000479 return MVT::Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000480 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng3aa39f42005-12-08 02:14:08 +0000481 return TP.getDAGISelEmitter().getComplexPattern(R).getValueType();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000482 } else if (R->getName() == "node") {
483 // Placeholder.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000484 return MVT::isUnknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000485 }
486
487 TP.error("Unknown node flavor used in pattern: " + R->getName());
488 return MVT::Other;
489}
490
Chris Lattner32707602005-09-08 23:22:48 +0000491/// ApplyTypeConstraints - Apply all of the type constraints relevent to
492/// this node and its children in the tree. This returns true if it makes a
493/// change, false otherwise. If a type contradiction is found, throw an
494/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000495bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
496 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000497 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000498 // If it's a regclass or something else known, include the type.
499 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
500 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000501 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
502 // Int inits are always integers. :)
503 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
504
505 if (hasTypeSet()) {
506 unsigned Size = MVT::getSizeInBits(getType());
507 // Make sure that the value is representable for this type.
508 if (Size < 32) {
509 int Val = (II->getValue() << (32-Size)) >> (32-Size);
510 if (Val != II->getValue())
511 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
512 "' is out of range for type 'MVT::" +
513 getEnumName(getType()) + "'!");
514 }
515 }
516
517 return MadeChange;
518 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000519 return false;
520 }
Chris Lattner32707602005-09-08 23:22:48 +0000521
522 // special handling for set, which isn't really an SDNode.
523 if (getOperator()->getName() == "set") {
524 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000525 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
526 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000527
528 // Types of operands must match.
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000529 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtType(), TP);
530 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtType(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000531 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
532 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000533 } else if (getOperator()->isSubClassOf("SDNode")) {
534 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
535
536 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
537 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000538 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000539 // Branch, etc. do not produce results and top-level forms in instr pattern
540 // must have void types.
541 if (NI.getNumResults() == 0)
542 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000543 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000544 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000545 const DAGInstruction &Inst =
546 TP.getDAGISelEmitter().getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000547 bool MadeChange = false;
548 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000549
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000550 assert(NumResults <= 1 &&
551 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000552 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000553 if (NumResults == 0) {
554 MadeChange = UpdateNodeType(MVT::isVoid, TP);
555 } else {
556 Record *ResultNode = Inst.getResult(0);
557 assert(ResultNode->isSubClassOf("RegisterClass") &&
558 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000559
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000560 const CodeGenRegisterClass &RC =
561 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000562
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000563 // Get the first ValueType in the RegClass, it's as good as any.
564 MadeChange = UpdateNodeType(RC.getValueTypeNum(0), TP);
565 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000566
567 if (getNumChildren() != Inst.getNumOperands())
568 TP.error("Instruction '" + getOperator()->getName() + " expects " +
569 utostr(Inst.getNumOperands()) + " operands, not " +
570 utostr(getNumChildren()) + " operands!");
571 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000572 Record *OperandNode = Inst.getOperand(i);
573 MVT::ValueType VT;
574 if (OperandNode->isSubClassOf("RegisterClass")) {
575 const CodeGenRegisterClass &RC =
576 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begeman6510b222005-12-01 04:51:06 +0000577 VT = RC.getValueTypeNum(0);
Nate Begemanddb39542005-12-01 00:06:14 +0000578 } else if (OperandNode->isSubClassOf("Operand")) {
579 VT = getValueType(OperandNode->getValueAsDef("Type"));
580 } else {
581 assert(0 && "Unknown operand type!");
582 abort();
583 }
584
585 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000586 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000587 }
588 return MadeChange;
589 } else {
590 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
591
592 // Node transforms always take one operand, and take and return the same
593 // type.
594 if (getNumChildren() != 1)
595 TP.error("Node transform '" + getOperator()->getName() +
596 "' requires one operand!");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000597 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
598 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000599 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000600 }
Chris Lattner32707602005-09-08 23:22:48 +0000601}
602
Chris Lattnere97603f2005-09-28 19:27:25 +0000603/// canPatternMatch - If it is impossible for this pattern to match on this
604/// target, fill in Reason and return false. Otherwise, return true. This is
605/// used as a santity check for .td files (to prevent people from writing stuff
606/// that can never possibly work), and to prevent the pattern permuter from
607/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000608bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000609 if (isLeaf()) return true;
610
611 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
612 if (!getChild(i)->canPatternMatch(Reason, ISE))
613 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000614
Chris Lattnere97603f2005-09-28 19:27:25 +0000615 // If this node is a commutative operator, check that the LHS isn't an
616 // immediate.
617 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
618 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
619 // Scan all of the operands of the node and make sure that only the last one
620 // is a constant node.
621 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
622 if (!getChild(i)->isLeaf() &&
623 getChild(i)->getOperator()->getName() == "imm") {
624 Reason = "Immediate value must be on the RHS of commutative operators!";
625 return false;
626 }
627 }
628
629 return true;
630}
Chris Lattner32707602005-09-08 23:22:48 +0000631
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000632//===----------------------------------------------------------------------===//
633// TreePattern implementation
634//
635
Chris Lattneredbd8712005-10-21 01:19:59 +0000636TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000637 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000638 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000639 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
640 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000641}
642
Chris Lattneredbd8712005-10-21 01:19:59 +0000643TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000644 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000645 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000646 Trees.push_back(ParseTreePattern(Pat));
647}
648
Chris Lattneredbd8712005-10-21 01:19:59 +0000649TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000650 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000651 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000652 Trees.push_back(Pat);
653}
654
655
656
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000657void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000658 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000659 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000660}
661
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000662TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
663 Record *Operator = Dag->getNodeType();
664
665 if (Operator->isSubClassOf("ValueType")) {
666 // If the operator is a ValueType, then this must be "type cast" of a leaf
667 // node.
668 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000669 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000670
671 Init *Arg = Dag->getArg(0);
672 TreePatternNode *New;
673 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000674 Record *R = DI->getDef();
675 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
676 Dag->setArg(0, new DagInit(R,
677 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000678 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000679 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000680 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000681 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
682 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000683 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
684 New = new TreePatternNode(II);
685 if (!Dag->getArgName(0).empty())
686 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000687 } else {
688 Arg->dump();
689 error("Unknown leaf value for tree pattern!");
690 return 0;
691 }
692
Chris Lattner32707602005-09-08 23:22:48 +0000693 // Apply the type cast.
694 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000695 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000696 return New;
697 }
698
699 // Verify that this is something that makes sense for an operator.
700 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000701 !Operator->isSubClassOf("Instruction") &&
702 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000703 Operator->getName() != "set")
704 error("Unrecognized node '" + Operator->getName() + "'!");
705
Chris Lattneredbd8712005-10-21 01:19:59 +0000706 // Check to see if this is something that is illegal in an input pattern.
707 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
708 Operator->isSubClassOf("SDNodeXForm")))
709 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
710
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000711 std::vector<TreePatternNode*> Children;
712
713 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
714 Init *Arg = Dag->getArg(i);
715 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
716 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000717 if (Children.back()->getName().empty())
718 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000719 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
720 Record *R = DefI->getDef();
721 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
722 // TreePatternNode if its own.
723 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
724 Dag->setArg(i, new DagInit(R,
725 std::vector<std::pair<Init*, std::string> >()));
726 --i; // Revisit this node...
727 } else {
728 TreePatternNode *Node = new TreePatternNode(DefI);
729 Node->setName(Dag->getArgName(i));
730 Children.push_back(Node);
731
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000732 // Input argument?
733 if (R->getName() == "node") {
734 if (Dag->getArgName(i).empty())
735 error("'node' argument requires a name to match with operand list");
736 Args.push_back(Dag->getArgName(i));
737 }
738 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000739 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
740 TreePatternNode *Node = new TreePatternNode(II);
741 if (!Dag->getArgName(i).empty())
742 error("Constant int argument should not have a name!");
743 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000744 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000745 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000746 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000747 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000748 error("Unknown leaf value for tree pattern!");
749 }
750 }
751
752 return new TreePatternNode(Operator, Children);
753}
754
Chris Lattner32707602005-09-08 23:22:48 +0000755/// InferAllTypes - Infer/propagate as many types throughout the expression
756/// patterns as possible. Return true if all types are infered, false
757/// otherwise. Throw an exception if a type contradiction is found.
758bool TreePattern::InferAllTypes() {
759 bool MadeChange = true;
760 while (MadeChange) {
761 MadeChange = false;
762 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000763 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000764 }
765
766 bool HasUnresolvedTypes = false;
767 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
768 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
769 return !HasUnresolvedTypes;
770}
771
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000772void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000773 OS << getRecord()->getName();
774 if (!Args.empty()) {
775 OS << "(" << Args[0];
776 for (unsigned i = 1, e = Args.size(); i != e; ++i)
777 OS << ", " << Args[i];
778 OS << ")";
779 }
780 OS << ": ";
781
782 if (Trees.size() > 1)
783 OS << "[\n";
784 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
785 OS << "\t";
786 Trees[i]->print(OS);
787 OS << "\n";
788 }
789
790 if (Trees.size() > 1)
791 OS << "]\n";
792}
793
794void TreePattern::dump() const { print(std::cerr); }
795
796
797
798//===----------------------------------------------------------------------===//
799// DAGISelEmitter implementation
800//
801
Chris Lattnerca559d02005-09-08 21:03:01 +0000802// Parse all of the SDNode definitions for the target, populating SDNodes.
803void DAGISelEmitter::ParseNodeInfo() {
804 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
805 while (!Nodes.empty()) {
806 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
807 Nodes.pop_back();
808 }
809}
810
Chris Lattner24eeeb82005-09-13 21:51:00 +0000811/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
812/// map, and emit them to the file as functions.
813void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
814 OS << "\n// Node transformations.\n";
815 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
816 while (!Xforms.empty()) {
817 Record *XFormNode = Xforms.back();
818 Record *SDNode = XFormNode->getValueAsDef("Opcode");
819 std::string Code = XFormNode->getValueAsCode("XFormFunction");
820 SDNodeXForms.insert(std::make_pair(XFormNode,
821 std::make_pair(SDNode, Code)));
822
Chris Lattner1048b7a2005-09-13 22:03:37 +0000823 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000824 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
825 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
826
Chris Lattner1048b7a2005-09-13 22:03:37 +0000827 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000828 << "(SDNode *" << C2 << ") {\n";
829 if (ClassName != "SDNode")
830 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
831 OS << Code << "\n}\n";
832 }
833
834 Xforms.pop_back();
835 }
836}
837
Evan Cheng0fc71982005-12-08 02:00:36 +0000838void DAGISelEmitter::ParseComplexPatterns() {
839 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
840 while (!AMs.empty()) {
841 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
842 AMs.pop_back();
843 }
844}
Chris Lattner24eeeb82005-09-13 21:51:00 +0000845
846
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000847/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
848/// file, building up the PatternFragments map. After we've collected them all,
849/// inline fragments together as necessary, so that there are no references left
850/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000851///
852/// This also emits all of the predicate functions to the output file.
853///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000854void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000855 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
856
857 // First step, parse all of the fragments and emit predicate functions.
858 OS << "\n// Predicate functions.\n";
859 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000860 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000861 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000862 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000863
864 // Validate the argument list, converting it to map, to discard duplicates.
865 std::vector<std::string> &Args = P->getArgList();
866 std::set<std::string> OperandsMap(Args.begin(), Args.end());
867
868 if (OperandsMap.count(""))
869 P->error("Cannot have unnamed 'node' values in pattern fragment!");
870
871 // Parse the operands list.
872 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
873 if (OpsList->getNodeType()->getName() != "ops")
874 P->error("Operands list should start with '(ops ... '!");
875
876 // Copy over the arguments.
877 Args.clear();
878 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
879 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
880 static_cast<DefInit*>(OpsList->getArg(j))->
881 getDef()->getName() != "node")
882 P->error("Operands list should all be 'node' values.");
883 if (OpsList->getArgName(j).empty())
884 P->error("Operands list should have names for each operand!");
885 if (!OperandsMap.count(OpsList->getArgName(j)))
886 P->error("'" + OpsList->getArgName(j) +
887 "' does not occur in pattern or was multiply specified!");
888 OperandsMap.erase(OpsList->getArgName(j));
889 Args.push_back(OpsList->getArgName(j));
890 }
891
892 if (!OperandsMap.empty())
893 P->error("Operands list does not contain an entry for operand '" +
894 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000895
896 // If there is a code init for this fragment, emit the predicate code and
897 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000898 std::string Code = Fragments[i]->getValueAsCode("Predicate");
899 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000900 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000901 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000902 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000903 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
904
Chris Lattner1048b7a2005-09-13 22:03:37 +0000905 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000906 << "(SDNode *" << C2 << ") {\n";
907 if (ClassName != "SDNode")
908 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000909 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000910 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000911 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000912
913 // If there is a node transformation corresponding to this, keep track of
914 // it.
915 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
916 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000917 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000918 }
919
920 OS << "\n\n";
921
922 // Now that we've parsed all of the tree fragments, do a closure on them so
923 // that there are not references to PatFrags left inside of them.
924 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
925 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000926 TreePattern *ThePat = I->second;
927 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000928
Chris Lattner32707602005-09-08 23:22:48 +0000929 // Infer as many types as possible. Don't worry about it if we don't infer
930 // all of them, some may depend on the inputs of the pattern.
931 try {
932 ThePat->InferAllTypes();
933 } catch (...) {
934 // If this pattern fragment is not supported by this target (no types can
935 // satisfy its constraints), just ignore it. If the bogus pattern is
936 // actually used by instructions, the type consistency error will be
937 // reported there.
938 }
939
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000940 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000941 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000942 }
943}
944
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000945/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000946/// instruction input. Return true if this is a real use.
947static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000948 std::map<std::string, TreePatternNode*> &InstInputs) {
949 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000950 if (Pat->getName().empty()) {
951 if (Pat->isLeaf()) {
952 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
953 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
954 I->error("Input " + DI->getDef()->getName() + " must be named!");
955
956 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000957 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000958 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000959
960 Record *Rec;
961 if (Pat->isLeaf()) {
962 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
963 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
964 Rec = DI->getDef();
965 } else {
966 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
967 Rec = Pat->getOperator();
968 }
969
970 TreePatternNode *&Slot = InstInputs[Pat->getName()];
971 if (!Slot) {
972 Slot = Pat;
973 } else {
974 Record *SlotRec;
975 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000976 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000977 } else {
978 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
979 SlotRec = Slot->getOperator();
980 }
981
982 // Ensure that the inputs agree if we've already seen this input.
983 if (Rec != SlotRec)
984 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000985 if (Slot->getExtType() != Pat->getExtType())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000986 I->error("All $" + Pat->getName() + " inputs must agree with each other");
987 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000988 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000989}
990
991/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
992/// part of "I", the instruction), computing the set of inputs and outputs of
993/// the pattern. Report errors if we see anything naughty.
994void DAGISelEmitter::
995FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
996 std::map<std::string, TreePatternNode*> &InstInputs,
997 std::map<std::string, Record*> &InstResults) {
998 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000999 bool isUse = HandleUse(I, Pat, InstInputs);
1000 if (!isUse && Pat->getTransformFn())
1001 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001002 return;
1003 } else if (Pat->getOperator()->getName() != "set") {
1004 // If this is not a set, verify that the children nodes are not void typed,
1005 // and recurse.
1006 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001007 if (Pat->getChild(i)->getExtType() == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001008 I->error("Cannot have void nodes inside of patterns!");
1009 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
1010 }
1011
1012 // If this is a non-leaf node with no children, treat it basically as if
1013 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001014 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001015 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +00001016 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001017
Chris Lattnerf1311842005-09-14 23:05:13 +00001018 if (!isUse && Pat->getTransformFn())
1019 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001020 return;
1021 }
1022
1023 // Otherwise, this is a set, validate and collect instruction results.
1024 if (Pat->getNumChildren() == 0)
1025 I->error("set requires operands!");
1026 else if (Pat->getNumChildren() & 1)
1027 I->error("set requires an even number of operands");
1028
Chris Lattnerf1311842005-09-14 23:05:13 +00001029 if (Pat->getTransformFn())
1030 I->error("Cannot specify a transform function on a set node!");
1031
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001032 // Check the set destinations.
1033 unsigned NumValues = Pat->getNumChildren()/2;
1034 for (unsigned i = 0; i != NumValues; ++i) {
1035 TreePatternNode *Dest = Pat->getChild(i);
1036 if (!Dest->isLeaf())
1037 I->error("set destination should be a virtual register!");
1038
1039 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1040 if (!Val)
1041 I->error("set destination should be a virtual register!");
1042
1043 if (!Val->getDef()->isSubClassOf("RegisterClass"))
1044 I->error("set destination should be a virtual register!");
1045 if (Dest->getName().empty())
1046 I->error("set destination must have a name!");
1047 if (InstResults.count(Dest->getName()))
1048 I->error("cannot set '" + Dest->getName() +"' multiple times");
1049 InstResults[Dest->getName()] = Val->getDef();
1050
1051 // Verify and collect info from the computation.
1052 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1053 InstInputs, InstResults);
1054 }
1055}
1056
Evan Chengdd304dd2005-12-05 23:08:55 +00001057/// NodeHasChain - return true if TreePatternNode has the property
1058/// 'hasChain', meaning it reads a ctrl-flow chain operand and writes
1059/// a chain result.
1060static bool NodeHasChain(TreePatternNode *N, DAGISelEmitter &ISE)
1061{
1062 if (N->isLeaf()) return false;
1063 Record *Operator = N->getOperator();
1064 if (!Operator->isSubClassOf("SDNode")) return false;
1065
1066 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1067 return NodeInfo.hasProperty(SDNodeInfo::SDNPHasChain);
1068}
1069
1070static bool PatternHasCtrlDep(TreePatternNode *N, DAGISelEmitter &ISE)
1071{
1072 if (NodeHasChain(N, ISE))
1073 return true;
1074 else {
1075 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1076 TreePatternNode *Child = N->getChild(i);
1077 if (PatternHasCtrlDep(Child, ISE))
1078 return true;
1079 }
1080 }
1081
1082 return false;
1083}
1084
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001085
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001086/// ParseInstructions - Parse all of the instructions, inlining and resolving
1087/// any fragments involved. This populates the Instructions list with fully
1088/// resolved instructions.
1089void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001090 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1091
1092 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001093 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001094
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001095 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1096 LI = Instrs[i]->getValueAsListInit("Pattern");
1097
1098 // If there is no pattern, only collect minimal information about the
1099 // instruction for its operand list. We have to assume that there is one
1100 // result, as we have no detailed info.
1101 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001102 std::vector<Record*> Results;
1103 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001104
1105 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1106
1107 // Doesn't even define a result?
1108 if (InstInfo.OperandList.size() == 0)
1109 continue;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001110
1111 // FIXME: temporary hack...
1112 if (InstInfo.isReturn || InstInfo.isBranch || InstInfo.isCall ||
1113 InstInfo.isStore) {
1114 // These produce no results
1115 for (unsigned j = 0, e = InstInfo.OperandList.size(); j != e; ++j)
1116 Operands.push_back(InstInfo.OperandList[j].Rec);
1117 } else {
1118 // Assume the first operand is the result.
1119 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001120
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001121 // The rest are inputs.
1122 for (unsigned j = 1, e = InstInfo.OperandList.size(); j != e; ++j)
1123 Operands.push_back(InstInfo.OperandList[j].Rec);
1124 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001125
1126 // Create and insert the instruction.
1127 Instructions.insert(std::make_pair(Instrs[i],
Nate Begemanddb39542005-12-01 00:06:14 +00001128 DAGInstruction(0, Results, Operands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001129 continue; // no pattern.
1130 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001131
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001132 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001133 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001134 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001135 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001136
Chris Lattner95f6b762005-09-08 23:26:30 +00001137 // Infer as many types as possible. If we cannot infer all of them, we can
1138 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001139 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001140 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001141
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001142 // InstInputs - Keep track of all of the inputs of the instruction, along
1143 // with the record they are declared as.
1144 std::map<std::string, TreePatternNode*> InstInputs;
1145
1146 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001147 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001148 std::map<std::string, Record*> InstResults;
1149
Chris Lattner1f39e292005-09-14 00:09:24 +00001150 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001151 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001152 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1153 TreePatternNode *Pat = I->getTree(j);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001154 if (Pat->getExtType() != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001155 I->error("Top-level forms in instruction pattern should have"
1156 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001157
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001158 // Find inputs and outputs, and verify the structure of the uses/defs.
1159 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001160 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001161
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001162 // Now that we have inputs and outputs of the pattern, inspect the operands
1163 // list for the instruction. This determines the order that operands are
1164 // added to the machine instruction the node corresponds to.
1165 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001166
1167 // Parse the operands list from the (ops) list, validating it.
1168 std::vector<std::string> &Args = I->getArgList();
1169 assert(Args.empty() && "Args list should still be empty here!");
1170 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1171
1172 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001173 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001174 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001175 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001176 I->error("'" + InstResults.begin()->first +
1177 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001178 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001179
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001180 // Check that it exists in InstResults.
1181 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001182 if (R == 0)
1183 I->error("Operand $" + OpName + " should be a set destination: all "
1184 "outputs must occur before inputs in operand list!");
1185
1186 if (CGI.OperandList[i].Rec != R)
1187 I->error("Operand $" + OpName + " class mismatch!");
1188
Chris Lattnerae6d8282005-09-15 21:51:12 +00001189 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001190 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001191
Chris Lattner39e8af92005-09-14 18:19:25 +00001192 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001193 InstResults.erase(OpName);
1194 }
1195
Chris Lattner0b592252005-09-14 21:59:34 +00001196 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1197 // the copy while we're checking the inputs.
1198 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001199
1200 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001201 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001202 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1203 const std::string &OpName = CGI.OperandList[i].Name;
1204 if (OpName.empty())
1205 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1206
Chris Lattner0b592252005-09-14 21:59:34 +00001207 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001208 I->error("Operand $" + OpName +
1209 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001210 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001211 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001212
1213 if (InVal->isLeaf() &&
1214 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1215 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001216 if (CGI.OperandList[i].Rec != InRec &&
1217 !InRec->isSubClassOf("ComplexPattern"))
Nate Begemanddb39542005-12-01 00:06:14 +00001218 I->error("Operand $" + OpName +
Evan Cheng0fc71982005-12-08 02:00:36 +00001219 "'s register class disagrees between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001220 }
1221 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001222
Chris Lattner2175c182005-09-14 23:01:59 +00001223 // Construct the result for the dest-pattern operand list.
1224 TreePatternNode *OpNode = InVal->clone();
1225
1226 // No predicate is useful on the result.
1227 OpNode->setPredicateFn("");
1228
1229 // Promote the xform function to be an explicit node if set.
1230 if (Record *Xform = OpNode->getTransformFn()) {
1231 OpNode->setTransformFn(0);
1232 std::vector<TreePatternNode*> Children;
1233 Children.push_back(OpNode);
1234 OpNode = new TreePatternNode(Xform, Children);
1235 }
1236
1237 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001238 }
1239
Chris Lattner0b592252005-09-14 21:59:34 +00001240 if (!InstInputsCheck.empty())
1241 I->error("Input operand $" + InstInputsCheck.begin()->first +
1242 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001243
1244 TreePatternNode *ResultPattern =
1245 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001246
1247 // Create and insert the instruction.
Nate Begemanddb39542005-12-01 00:06:14 +00001248 DAGInstruction TheInst(I, Results, Operands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001249 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1250
1251 // Use a temporary tree pattern to infer all types and make sure that the
1252 // constructed result is correct. This depends on the instruction already
1253 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001254 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001255 Temp.InferAllTypes();
1256
1257 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1258 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001259
Chris Lattner32707602005-09-08 23:22:48 +00001260 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001261 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001262
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001263 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001264 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1265 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001266 DAGInstruction &TheInst = II->second;
1267 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001268 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001269
Chris Lattner1f39e292005-09-14 00:09:24 +00001270 if (I->getNumTrees() != 1) {
1271 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1272 continue;
1273 }
1274 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001275 TreePatternNode *SrcPattern;
1276 if (TheInst.getNumResults() == 0) {
1277 SrcPattern = Pattern;
1278 } else {
1279 if (Pattern->getOperator()->getName() != "set")
1280 continue; // Not a set (store or something?)
Chris Lattner1f39e292005-09-14 00:09:24 +00001281
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001282 if (Pattern->getNumChildren() != 2)
1283 continue; // Not a set of a single value (not handled so far)
1284
1285 SrcPattern = Pattern->getChild(1)->clone();
1286 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001287
1288 std::string Reason;
1289 if (!SrcPattern->canPatternMatch(Reason, *this))
1290 I->error("Instruction can never match: " + Reason);
1291
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001292 TreePatternNode *DstPattern = TheInst.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +00001293 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Evan Chengdd304dd2005-12-05 23:08:55 +00001294
1295 if (PatternHasCtrlDep(Pattern, *this)) {
1296 Record *Instr = II->first;
1297 CodeGenInstruction &InstInfo = Target.getInstruction(Instr->getName());
1298 InstInfo.hasCtrlDep = true;
1299 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001300 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001301}
1302
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001303void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001304 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001305
Chris Lattnerabbb6052005-09-15 21:42:00 +00001306 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001307 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001308 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001309
Chris Lattnerabbb6052005-09-15 21:42:00 +00001310 // Inline pattern fragments into it.
1311 Pattern->InlinePatternFragments();
1312
1313 // Infer as many types as possible. If we cannot infer all of them, we can
1314 // never do anything with this pattern: report it to the user.
1315 if (!Pattern->InferAllTypes())
1316 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001317
1318 // Validate that the input pattern is correct.
1319 {
1320 std::map<std::string, TreePatternNode*> InstInputs;
1321 std::map<std::string, Record*> InstResults;
1322 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1323 InstInputs, InstResults);
1324 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001325
1326 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1327 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001328
1329 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001330 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001331
1332 // Inline pattern fragments into it.
1333 Result->InlinePatternFragments();
1334
1335 // Infer as many types as possible. If we cannot infer all of them, we can
1336 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001337 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001338 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001339
1340 if (Result->getNumTrees() != 1)
1341 Result->error("Cannot handle instructions producing instructions "
1342 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001343
1344 std::string Reason;
1345 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1346 Pattern->error("Pattern can never match: " + Reason);
1347
Chris Lattnerabbb6052005-09-15 21:42:00 +00001348 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
1349 Result->getOnlyTree()));
1350 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001351}
1352
Chris Lattnere46e17b2005-09-29 19:28:10 +00001353/// CombineChildVariants - Given a bunch of permutations of each child of the
1354/// 'operator' node, put them together in all possible ways.
1355static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001356 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001357 std::vector<TreePatternNode*> &OutVariants,
1358 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001359 // Make sure that each operand has at least one variant to choose from.
1360 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1361 if (ChildVariants[i].empty())
1362 return;
1363
Chris Lattnere46e17b2005-09-29 19:28:10 +00001364 // The end result is an all-pairs construction of the resultant pattern.
1365 std::vector<unsigned> Idxs;
1366 Idxs.resize(ChildVariants.size());
1367 bool NotDone = true;
1368 while (NotDone) {
1369 // Create the variant and add it to the output list.
1370 std::vector<TreePatternNode*> NewChildren;
1371 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1372 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1373 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1374
1375 // Copy over properties.
1376 R->setName(Orig->getName());
1377 R->setPredicateFn(Orig->getPredicateFn());
1378 R->setTransformFn(Orig->getTransformFn());
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001379 R->setType(Orig->getExtType());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001380
1381 // If this pattern cannot every match, do not include it as a variant.
1382 std::string ErrString;
1383 if (!R->canPatternMatch(ErrString, ISE)) {
1384 delete R;
1385 } else {
1386 bool AlreadyExists = false;
1387
1388 // Scan to see if this pattern has already been emitted. We can get
1389 // duplication due to things like commuting:
1390 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1391 // which are the same pattern. Ignore the dups.
1392 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1393 if (R->isIsomorphicTo(OutVariants[i])) {
1394 AlreadyExists = true;
1395 break;
1396 }
1397
1398 if (AlreadyExists)
1399 delete R;
1400 else
1401 OutVariants.push_back(R);
1402 }
1403
1404 // Increment indices to the next permutation.
1405 NotDone = false;
1406 // Look for something we can increment without causing a wrap-around.
1407 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1408 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1409 NotDone = true; // Found something to increment.
1410 break;
1411 }
1412 Idxs[IdxsIdx] = 0;
1413 }
1414 }
1415}
1416
Chris Lattneraf302912005-09-29 22:36:54 +00001417/// CombineChildVariants - A helper function for binary operators.
1418///
1419static void CombineChildVariants(TreePatternNode *Orig,
1420 const std::vector<TreePatternNode*> &LHS,
1421 const std::vector<TreePatternNode*> &RHS,
1422 std::vector<TreePatternNode*> &OutVariants,
1423 DAGISelEmitter &ISE) {
1424 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1425 ChildVariants.push_back(LHS);
1426 ChildVariants.push_back(RHS);
1427 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1428}
1429
1430
1431static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1432 std::vector<TreePatternNode *> &Children) {
1433 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1434 Record *Operator = N->getOperator();
1435
1436 // Only permit raw nodes.
1437 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1438 N->getTransformFn()) {
1439 Children.push_back(N);
1440 return;
1441 }
1442
1443 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1444 Children.push_back(N->getChild(0));
1445 else
1446 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1447
1448 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1449 Children.push_back(N->getChild(1));
1450 else
1451 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1452}
1453
Chris Lattnere46e17b2005-09-29 19:28:10 +00001454/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1455/// the (potentially recursive) pattern by using algebraic laws.
1456///
1457static void GenerateVariantsOf(TreePatternNode *N,
1458 std::vector<TreePatternNode*> &OutVariants,
1459 DAGISelEmitter &ISE) {
1460 // We cannot permute leaves.
1461 if (N->isLeaf()) {
1462 OutVariants.push_back(N);
1463 return;
1464 }
1465
1466 // Look up interesting info about the node.
1467 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1468
1469 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001470 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1471 // Reassociate by pulling together all of the linked operators
1472 std::vector<TreePatternNode*> MaximalChildren;
1473 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1474
1475 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1476 // permutations.
1477 if (MaximalChildren.size() == 3) {
1478 // Find the variants of all of our maximal children.
1479 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1480 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1481 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1482 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1483
1484 // There are only two ways we can permute the tree:
1485 // (A op B) op C and A op (B op C)
1486 // Within these forms, we can also permute A/B/C.
1487
1488 // Generate legal pair permutations of A/B/C.
1489 std::vector<TreePatternNode*> ABVariants;
1490 std::vector<TreePatternNode*> BAVariants;
1491 std::vector<TreePatternNode*> ACVariants;
1492 std::vector<TreePatternNode*> CAVariants;
1493 std::vector<TreePatternNode*> BCVariants;
1494 std::vector<TreePatternNode*> CBVariants;
1495 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1496 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1497 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1498 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1499 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1500 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1501
1502 // Combine those into the result: (x op x) op x
1503 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1504 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1505 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1506 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1507 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1508 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1509
1510 // Combine those into the result: x op (x op x)
1511 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1512 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1513 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1514 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1515 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1516 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1517 return;
1518 }
1519 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001520
1521 // Compute permutations of all children.
1522 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1523 ChildVariants.resize(N->getNumChildren());
1524 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1525 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1526
1527 // Build all permutations based on how the children were formed.
1528 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1529
1530 // If this node is commutative, consider the commuted order.
1531 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1532 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001533 // Consider the commuted order.
1534 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1535 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001536 }
1537}
1538
1539
Chris Lattnere97603f2005-09-28 19:27:25 +00001540// GenerateVariants - Generate variants. For example, commutative patterns can
1541// match multiple ways. Add them to PatternsToMatch as well.
1542void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001543
1544 DEBUG(std::cerr << "Generating instruction variants.\n");
1545
1546 // Loop over all of the patterns we've collected, checking to see if we can
1547 // generate variants of the instruction, through the exploitation of
1548 // identities. This permits the target to provide agressive matching without
1549 // the .td file having to contain tons of variants of instructions.
1550 //
1551 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1552 // intentionally do not reconsider these. Any variants of added patterns have
1553 // already been added.
1554 //
1555 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1556 std::vector<TreePatternNode*> Variants;
1557 GenerateVariantsOf(PatternsToMatch[i].first, Variants, *this);
1558
1559 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001560 Variants.erase(Variants.begin()); // Remove the original pattern.
1561
1562 if (Variants.empty()) // No variants for this pattern.
1563 continue;
1564
1565 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1566 PatternsToMatch[i].first->dump();
1567 std::cerr << "\n");
1568
1569 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1570 TreePatternNode *Variant = Variants[v];
1571
1572 DEBUG(std::cerr << " VAR#" << v << ": ";
1573 Variant->dump();
1574 std::cerr << "\n");
1575
1576 // Scan to see if an instruction or explicit pattern already matches this.
1577 bool AlreadyExists = false;
1578 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1579 // Check to see if this variant already exists.
1580 if (Variant->isIsomorphicTo(PatternsToMatch[p].first)) {
1581 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1582 AlreadyExists = true;
1583 break;
1584 }
1585 }
1586 // If we already have it, ignore the variant.
1587 if (AlreadyExists) continue;
1588
1589 // Otherwise, add it to the list of patterns we have.
1590 PatternsToMatch.push_back(std::make_pair(Variant,
1591 PatternsToMatch[i].second));
1592 }
1593
1594 DEBUG(std::cerr << "\n");
1595 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001596}
1597
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001598
Evan Cheng0fc71982005-12-08 02:00:36 +00001599// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1600// ComplexPattern.
1601static bool NodeIsComplexPattern(TreePatternNode *N)
1602{
1603 return (N->isLeaf() &&
1604 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1605 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1606 isSubClassOf("ComplexPattern"));
1607}
1608
1609// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1610// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1611static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1612 DAGISelEmitter &ISE)
1613{
1614 if (N->isLeaf() &&
1615 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1616 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1617 isSubClassOf("ComplexPattern")) {
1618 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1619 ->getDef());
1620 }
1621 return NULL;
1622}
1623
Chris Lattner05814af2005-09-28 17:57:56 +00001624/// getPatternSize - Return the 'size' of this pattern. We want to match large
1625/// patterns before small ones. This is used to determine the size of a
1626/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001627static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001628 assert(isExtIntegerVT(P->getExtType()) ||
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001629 isExtFloatingPointVT(P->getExtType()) ||
1630 P->getExtType() == MVT::isVoid && "Not a valid pattern node to size!");
Chris Lattner05814af2005-09-28 17:57:56 +00001631 unsigned Size = 1; // The node itself.
Evan Cheng0fc71982005-12-08 02:00:36 +00001632
1633 // FIXME: This is a hack to statically increase the priority of patterns
1634 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1635 // Later we can allow complexity / cost for each pattern to be (optionally)
1636 // specified. To get best possible pattern match we'll need to dynamically
1637 // calculate the complexity of all patterns a dag can potentially map to.
1638 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1639 if (AM)
1640 Size += AM->getNumOperands();
1641
Chris Lattner05814af2005-09-28 17:57:56 +00001642 // Count children in the count if they are also nodes.
1643 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1644 TreePatternNode *Child = P->getChild(i);
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001645 if (!Child->isLeaf() && Child->getExtType() != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001646 Size += getPatternSize(Child, ISE);
1647 else if (Child->isLeaf()) {
1648 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1649 ++Size; // Matches a ConstantSDNode.
1650 else if (NodeIsComplexPattern(Child))
1651 Size += getPatternSize(Child, ISE);
Chris Lattner2f041d42005-10-19 04:41:05 +00001652 }
Chris Lattner05814af2005-09-28 17:57:56 +00001653 }
1654
1655 return Size;
1656}
1657
1658/// getResultPatternCost - Compute the number of instructions for this pattern.
1659/// This is a temporary hack. We should really include the instruction
1660/// latencies in this calculation.
1661static unsigned getResultPatternCost(TreePatternNode *P) {
1662 if (P->isLeaf()) return 0;
1663
1664 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1665 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1666 Cost += getResultPatternCost(P->getChild(i));
1667 return Cost;
1668}
1669
1670// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1671// In particular, we want to match maximal patterns first and lowest cost within
1672// a particular complexity first.
1673struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001674 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1675 DAGISelEmitter &ISE;
1676
Chris Lattner05814af2005-09-28 17:57:56 +00001677 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1678 DAGISelEmitter::PatternToMatch *RHS) {
Evan Cheng0fc71982005-12-08 02:00:36 +00001679 unsigned LHSSize = getPatternSize(LHS->first, ISE);
1680 unsigned RHSSize = getPatternSize(RHS->first, ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001681 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1682 if (LHSSize < RHSSize) return false;
1683
1684 // If the patterns have equal complexity, compare generated instruction cost
1685 return getResultPatternCost(LHS->second) <getResultPatternCost(RHS->second);
1686 }
1687};
1688
Nate Begeman6510b222005-12-01 04:51:06 +00001689/// getRegisterValueType - Look up and return the first ValueType of specified
1690/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001691static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001692 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1693 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001694 return MVT::Other;
1695}
1696
Chris Lattner72fe91c2005-09-24 00:40:24 +00001697
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001698/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1699/// type information from it.
1700static void RemoveAllTypes(TreePatternNode *N) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +00001701 N->setType(MVT::isUnknown);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001702 if (!N->isLeaf())
1703 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1704 RemoveAllTypes(N->getChild(i));
1705}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001706
Chris Lattner0614b622005-11-02 06:49:14 +00001707Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1708 Record *N = Records.getDef(Name);
1709 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1710 return N;
1711}
1712
Evan Chengb915f312005-12-09 22:45:35 +00001713class PatternCodeEmitter {
1714private:
1715 DAGISelEmitter &ISE;
1716
1717 // LHS of the pattern being matched
1718 TreePatternNode *LHS;
1719 unsigned PatternNo;
1720 std::ostream &OS;
1721 // Node to name mapping
1722 std::map<std::string,std::string> VariableMap;
1723 // Name of the inner most node which produces a chain.
1724 std::string InnerChain;
1725 // Names of all the folded nodes which produce chains.
1726 std::vector<std::string> FoldedChains;
1727 bool InFlag;
1728 unsigned TmpNo;
1729
1730public:
1731 PatternCodeEmitter(DAGISelEmitter &ise, TreePatternNode *lhs,
1732 unsigned PatNum, std::ostream &os) :
1733 ISE(ise), LHS(lhs), PatternNo(PatNum), OS(os),
1734 InFlag(false), TmpNo(0) {};
1735
1736 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1737 /// if the match fails. At this point, we already know that the opcode for N
1738 /// matches, and the SDNode for the result has the RootName specified name.
1739 void EmitMatchCode(TreePatternNode *N, const std::string &RootName,
1740 bool isRoot = false) {
1741 if (N->isLeaf()) {
1742 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1743 OS << " if (cast<ConstantSDNode>(" << RootName
1744 << ")->getSignExtended() != " << II->getValue() << ")\n"
1745 << " goto P" << PatternNo << "Fail;\n";
1746 return;
1747 } else if (!NodeIsComplexPattern(N)) {
1748 assert(0 && "Cannot match this as a leaf value!");
1749 abort();
1750 }
1751 }
1752
1753 // If this node has a name associated with it, capture it in VariableMap. If
1754 // we already saw this in the pattern, emit code to verify dagness.
1755 if (!N->getName().empty()) {
1756 std::string &VarMapEntry = VariableMap[N->getName()];
1757 if (VarMapEntry.empty()) {
1758 VarMapEntry = RootName;
1759 } else {
1760 // If we get here, this is a second reference to a specific name. Since
1761 // we already have checked that the first reference is valid, we don't
1762 // have to recursively match it, just check that it's the same as the
1763 // previously named thing.
1764 OS << " if (" << VarMapEntry << " != " << RootName
1765 << ") goto P" << PatternNo << "Fail;\n";
1766 return;
1767 }
1768 }
1769
1770
1771 // Emit code to load the child nodes and match their contents recursively.
1772 unsigned OpNo = 0;
1773 if (NodeHasChain(N, ISE)) {
1774 OpNo = 1;
1775 if (!isRoot) {
1776 OS << " if (!" << RootName << ".hasOneUse()) goto P"
1777 << PatternNo << "Fail; // Multiple uses of actual result?\n";
1778 OS << " if (CodeGenMap.count(" << RootName
1779 << ".getValue(1))) goto P"
1780 << PatternNo << "Fail; // Already selected for a chain use?\n";
1781 }
1782 if (InnerChain.empty()) {
1783 OS << " SDOperand " << RootName << "0 = " << RootName
1784 << ".getOperand(0);\n";
1785 InnerChain = RootName + "0";
1786 }
1787 }
1788
1789 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1790 OS << " SDOperand " << RootName << OpNo <<" = " << RootName
1791 << ".getOperand(" << OpNo << ");\n";
1792 TreePatternNode *Child = N->getChild(i);
1793
1794 if (!Child->isLeaf()) {
1795 // If it's not a leaf, recursively match.
1796 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
1797 OS << " if (" << RootName << OpNo << ".getOpcode() != "
1798 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
1799 EmitMatchCode(Child, RootName + utostr(OpNo));
1800 if (NodeHasChain(Child, ISE))
1801 FoldedChains.push_back(RootName + utostr(OpNo));
1802 } else {
1803 // If this child has a name associated with it, capture it in VarMap. If
1804 // we already saw this in the pattern, emit code to verify dagness.
1805 if (!Child->getName().empty()) {
1806 std::string &VarMapEntry = VariableMap[Child->getName()];
1807 if (VarMapEntry.empty()) {
1808 VarMapEntry = RootName + utostr(OpNo);
1809 } else {
1810 // If we get here, this is a second reference to a specific name. Since
1811 // we already have checked that the first reference is valid, we don't
1812 // have to recursively match it, just check that it's the same as the
1813 // previously named thing.
1814 OS << " if (" << VarMapEntry << " != " << RootName << OpNo
1815 << ") goto P" << PatternNo << "Fail;\n";
1816 continue;
1817 }
1818 }
1819
1820 // Handle leaves of various types.
1821 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1822 Record *LeafRec = DI->getDef();
1823 if (LeafRec->isSubClassOf("RegisterClass")) {
1824 // Handle register references. Nothing to do here.
1825 } else if (LeafRec->isSubClassOf("Register")) {
1826 if (!InFlag) {
1827 OS << " SDOperand InFlag = SDOperand(0,0);\n";
1828 InFlag = true;
1829 }
1830 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
1831 // Handle complex pattern. Nothing to do here.
1832 } else if (LeafRec->isSubClassOf("ValueType")) {
1833 // Make sure this is the specified value type.
1834 OS << " if (cast<VTSDNode>(" << RootName << OpNo << ")->getVT() != "
1835 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1836 << "Fail;\n";
1837 } else if (LeafRec->isSubClassOf("CondCode")) {
1838 // Make sure this is the specified cond code.
1839 OS << " if (cast<CondCodeSDNode>(" << RootName << OpNo
1840 << ")->get() != " << "ISD::" << LeafRec->getName()
1841 << ") goto P" << PatternNo << "Fail;\n";
1842 } else {
1843 Child->dump();
1844 assert(0 && "Unknown leaf type!");
1845 }
1846 } else if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
1847 OS << " if (!isa<ConstantSDNode>(" << RootName << OpNo << ") ||\n"
1848 << " cast<ConstantSDNode>(" << RootName << OpNo
1849 << ")->getSignExtended() != " << II->getValue() << ")\n"
1850 << " goto P" << PatternNo << "Fail;\n";
1851 } else {
1852 Child->dump();
1853 assert(0 && "Unknown leaf type!");
1854 }
1855 }
1856 }
1857
1858 // If there is a node predicate for this, emit the call.
1859 if (!N->getPredicateFn().empty())
1860 OS << " if (!" << N->getPredicateFn() << "(" << RootName
1861 << ".Val)) goto P" << PatternNo << "Fail;\n";
1862 }
1863
1864 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
1865 /// we actually have to build a DAG!
1866 std::pair<unsigned, unsigned>
1867 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
1868 // This is something selected from the pattern we matched.
1869 if (!N->getName().empty()) {
1870 assert(!isRoot && "Root of pattern cannot be a leaf!");
1871 std::string &Val = VariableMap[N->getName()];
1872 assert(!Val.empty() &&
1873 "Variable referenced but not defined and not caught earlier!");
1874 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1875 // Already selected this operand, just return the tmpval.
1876 return std::make_pair(1, atoi(Val.c_str()+3));
1877 }
1878
1879 const ComplexPattern *CP;
1880 unsigned ResNo = TmpNo++;
1881 unsigned NumRes = 1;
1882 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
1883 switch (N->getType()) {
1884 default: assert(0 && "Unknown type for constant node!");
1885 case MVT::i1: OS << " bool Tmp"; break;
1886 case MVT::i8: OS << " unsigned char Tmp"; break;
1887 case MVT::i16: OS << " unsigned short Tmp"; break;
1888 case MVT::i32: OS << " unsigned Tmp"; break;
1889 case MVT::i64: OS << " uint64_t Tmp"; break;
1890 }
1891 OS << ResNo << "C = cast<ConstantSDNode>(" << Val << ")->getValue();\n";
1892 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant(Tmp"
1893 << ResNo << "C, MVT::" << getEnumName(N->getType()) << ");\n";
1894 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
1895 OS << " SDOperand Tmp" << ResNo << " = " << Val << ";\n";
1896 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
1897 std::string Fn = CP->getSelectFunc();
1898 NumRes = CP->getNumOperands();
1899 OS << " SDOperand ";
1900 for (unsigned i = 0; i < NumRes; i++) {
1901 if (i != 0) OS << ", ";
1902 OS << "Tmp" << i + ResNo;
1903 }
1904 OS << ";\n";
1905 OS << " if (!" << Fn << "(" << Val;
1906 for (unsigned i = 0; i < NumRes; i++)
1907 OS << " , Tmp" << i + ResNo;
1908 OS << ")) goto P" << PatternNo << "Fail;\n";
1909 TmpNo = ResNo + NumRes;
1910 } else {
1911 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1912 }
1913 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
1914 // value if used multiple times by this pattern result.
1915 Val = "Tmp"+utostr(ResNo);
1916 return std::make_pair(NumRes, ResNo);
1917 }
1918
1919 if (N->isLeaf()) {
1920 // If this is an explicit register reference, handle it.
1921 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1922 unsigned ResNo = TmpNo++;
1923 if (DI->getDef()->isSubClassOf("Register")) {
1924 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getRegister("
1925 << ISE.getQualifiedName(DI->getDef()) << ", MVT::"
1926 << getEnumName(N->getType())
1927 << ");\n";
1928 return std::make_pair(1, ResNo);
1929 }
1930 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1931 unsigned ResNo = TmpNo++;
1932 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetConstant("
1933 << II->getValue() << ", MVT::"
1934 << getEnumName(N->getType())
1935 << ");\n";
1936 return std::make_pair(1, ResNo);
1937 }
1938
1939 N->dump();
1940 assert(0 && "Unknown leaf type!");
1941 return std::make_pair(1, ~0U);
1942 }
1943
1944 Record *Op = N->getOperator();
1945 if (Op->isSubClassOf("Instruction")) {
1946 // Determine operand emission order. Complex pattern first.
1947 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
1948 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
1949 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1950 TreePatternNode *Child = N->getChild(i);
1951 if (i == 0) {
1952 EmitOrder.push_back(std::make_pair(i, Child));
1953 OI = EmitOrder.begin();
1954 } else if (NodeIsComplexPattern(Child)) {
1955 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
1956 } else {
1957 EmitOrder.push_back(std::make_pair(i, Child));
1958 }
1959 }
1960
1961 // Emit all of the operands.
1962 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
1963 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
1964 unsigned OpOrder = EmitOrder[i].first;
1965 TreePatternNode *Child = EmitOrder[i].second;
1966 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
1967 NumTemps[OpOrder] = NumTemp;
1968 }
1969
1970 // List all the operands in the right order.
1971 std::vector<unsigned> Ops;
1972 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
1973 for (unsigned j = 0; j < NumTemps[i].first; j++)
1974 Ops.push_back(NumTemps[i].second + j);
1975 }
1976
1977 CodeGenInstruction &II =
1978 ISE.getTargetInfo().getInstruction(Op->getName());
1979
1980 // Emit all the chain and CopyToReg stuff.
1981 if (II.hasCtrlDep)
1982 OS << " SDOperand Chain = Select(" << InnerChain << ");\n";
1983 EmitCopyToRegs(LHS, "N", II.hasCtrlDep);
1984
1985 const DAGInstruction &Inst = ISE.getInstruction(Op);
1986 unsigned NumResults = Inst.getNumResults();
1987 unsigned ResNo = TmpNo++;
1988 if (!isRoot) {
1989 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1990 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1991 << getEnumName(N->getType());
1992 unsigned LastOp = 0;
1993 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1994 LastOp = Ops[i];
1995 OS << ", Tmp" << LastOp;
1996 }
1997 OS << ");\n";
1998 if (II.hasCtrlDep) {
1999 // Must have at least one result
2000 OS << " Chain = Tmp" << LastOp << ".getValue("
2001 << NumResults << ");\n";
2002 }
2003 } else if (II.hasCtrlDep) {
2004 OS << " SDOperand Result = ";
2005 OS << "CurDAG->getTargetNode("
2006 << II.Namespace << "::" << II.TheDef->getName();
2007 if (NumResults > 0)
2008 OS << ", MVT::" << getEnumName(N->getType()); // TODO: multiple results?
2009 OS << ", MVT::Other";
2010 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2011 OS << ", Tmp" << Ops[i];
2012 OS << ", Chain";
2013 if (InFlag)
2014 OS << ", InFlag";
2015 OS << ");\n";
2016 if (NumResults != 0) {
2017 OS << " CodeGenMap[N] = Result;\n";
2018 }
2019 OS << " Chain ";
2020 if (NodeHasChain(LHS, ISE))
2021 OS << "= CodeGenMap[N.getValue(1)] ";
2022 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2023 OS << "= CodeGenMap[" << FoldedChains[j] << ".getValue(1)] ";
2024 OS << "= Result.getValue(1);\n";
2025 if (NumResults == 0)
2026 OS << " return Chain;\n";
2027 else
2028 OS << " return (N.ResNo) ? Chain : Result.getValue(0);\n";
2029 } else {
2030 // If this instruction is the root, and if there is only one use of it,
2031 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2032 OS << " if (N.Val->hasOneUse()) {\n";
2033 OS << " return CurDAG->SelectNodeTo(N.Val, "
2034 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
2035 << getEnumName(N->getType());
2036 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2037 OS << ", Tmp" << Ops[i];
2038 if (InFlag)
2039 OS << ", InFlag";
2040 OS << ");\n";
2041 OS << " } else {\n";
2042 OS << " return CodeGenMap[N] = CurDAG->getTargetNode("
2043 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
2044 << getEnumName(N->getType());
2045 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2046 OS << ", Tmp" << Ops[i];
2047 if (InFlag)
2048 OS << ", InFlag";
2049 OS << ");\n";
2050 OS << " }\n";
2051 }
2052 return std::make_pair(1, ResNo);
2053 } else if (Op->isSubClassOf("SDNodeXForm")) {
2054 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2055 unsigned OpVal = EmitResultCode(N->getChild(0))
2056 .second;
2057
2058 unsigned ResNo = TmpNo++;
2059 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
2060 << "(Tmp" << OpVal << ".Val);\n";
2061 if (isRoot) {
2062 OS << " CodeGenMap[N] = Tmp" << ResNo << ";\n";
2063 OS << " return Tmp" << ResNo << ";\n";
2064 }
2065 return std::make_pair(1, ResNo);
2066 } else {
2067 N->dump();
2068 assert(0 && "Unknown node in result pattern!");
2069 return std::make_pair(1, ~0U);
2070 }
2071 }
2072
2073 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat' and
2074 /// add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2075 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2076 /// for, this returns true otherwise false if Pat has all types.
2077 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2078 const std::string &Prefix) {
2079 // Did we find one?
2080 if (!Pat->hasTypeSet()) {
2081 // Move a type over from 'other' to 'pat'.
2082 Pat->setType(Other->getType());
2083 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
2084 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
2085 return true;
2086 } else if (Pat->isLeaf()) {
2087 if (NodeIsComplexPattern(Pat))
2088 OS << " if (" << Prefix << ".Val->getValueType(0) != MVT::"
2089 << getName(Pat->getType()) << ") goto P" << PatternNo << "Fail;\n";
2090 return false;
2091 }
2092
2093 unsigned OpNo = (unsigned) NodeHasChain(Pat, ISE);
2094 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2095 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2096 Prefix + utostr(OpNo)))
2097 return true;
2098 return false;
2099 }
2100
2101private:
2102 /// EmitCopyToRegs - Emit the flag operands for the DAG that is
2103 /// being built.
2104 void EmitCopyToRegs(TreePatternNode *N, const std::string &RootName,
2105 bool HasCtrlDep) {
2106 const CodeGenTarget &T = ISE.getTargetInfo();
2107 unsigned OpNo = (unsigned) NodeHasChain(N, ISE);
2108 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2109 TreePatternNode *Child = N->getChild(i);
2110 if (!Child->isLeaf()) {
2111 EmitCopyToRegs(Child, RootName + utostr(OpNo), HasCtrlDep);
2112 } else {
2113 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2114 Record *RR = DI->getDef();
2115 if (RR->isSubClassOf("Register")) {
2116 MVT::ValueType RVT = getRegisterValueType(RR, T);
2117 if (HasCtrlDep) {
2118 OS << " SDOperand " << RootName << "CR" << i << ";\n";
2119 OS << " " << RootName << "CR" << i
2120 << " = CurDAG->getCopyToReg(Chain, CurDAG->getRegister("
2121 << ISE.getQualifiedName(RR) << ", MVT::"
2122 << getEnumName(RVT) << ")"
2123 << ", Select(" << RootName << OpNo << "), InFlag);\n";
2124 OS << " Chain = " << RootName << "CR" << i
2125 << ".getValue(0);\n";
2126 OS << " InFlag = " << RootName << "CR" << i
2127 << ".getValue(1);\n";
2128 } else {
2129 OS << " InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode()"
2130 << ", CurDAG->getRegister(" << ISE.getQualifiedName(RR)
2131 << ", MVT::" << getEnumName(RVT) << ")"
2132 << ", Select(" << RootName << OpNo
2133 << "), InFlag).getValue(1);\n";
2134 }
2135 }
2136 }
2137 }
2138 }
2139 }
2140};
2141
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002142/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2143/// stream to match the pattern, and generate the code for the match if it
2144/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00002145void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
2146 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002147 static unsigned PatternCount = 0;
2148 unsigned PatternNo = PatternCount++;
2149 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002150 Pattern.first->print(OS);
Chris Lattner05814af2005-09-28 17:57:56 +00002151 OS << "\n // Emits: ";
2152 Pattern.second->print(OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00002153 OS << "\n";
Evan Cheng0fc71982005-12-08 02:00:36 +00002154 OS << " // Pattern complexity = " << getPatternSize(Pattern.first, *this)
Chris Lattner05814af2005-09-28 17:57:56 +00002155 << " cost = " << getResultPatternCost(Pattern.second) << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002156
Evan Chengb915f312005-12-09 22:45:35 +00002157 PatternCodeEmitter Emitter(*this, Pattern.first, PatternNo, OS);
2158
Chris Lattner8fc35682005-09-23 23:16:51 +00002159 // Emit the matcher, capturing named arguments in VariableMap.
Evan Chengb915f312005-12-09 22:45:35 +00002160 Emitter.EmitMatchCode(Pattern.first, "N", true /*the root*/);
2161
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002162 // TP - Get *SOME* tree pattern, we don't care which.
2163 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002164
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002165 // At this point, we know that we structurally match the pattern, but the
2166 // types of the nodes may not match. Figure out the fewest number of type
2167 // comparisons we need to emit. For example, if there is only one integer
2168 // type supported by a target, there should be no type comparisons at all for
2169 // integer patterns!
2170 //
2171 // To figure out the fewest number of type checks needed, clone the pattern,
2172 // remove the types, then perform type inference on the pattern as a whole.
2173 // If there are unresolved types, emit an explicit check for those types,
2174 // apply the type to the tree, then rerun type inference. Iterate until all
2175 // types are resolved.
2176 //
2177 TreePatternNode *Pat = Pattern.first->clone();
2178 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002179
2180 do {
2181 // Resolve/propagate as many types as possible.
2182 try {
2183 bool MadeChange = true;
2184 while (MadeChange)
2185 MadeChange = Pat->ApplyTypeConstraints(TP,true/*Ignore reg constraints*/);
2186 } catch (...) {
2187 assert(0 && "Error: could not find consistent types for something we"
2188 " already decided was ok!");
2189 abort();
2190 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002191
Chris Lattner7e82f132005-10-15 21:34:21 +00002192 // Insert a check for an unresolved type and add it to the tree. If we find
2193 // an unresolved type to add a check for, this returns true and we iterate,
2194 // otherwise we are done.
Evan Chengb915f312005-12-09 22:45:35 +00002195 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.first, "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002196
Evan Chengb915f312005-12-09 22:45:35 +00002197 Emitter.EmitResultCode(Pattern.second, true /*the root*/);
2198
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002199 delete Pat;
2200
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002201 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002202}
2203
Chris Lattner37481472005-09-26 21:59:35 +00002204
2205namespace {
2206 /// CompareByRecordName - An ordering predicate that implements less-than by
2207 /// comparing the names records.
2208 struct CompareByRecordName {
2209 bool operator()(const Record *LHS, const Record *RHS) const {
2210 // Sort by name first.
2211 if (LHS->getName() < RHS->getName()) return true;
2212 // If both names are equal, sort by pointer.
2213 return LHS->getName() == RHS->getName() && LHS < RHS;
2214 }
2215 };
2216}
2217
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002218void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002219 std::string InstNS = Target.inst_begin()->second.Namespace;
2220 if (!InstNS.empty()) InstNS += "::";
2221
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002222 // Emit boilerplate.
2223 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002224 << "SDOperand SelectCode(SDOperand N) {\n"
2225 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002226 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2227 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002228 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00002229 << " if (!N.Val->hasOneUse()) {\n"
2230 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
2231 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
2232 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002233 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002234 << " default: break;\n"
2235 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002236 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002237 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002238 << " case ISD::AssertZext: {\n"
2239 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2240 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2241 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002242 << " }\n"
2243 << " case ISD::TokenFactor:\n"
2244 << " if (N.getNumOperands() == 2) {\n"
2245 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2246 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2247 << " return CodeGenMap[N] =\n"
2248 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2249 << " } else {\n"
2250 << " std::vector<SDOperand> Ops;\n"
2251 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2252 << " Ops.push_back(Select(N.getOperand(i)));\n"
2253 << " return CodeGenMap[N] = \n"
2254 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2255 << " }\n"
2256 << " case ISD::CopyFromReg: {\n"
2257 << " SDOperand Chain = Select(N.getOperand(0));\n"
2258 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2259 << " SDOperand New = CurDAG->getCopyFromReg(Chain,\n"
2260 << " cast<RegisterSDNode>(N.getOperand(1))->getReg(),\n"
2261 << " N.Val->getValueType(0));\n"
2262 << " return New.getValue(N.ResNo);\n"
2263 << " }\n"
2264 << " case ISD::CopyToReg: {\n"
2265 << " SDOperand Chain = Select(N.getOperand(0));\n"
2266 << " SDOperand Reg = N.getOperand(1);\n"
2267 << " SDOperand Val = Select(N.getOperand(2));\n"
2268 << " return CodeGenMap[N] = \n"
2269 << " CurDAG->getNode(ISD::CopyToReg, MVT::Other,\n"
2270 << " Chain, Reg, Val);\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002271 << " }\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002272
Chris Lattner81303322005-09-23 19:36:15 +00002273 // Group the patterns by their top-level opcodes.
Chris Lattner37481472005-09-26 21:59:35 +00002274 std::map<Record*, std::vector<PatternToMatch*>,
2275 CompareByRecordName> PatternsByOpcode;
Evan Cheng0fc71982005-12-08 02:00:36 +00002276 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2277 TreePatternNode *Node = PatternsToMatch[i].first;
2278 if (!Node->isLeaf()) {
2279 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
Chris Lattner0614b622005-11-02 06:49:14 +00002280 } else {
Evan Cheng0fc71982005-12-08 02:00:36 +00002281 const ComplexPattern *CP;
Chris Lattner0614b622005-11-02 06:49:14 +00002282 if (IntInit *II =
Evan Cheng0fc71982005-12-08 02:00:36 +00002283 dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner0614b622005-11-02 06:49:14 +00002284 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
Evan Cheng0fc71982005-12-08 02:00:36 +00002285 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
Evan Cheng3aa39f42005-12-08 02:14:08 +00002286 std::vector<Record*> OpNodes = CP->getRootNodes();
Evan Cheng0fc71982005-12-08 02:00:36 +00002287 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
2288 PatternsByOpcode[OpNodes[j]].insert(PatternsByOpcode[OpNodes[j]].begin(),
2289 &PatternsToMatch[i]);
2290 }
Chris Lattner0614b622005-11-02 06:49:14 +00002291 } else {
Evan Cheng76021f02005-11-29 18:44:58 +00002292 std::cerr << "Unrecognized opcode '";
Evan Cheng0fc71982005-12-08 02:00:36 +00002293 Node->dump();
Evan Cheng76021f02005-11-29 18:44:58 +00002294 std::cerr << "' on tree pattern '";
2295 std::cerr << PatternsToMatch[i].second->getOperator()->getName();
2296 std::cerr << "'!\n";
2297 exit(1);
Chris Lattner0614b622005-11-02 06:49:14 +00002298 }
2299 }
Evan Cheng0fc71982005-12-08 02:00:36 +00002300 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002301
Chris Lattner3f7e9142005-09-23 20:52:47 +00002302 // Loop over all of the case statements.
Chris Lattner37481472005-09-26 21:59:35 +00002303 for (std::map<Record*, std::vector<PatternToMatch*>,
2304 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2305 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00002306 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
2307 std::vector<PatternToMatch*> &Patterns = PBOI->second;
2308
2309 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00002310
2311 // We want to emit all of the matching code now. However, we want to emit
2312 // the matches in order of minimal cost. Sort the patterns so the least
2313 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002314 std::stable_sort(Patterns.begin(), Patterns.end(),
Evan Cheng0fc71982005-12-08 02:00:36 +00002315 PatternSortingPredicate(*this));
Chris Lattner81303322005-09-23 19:36:15 +00002316
Chris Lattner3f7e9142005-09-23 20:52:47 +00002317 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2318 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002319 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00002320 }
2321
2322
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002323 OS << " } // end of big switch.\n\n"
2324 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002325 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002326 << " std::cerr << '\\n';\n"
2327 << " abort();\n"
2328 << "}\n";
2329}
2330
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002331void DAGISelEmitter::run(std::ostream &OS) {
2332 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
2333 " target", OS);
2334
Chris Lattner1f39e292005-09-14 00:09:24 +00002335 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2336 << "// *** instruction selector class. These functions are really "
2337 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002338
Chris Lattner296dfe32005-09-24 00:50:51 +00002339 OS << "// Instance var to keep track of multiply used nodes that have \n"
2340 << "// already been selected.\n"
2341 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
2342
Chris Lattnerca559d02005-09-08 21:03:01 +00002343 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00002344 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00002345 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002346 ParsePatternFragments(OS);
2347 ParseInstructions();
2348 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00002349
Chris Lattnere97603f2005-09-28 19:27:25 +00002350 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00002351 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00002352 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00002353
Chris Lattnere46e17b2005-09-29 19:28:10 +00002354
2355 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
2356 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2357 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
2358 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
2359 std::cerr << "\n";
2360 });
2361
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002362 // At this point, we have full information about the 'Patterns' we need to
2363 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002364 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002365 EmitInstructionSelector(OS);
2366
2367 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
2368 E = PatternFragments.end(); I != E; ++I)
2369 delete I->second;
2370 PatternFragments.clear();
2371
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002372 Instructions.clear();
2373}