blob: 5221fe025bfc9fe2eea3ba8bde4bf253db43b072 [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"
Chris Lattnerbe8e7212006-10-11 03:35:34 +000018#include "llvm/Support/MathExtras.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000019#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000020#include <set>
21using namespace llvm;
22
Chris Lattnerca559d02005-09-08 21:03:01 +000023//===----------------------------------------------------------------------===//
Chris Lattner3c7e18d2005-10-14 06:12:03 +000024// Helpers for working with extended types.
25
26/// FilterVTs - Filter a list of VT's according to a predicate.
27///
28template<typename T>
29static std::vector<MVT::ValueType>
30FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
31 std::vector<MVT::ValueType> Result;
32 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
33 if (Filter(InVTs[i]))
34 Result.push_back(InVTs[i]);
35 return Result;
36}
37
Nate Begemanb73628b2005-12-30 00:12:56 +000038template<typename T>
39static std::vector<unsigned char>
40FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
41 std::vector<unsigned char> Result;
42 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
43 if (Filter((MVT::ValueType)InVTs[i]))
44 Result.push_back(InVTs[i]);
45 return Result;
Chris Lattner3c7e18d2005-10-14 06:12:03 +000046}
47
Nate Begemanb73628b2005-12-30 00:12:56 +000048static std::vector<unsigned char>
49ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
50 std::vector<unsigned char> Result;
51 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
52 Result.push_back(InVTs[i]);
53 return Result;
54}
55
56static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
57 const std::vector<unsigned char> &RHS) {
58 if (LHS.size() > RHS.size()) return false;
59 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
Duraid Madinad47ae092005-12-30 16:41:48 +000060 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
Nate Begemanb73628b2005-12-30 00:12:56 +000061 return false;
62 return true;
63}
64
65/// isExtIntegerVT - Return true if the specified extended value type vector
66/// contains isInt or an integer value type.
Chris Lattner697f8842006-03-20 05:39:48 +000067static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000068 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
69 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
70}
71
72/// isExtFloatingPointVT - Return true if the specified extended value type
73/// vector contains isFP or a FP value type.
Chris Lattner697f8842006-03-20 05:39:48 +000074static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000075 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
Chris Lattner488580c2006-01-28 19:06:51 +000076 return EVTs[0] == MVT::isFP ||
77 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
Chris Lattner3c7e18d2005-10-14 06:12:03 +000078}
79
80//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000081// SDTypeConstraint implementation
82//
83
84SDTypeConstraint::SDTypeConstraint(Record *R) {
85 OperandNo = R->getValueAsInt("OperandNum");
86
87 if (R->isSubClassOf("SDTCisVT")) {
88 ConstraintType = SDTCisVT;
89 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattner5b21be72005-12-09 22:57:42 +000090 } else if (R->isSubClassOf("SDTCisPtrTy")) {
91 ConstraintType = SDTCisPtrTy;
Chris Lattner33c92e92005-09-08 21:27:15 +000092 } else if (R->isSubClassOf("SDTCisInt")) {
93 ConstraintType = SDTCisInt;
94 } else if (R->isSubClassOf("SDTCisFP")) {
95 ConstraintType = SDTCisFP;
96 } else if (R->isSubClassOf("SDTCisSameAs")) {
97 ConstraintType = SDTCisSameAs;
98 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
99 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
100 ConstraintType = SDTCisVTSmallerThanOp;
101 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
102 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +0000103 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
104 ConstraintType = SDTCisOpSmallerThanOp;
105 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
106 R->getValueAsInt("BigOperandNum");
Chris Lattner697f8842006-03-20 05:39:48 +0000107 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
108 ConstraintType = SDTCisIntVectorOfSameSize;
109 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
110 R->getValueAsInt("OtherOpNum");
Chris Lattner33c92e92005-09-08 21:27:15 +0000111 } else {
112 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
113 exit(1);
114 }
115}
116
Chris Lattner32707602005-09-08 23:22:48 +0000117/// getOperandNum - Return the node corresponding to operand #OpNo in tree
118/// N, which has NumResults results.
119TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
120 TreePatternNode *N,
121 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000122 assert(NumResults <= 1 &&
123 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000124
Evan Cheng50c997e2006-06-13 21:47:27 +0000125 if (OpNo >= (NumResults + N->getNumChildren())) {
126 std::cerr << "Invalid operand number " << OpNo << " ";
127 N->dump();
128 std::cerr << '\n';
129 exit(1);
130 }
131
Chris Lattner32707602005-09-08 23:22:48 +0000132 if (OpNo < NumResults)
133 return N; // FIXME: need value #
134 else
135 return N->getChild(OpNo-NumResults);
136}
137
138/// ApplyTypeConstraint - Given a node in a pattern, apply this type
139/// constraint to the nodes operands. This returns true if it makes a
140/// change, false otherwise. If a type contradiction is found, throw an
141/// exception.
142bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
143 const SDNodeInfo &NodeInfo,
144 TreePattern &TP) const {
145 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000146 assert(NumResults <= 1 &&
147 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000148
Chris Lattner8f60d542006-06-16 18:25:06 +0000149 // Check that the number of operands is sane. Negative operands -> varargs.
Chris Lattner32707602005-09-08 23:22:48 +0000150 if (NodeInfo.getNumOperands() >= 0) {
151 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
152 TP.error(N->getOperator()->getName() + " node requires exactly " +
153 itostr(NodeInfo.getNumOperands()) + " operands!");
154 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000155
156 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000157
158 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
159
160 switch (ConstraintType) {
161 default: assert(0 && "Unknown constraint type!");
162 case SDTCisVT:
163 // Operand must be a particular type.
164 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000165 case SDTCisPtrTy: {
166 // Operand must be same as target pointer type.
Evan Cheng2618d072006-05-17 20:37:59 +0000167 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000168 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000169 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000170 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000171 std::vector<MVT::ValueType> IntVTs =
172 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000173
174 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000175 if (IntVTs.size() == 1)
176 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000177 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000178 }
179 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000180 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000181 std::vector<MVT::ValueType> FPVTs =
182 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000183
184 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000185 if (FPVTs.size() == 1)
186 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000187 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000188 }
Chris Lattner32707602005-09-08 23:22:48 +0000189 case SDTCisSameAs: {
190 TreePatternNode *OtherNode =
191 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000192 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
193 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000194 }
195 case SDTCisVTSmallerThanOp: {
196 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
197 // have an integer type that is smaller than the VT.
198 if (!NodeToApply->isLeaf() ||
199 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
200 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
201 ->isSubClassOf("ValueType"))
202 TP.error(N->getOperator()->getName() + " expects a VT operand!");
203 MVT::ValueType VT =
204 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
205 if (!MVT::isInteger(VT))
206 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
207
208 TreePatternNode *OtherNode =
209 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000210
211 // It must be integer.
212 bool MadeChange = false;
213 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
214
Nate Begemanb73628b2005-12-30 00:12:56 +0000215 // This code only handles nodes that have one type set. Assert here so
216 // that we can change this if we ever need to deal with multiple value
217 // types at this point.
218 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
219 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000220 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
221 return false;
222 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000223 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000224 TreePatternNode *BigOperand =
225 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
226
227 // Both operands must be integer or FP, but we don't care which.
228 bool MadeChange = false;
229
Nate Begemanb73628b2005-12-30 00:12:56 +0000230 // This code does not currently handle nodes which have multiple types,
231 // where some types are integer, and some are fp. Assert that this is not
232 // the case.
233 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
234 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
235 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
236 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
237 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
238 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000239 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000240 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000241 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000242 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000243 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000244 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000245 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
246
247 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
248
Nate Begemanb73628b2005-12-30 00:12:56 +0000249 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000250 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000251 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000252 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
253 } else {
254 VTs.clear();
255 }
256
257 switch (VTs.size()) {
258 default: // Too many VT's to pick from.
259 case 0: break; // No info yet.
260 case 1:
261 // Only one VT of this flavor. Cannot ever satisify the constraints.
262 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
263 case 2:
264 // If we have exactly two possible types, the little operand must be the
265 // small one, the big operand should be the big one. Common with
266 // float/double for example.
267 assert(VTs[0] < VTs[1] && "Should be sorted!");
268 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
269 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
270 break;
271 }
272 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000273 }
Chris Lattner697f8842006-03-20 05:39:48 +0000274 case SDTCisIntVectorOfSameSize: {
275 TreePatternNode *OtherOperand =
276 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
277 N, NumResults);
278 if (OtherOperand->hasTypeSet()) {
279 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
280 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
281 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
282 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
283 return NodeToApply->UpdateNodeType(IVT, TP);
284 }
285 return false;
286 }
Chris Lattner32707602005-09-08 23:22:48 +0000287 }
288 return false;
289}
290
291
Chris Lattner33c92e92005-09-08 21:27:15 +0000292//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000293// SDNodeInfo implementation
294//
295SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
296 EnumName = R->getValueAsString("Opcode");
297 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000298 Record *TypeProfile = R->getValueAsDef("TypeProfile");
299 NumResults = TypeProfile->getValueAsInt("NumResults");
300 NumOperands = TypeProfile->getValueAsInt("NumOperands");
301
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000302 // Parse the properties.
303 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000304 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000305 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
306 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000307 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000308 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000309 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000310 } else if (PropList[i]->getName() == "SDNPHasChain") {
311 Properties |= 1 << SDNPHasChain;
Evan Cheng51fecc82006-01-09 18:27:06 +0000312 } else if (PropList[i]->getName() == "SDNPOutFlag") {
313 Properties |= 1 << SDNPOutFlag;
314 } else if (PropList[i]->getName() == "SDNPInFlag") {
315 Properties |= 1 << SDNPInFlag;
316 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
317 Properties |= 1 << SDNPOptInFlag;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000318 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000319 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000320 << "' on node '" << R->getName() << "'!\n";
321 exit(1);
322 }
323 }
324
325
Chris Lattner33c92e92005-09-08 21:27:15 +0000326 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000327 std::vector<Record*> ConstraintList =
328 TypeProfile->getValueAsListOfDefs("Constraints");
329 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000330}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000331
332//===----------------------------------------------------------------------===//
333// TreePatternNode implementation
334//
335
336TreePatternNode::~TreePatternNode() {
337#if 0 // FIXME: implement refcounted tree nodes!
338 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
339 delete getChild(i);
340#endif
341}
342
Chris Lattner32707602005-09-08 23:22:48 +0000343/// UpdateNodeType - Set the node type of N to VT if VT contains
344/// information. If N already contains a conflicting type, then throw an
345/// exception. This returns true if any information was updated.
346///
Nate Begemanb73628b2005-12-30 00:12:56 +0000347bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
348 TreePattern &TP) {
349 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
350
351 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
352 return false;
353 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
354 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000355 return true;
356 }
Evan Cheng2618d072006-05-17 20:37:59 +0000357
358 if (getExtTypeNum(0) == MVT::iPTR) {
359 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
360 return false;
361 if (isExtIntegerInVTs(ExtVTs)) {
362 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
363 if (FVTs.size()) {
364 setTypes(ExtVTs);
365 return true;
366 }
367 }
368 }
Chris Lattner32707602005-09-08 23:22:48 +0000369
Nate Begemanb73628b2005-12-30 00:12:56 +0000370 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
371 assert(hasTypeSet() && "should be handled above!");
372 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
373 if (getExtTypes() == FVTs)
374 return false;
375 setTypes(FVTs);
376 return true;
377 }
Evan Cheng2618d072006-05-17 20:37:59 +0000378 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
379 //assert(hasTypeSet() && "should be handled above!");
380 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
381 if (getExtTypes() == FVTs)
382 return false;
383 if (FVTs.size()) {
384 setTypes(FVTs);
385 return true;
386 }
387 }
Nate Begemanb73628b2005-12-30 00:12:56 +0000388 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
389 assert(hasTypeSet() && "should be handled above!");
Chris Lattner488580c2006-01-28 19:06:51 +0000390 std::vector<unsigned char> FVTs =
391 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
Nate Begemanb73628b2005-12-30 00:12:56 +0000392 if (getExtTypes() == FVTs)
393 return false;
394 setTypes(FVTs);
395 return true;
396 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000397
398 // If we know this is an int or fp type, and we are told it is a specific one,
399 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000400 //
401 // Similarly, we should probably set the type here to the intersection of
402 // {isInt|isFP} and ExtVTs
403 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
404 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
405 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000406 return true;
Evan Cheng2618d072006-05-17 20:37:59 +0000407 }
408 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
409 setTypes(ExtVTs);
410 return true;
411 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000412
Chris Lattner1531f202005-10-26 16:59:37 +0000413 if (isLeaf()) {
414 dump();
Evan Chengbcecf332005-12-17 01:19:28 +0000415 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000416 TP.error("Type inference contradiction found in node!");
417 } else {
418 TP.error("Type inference contradiction found in node " +
419 getOperator()->getName() + "!");
420 }
Chris Lattner32707602005-09-08 23:22:48 +0000421 return true; // unreachable
422}
423
424
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000425void TreePatternNode::print(std::ostream &OS) const {
426 if (isLeaf()) {
427 OS << *getLeafValue();
428 } else {
429 OS << "(" << getOperator()->getName();
430 }
431
Nate Begemanb73628b2005-12-30 00:12:56 +0000432 // FIXME: At some point we should handle printing all the value types for
433 // nodes that are multiply typed.
434 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000435 case MVT::Other: OS << ":Other"; break;
436 case MVT::isInt: OS << ":isInt"; break;
437 case MVT::isFP : OS << ":isFP"; break;
438 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Evan Cheng2618d072006-05-17 20:37:59 +0000439 case MVT::iPTR: OS << ":iPTR"; break;
Chris Lattner02cdb372006-06-20 00:56:37 +0000440 default: {
441 std::string VTName = llvm::getName(getTypeNum(0));
442 // Strip off MVT:: prefix if present.
443 if (VTName.substr(0,5) == "MVT::")
444 VTName = VTName.substr(5);
445 OS << ":" << VTName;
446 break;
447 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000448 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000449
450 if (!isLeaf()) {
451 if (getNumChildren() != 0) {
452 OS << " ";
453 getChild(0)->print(OS);
454 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
455 OS << ", ";
456 getChild(i)->print(OS);
457 }
458 }
459 OS << ")";
460 }
461
462 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000463 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000464 if (TransformFn)
465 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000466 if (!getName().empty())
467 OS << ":$" << getName();
468
469}
470void TreePatternNode::dump() const {
471 print(std::cerr);
472}
473
Chris Lattnere46e17b2005-09-29 19:28:10 +0000474/// isIsomorphicTo - Return true if this node is recursively isomorphic to
475/// the specified node. For this comparison, all of the state of the node
476/// is considered, except for the assigned name. Nodes with differing names
477/// that are otherwise identical are considered isomorphic.
478bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
479 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000480 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000481 getPredicateFn() != N->getPredicateFn() ||
482 getTransformFn() != N->getTransformFn())
483 return false;
484
485 if (isLeaf()) {
486 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
487 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
488 return DI->getDef() == NDI->getDef();
489 return getLeafValue() == N->getLeafValue();
490 }
491
492 if (N->getOperator() != getOperator() ||
493 N->getNumChildren() != getNumChildren()) return false;
494 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
495 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
496 return false;
497 return true;
498}
499
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000500/// clone - Make a copy of this tree and all of its children.
501///
502TreePatternNode *TreePatternNode::clone() const {
503 TreePatternNode *New;
504 if (isLeaf()) {
505 New = new TreePatternNode(getLeafValue());
506 } else {
507 std::vector<TreePatternNode*> CChildren;
508 CChildren.reserve(Children.size());
509 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
510 CChildren.push_back(getChild(i)->clone());
511 New = new TreePatternNode(getOperator(), CChildren);
512 }
513 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000514 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000515 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000516 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000517 return New;
518}
519
Chris Lattner32707602005-09-08 23:22:48 +0000520/// SubstituteFormalArguments - Replace the formal arguments in this tree
521/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000522void TreePatternNode::
523SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
524 if (isLeaf()) return;
525
526 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
527 TreePatternNode *Child = getChild(i);
528 if (Child->isLeaf()) {
529 Init *Val = Child->getLeafValue();
530 if (dynamic_cast<DefInit*>(Val) &&
531 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
532 // We found a use of a formal argument, replace it with its value.
533 Child = ArgMap[Child->getName()];
534 assert(Child && "Couldn't find formal argument!");
535 setChild(i, Child);
536 }
537 } else {
538 getChild(i)->SubstituteFormalArguments(ArgMap);
539 }
540 }
541}
542
543
544/// InlinePatternFragments - If this pattern refers to any pattern
545/// fragments, inline them into place, giving us a pattern without any
546/// PatFrag references.
547TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
548 if (isLeaf()) return this; // nothing to do.
549 Record *Op = getOperator();
550
551 if (!Op->isSubClassOf("PatFrag")) {
552 // Just recursively inline children nodes.
553 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
554 setChild(i, getChild(i)->InlinePatternFragments(TP));
555 return this;
556 }
557
558 // Otherwise, we found a reference to a fragment. First, look up its
559 // TreePattern record.
560 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
561
562 // Verify that we are passing the right number of operands.
563 if (Frag->getNumArgs() != Children.size())
564 TP.error("'" + Op->getName() + "' fragment requires " +
565 utostr(Frag->getNumArgs()) + " operands!");
566
Chris Lattner37937092005-09-09 01:15:01 +0000567 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000568
569 // Resolve formal arguments to their actual value.
570 if (Frag->getNumArgs()) {
571 // Compute the map of formal to actual arguments.
572 std::map<std::string, TreePatternNode*> ArgMap;
573 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
574 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
575
576 FragTree->SubstituteFormalArguments(ArgMap);
577 }
578
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000579 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000580 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000581
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000582 // Get a new copy of this fragment to stitch into here.
583 //delete this; // FIXME: implement refcounting!
584 return FragTree;
585}
586
Chris Lattner52793e22006-04-06 20:19:52 +0000587/// getImplicitType - Check to see if the specified record has an implicit
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000588/// type which should be applied to it. This infer the type of register
589/// references from the register file information, for example.
590///
Chris Lattner52793e22006-04-06 20:19:52 +0000591static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000592 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000593 // Some common return values
594 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
595 std::vector<unsigned char> Other(1, MVT::Other);
596
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000597 // Check to see if this is a register or a register class...
598 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000599 if (NotRegisters)
600 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000601 const CodeGenRegisterClass &RC =
602 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000603 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000604 } else if (R->isSubClassOf("PatFrag")) {
605 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000606 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000607 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000608 if (NotRegisters)
609 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000610 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
Evan Cheng44a65fa2006-05-16 07:05:30 +0000611 return T.getRegisterVTs(R);
Chris Lattner1531f202005-10-26 16:59:37 +0000612 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
613 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000614 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000615 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000616 if (NotRegisters)
617 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000618 std::vector<unsigned char>
619 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
620 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000621 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000622 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000623 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000624 }
625
626 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000627 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000628}
629
Chris Lattner32707602005-09-08 23:22:48 +0000630/// ApplyTypeConstraints - Apply all of the type constraints relevent to
631/// this node and its children in the tree. This returns true if it makes a
632/// change, false otherwise. If a type contradiction is found, throw an
633/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000634bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000635 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000636 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000637 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000638 // If it's a regclass or something else known, include the type.
Chris Lattner52793e22006-04-06 20:19:52 +0000639 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000640 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
641 // Int inits are always integers. :)
642 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
643
644 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000645 // At some point, it may make sense for this tree pattern to have
646 // multiple types. Assert here that it does not, so we revisit this
647 // code when appropriate.
Evan Cheng2618d072006-05-17 20:37:59 +0000648 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Evan Cheng44a65fa2006-05-16 07:05:30 +0000649 MVT::ValueType VT = getTypeNum(0);
650 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
651 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000652
Evan Cheng2618d072006-05-17 20:37:59 +0000653 VT = getTypeNum(0);
654 if (VT != MVT::iPTR) {
655 unsigned Size = MVT::getSizeInBits(VT);
656 // Make sure that the value is representable for this type.
657 if (Size < 32) {
658 int Val = (II->getValue() << (32-Size)) >> (32-Size);
659 if (Val != II->getValue())
660 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
661 "' is out of range for type '" +
662 getEnumName(getTypeNum(0)) + "'!");
663 }
Chris Lattner465c7372005-11-03 05:46:11 +0000664 }
665 }
666
667 return MadeChange;
668 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000669 return false;
670 }
Chris Lattner32707602005-09-08 23:22:48 +0000671
672 // special handling for set, which isn't really an SDNode.
673 if (getOperator()->getName() == "set") {
674 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000675 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
676 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000677
678 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000679 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
680 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000681 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
682 return MadeChange;
Chris Lattner5a1df382006-03-24 23:10:39 +0000683 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
684 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
685 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
686 unsigned IID =
687 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
688 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
689 bool MadeChange = false;
690
691 // Apply the result type to the node.
692 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
693
694 if (getNumChildren() != Int.ArgVTs.size())
Chris Lattner2c4e65d2006-03-27 22:21:18 +0000695 TP.error("Intrinsic '" + Int.Name + "' expects " +
Chris Lattner5a1df382006-03-24 23:10:39 +0000696 utostr(Int.ArgVTs.size()-1) + " operands, not " +
697 utostr(getNumChildren()-1) + " operands!");
698
699 // Apply type info to the intrinsic ID.
Evan Cheng2618d072006-05-17 20:37:59 +0000700 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5a1df382006-03-24 23:10:39 +0000701
702 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
703 MVT::ValueType OpVT = Int.ArgVTs[i];
704 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
705 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
706 }
707 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000708 } else if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000709 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
Chris Lattnerabbb6052005-09-15 21:42:00 +0000710
711 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
712 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000713 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000714 // Branch, etc. do not produce results and top-level forms in instr pattern
715 // must have void types.
716 if (NI.getNumResults() == 0)
717 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner91ded082006-04-06 20:36:51 +0000718
719 // If this is a vector_shuffle operation, apply types to the build_vector
720 // operation. The types of the integers don't matter, but this ensures they
721 // won't get checked.
722 if (getOperator()->getName() == "vector_shuffle" &&
723 getChild(2)->getOperator()->getName() == "build_vector") {
724 TreePatternNode *BV = getChild(2);
725 const std::vector<MVT::ValueType> &LegalVTs
726 = ISE.getTargetInfo().getLegalValueTypes();
727 MVT::ValueType LegalIntVT = MVT::Other;
728 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
729 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
730 LegalIntVT = LegalVTs[i];
731 break;
732 }
733 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
734
735 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
736 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
737 }
Chris Lattnerabbb6052005-09-15 21:42:00 +0000738 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000739 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000740 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000741 bool MadeChange = false;
742 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000743
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000744 assert(NumResults <= 1 &&
745 "Only supports zero or one result instrs!");
Evan Chengeb1f40d2006-07-20 23:36:20 +0000746
747 CodeGenInstruction &InstInfo =
748 ISE.getTargetInfo().getInstruction(getOperator()->getName());
Chris Lattnera28aec12005-09-15 22:23:50 +0000749 // Apply the result type to the node
Evan Chengeb1f40d2006-07-20 23:36:20 +0000750 if (NumResults == 0 || InstInfo.noResults) { // FIXME: temporary hack...
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000751 MadeChange = UpdateNodeType(MVT::isVoid, TP);
752 } else {
753 Record *ResultNode = Inst.getResult(0);
754 assert(ResultNode->isSubClassOf("RegisterClass") &&
755 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000756
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000757 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000758 ISE.getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000759 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000760 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000761
762 if (getNumChildren() != Inst.getNumOperands())
763 TP.error("Instruction '" + getOperator()->getName() + " expects " +
764 utostr(Inst.getNumOperands()) + " operands, not " +
765 utostr(getNumChildren()) + " operands!");
766 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000767 Record *OperandNode = Inst.getOperand(i);
768 MVT::ValueType VT;
769 if (OperandNode->isSubClassOf("RegisterClass")) {
770 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000771 ISE.getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000772 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
773 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000774 } else if (OperandNode->isSubClassOf("Operand")) {
775 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000776 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000777 } else {
778 assert(0 && "Unknown operand type!");
779 abort();
780 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000781 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000782 }
783 return MadeChange;
784 } else {
785 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
786
Evan Chengf26ba692006-03-20 08:09:17 +0000787 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000788 if (getNumChildren() != 1)
789 TP.error("Node transform '" + getOperator()->getName() +
790 "' requires one operand!");
Chris Lattner4e2f54d2006-03-21 06:42:58 +0000791
792 // If either the output or input of the xform does not have exact
793 // type info. We assume they must be the same. Otherwise, it is perfectly
794 // legal to transform from one type to a completely different type.
795 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Evan Chengf26ba692006-03-20 08:09:17 +0000796 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
797 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
798 return MadeChange;
799 }
800 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000801 }
Chris Lattner32707602005-09-08 23:22:48 +0000802}
803
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000804/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
805/// RHS of a commutative operation, not the on LHS.
806static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
807 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
808 return true;
809 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
810 return true;
811 return false;
812}
813
814
Chris Lattnere97603f2005-09-28 19:27:25 +0000815/// canPatternMatch - If it is impossible for this pattern to match on this
816/// target, fill in Reason and return false. Otherwise, return true. This is
817/// used as a santity check for .td files (to prevent people from writing stuff
818/// that can never possibly work), and to prevent the pattern permuter from
819/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000820bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000821 if (isLeaf()) return true;
822
823 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
824 if (!getChild(i)->canPatternMatch(Reason, ISE))
825 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000826
Chris Lattner550525e2006-03-24 21:48:51 +0000827 // If this is an intrinsic, handle cases that would make it not match. For
828 // example, if an operand is required to be an immediate.
829 if (getOperator()->isSubClassOf("Intrinsic")) {
830 // TODO:
831 return true;
832 }
833
Chris Lattnere97603f2005-09-28 19:27:25 +0000834 // If this node is a commutative operator, check that the LHS isn't an
835 // immediate.
836 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
Evan Cheng94b30402006-10-11 21:02:01 +0000837 if (NodeInfo.hasProperty(SDNPCommutative)) {
Chris Lattnere97603f2005-09-28 19:27:25 +0000838 // Scan all of the operands of the node and make sure that only the last one
Chris Lattner7905c552006-09-14 23:54:24 +0000839 // is a constant node, unless the RHS also is.
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000840 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Chris Lattner7905c552006-09-14 23:54:24 +0000841 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
Chris Lattnerce6e84c2006-09-21 20:46:13 +0000842 if (OnlyOnRHSOfCommutative(getChild(i))) {
Chris Lattner64906972006-09-21 18:28:27 +0000843 Reason="Immediate value must be on the RHS of commutative operators!";
Chris Lattner7905c552006-09-14 23:54:24 +0000844 return false;
845 }
846 }
Chris Lattnere97603f2005-09-28 19:27:25 +0000847 }
848
849 return true;
850}
Chris Lattner32707602005-09-08 23:22:48 +0000851
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000852//===----------------------------------------------------------------------===//
853// TreePattern implementation
854//
855
Chris Lattneredbd8712005-10-21 01:19:59 +0000856TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000857 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000858 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000859 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
860 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000861}
862
Chris Lattneredbd8712005-10-21 01:19:59 +0000863TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000864 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000865 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000866 Trees.push_back(ParseTreePattern(Pat));
867}
868
Chris Lattneredbd8712005-10-21 01:19:59 +0000869TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000870 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000871 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000872 Trees.push_back(Pat);
873}
874
875
876
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000877void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000878 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000879 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000880}
881
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000882TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
Chris Lattner8c063182006-03-30 22:50:40 +0000883 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
884 if (!OpDef) error("Pattern has unexpected operator type!");
885 Record *Operator = OpDef->getDef();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000886
887 if (Operator->isSubClassOf("ValueType")) {
888 // If the operator is a ValueType, then this must be "type cast" of a leaf
889 // node.
890 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000891 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000892
893 Init *Arg = Dag->getArg(0);
894 TreePatternNode *New;
895 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000896 Record *R = DI->getDef();
897 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000898 Dag->setArg(0, new DagInit(DI,
Chris Lattner72fe91c2005-09-24 00:40:24 +0000899 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000900 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000901 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000902 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000903 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
904 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000905 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
906 New = new TreePatternNode(II);
907 if (!Dag->getArgName(0).empty())
908 error("Constant int argument should not have a name!");
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000909 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
910 // Turn this into an IntInit.
911 Init *II = BI->convertInitializerTo(new IntRecTy());
912 if (II == 0 || !dynamic_cast<IntInit*>(II))
913 error("Bits value must be constants!");
914
915 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
916 if (!Dag->getArgName(0).empty())
917 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000918 } else {
919 Arg->dump();
920 error("Unknown leaf value for tree pattern!");
921 return 0;
922 }
923
Chris Lattner32707602005-09-08 23:22:48 +0000924 // Apply the type cast.
925 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000926 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000927 return New;
928 }
929
930 // Verify that this is something that makes sense for an operator.
931 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000932 !Operator->isSubClassOf("Instruction") &&
933 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner550525e2006-03-24 21:48:51 +0000934 !Operator->isSubClassOf("Intrinsic") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000935 Operator->getName() != "set")
936 error("Unrecognized node '" + Operator->getName() + "'!");
937
Chris Lattneredbd8712005-10-21 01:19:59 +0000938 // Check to see if this is something that is illegal in an input pattern.
939 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
Chris Lattner5a1df382006-03-24 23:10:39 +0000940 Operator->isSubClassOf("SDNodeXForm")))
Chris Lattneredbd8712005-10-21 01:19:59 +0000941 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
942
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000943 std::vector<TreePatternNode*> Children;
944
945 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
946 Init *Arg = Dag->getArg(i);
947 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
948 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000949 if (Children.back()->getName().empty())
950 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000951 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
952 Record *R = DefI->getDef();
953 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
954 // TreePatternNode if its own.
955 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000956 Dag->setArg(i, new DagInit(DefI,
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000957 std::vector<std::pair<Init*, std::string> >()));
958 --i; // Revisit this node...
959 } else {
960 TreePatternNode *Node = new TreePatternNode(DefI);
961 Node->setName(Dag->getArgName(i));
962 Children.push_back(Node);
963
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000964 // Input argument?
965 if (R->getName() == "node") {
966 if (Dag->getArgName(i).empty())
967 error("'node' argument requires a name to match with operand list");
968 Args.push_back(Dag->getArgName(i));
969 }
970 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000971 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
972 TreePatternNode *Node = new TreePatternNode(II);
973 if (!Dag->getArgName(i).empty())
974 error("Constant int argument should not have a name!");
975 Children.push_back(Node);
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000976 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
977 // Turn this into an IntInit.
978 Init *II = BI->convertInitializerTo(new IntRecTy());
979 if (II == 0 || !dynamic_cast<IntInit*>(II))
980 error("Bits value must be constants!");
981
982 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
983 if (!Dag->getArgName(i).empty())
984 error("Constant int argument should not have a name!");
985 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000986 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000987 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000988 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000989 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000990 error("Unknown leaf value for tree pattern!");
991 }
992 }
993
Chris Lattner5a1df382006-03-24 23:10:39 +0000994 // If the operator is an intrinsic, then this is just syntactic sugar for for
995 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
996 // convert the intrinsic name to a number.
997 if (Operator->isSubClassOf("Intrinsic")) {
998 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
999 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
1000
1001 // If this intrinsic returns void, it must have side-effects and thus a
1002 // chain.
1003 if (Int.ArgVTs[0] == MVT::isVoid) {
1004 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
1005 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1006 // Has side-effects, requires chain.
1007 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
1008 } else {
1009 // Otherwise, no chain.
1010 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
1011 }
1012
1013 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1014 Children.insert(Children.begin(), IIDNode);
1015 }
1016
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001017 return new TreePatternNode(Operator, Children);
1018}
1019
Chris Lattner32707602005-09-08 23:22:48 +00001020/// InferAllTypes - Infer/propagate as many types throughout the expression
1021/// patterns as possible. Return true if all types are infered, false
1022/// otherwise. Throw an exception if a type contradiction is found.
1023bool TreePattern::InferAllTypes() {
1024 bool MadeChange = true;
1025 while (MadeChange) {
1026 MadeChange = false;
1027 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001028 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +00001029 }
1030
1031 bool HasUnresolvedTypes = false;
1032 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1033 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1034 return !HasUnresolvedTypes;
1035}
1036
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001037void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001038 OS << getRecord()->getName();
1039 if (!Args.empty()) {
1040 OS << "(" << Args[0];
1041 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1042 OS << ", " << Args[i];
1043 OS << ")";
1044 }
1045 OS << ": ";
1046
1047 if (Trees.size() > 1)
1048 OS << "[\n";
1049 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1050 OS << "\t";
1051 Trees[i]->print(OS);
1052 OS << "\n";
1053 }
1054
1055 if (Trees.size() > 1)
1056 OS << "]\n";
1057}
1058
1059void TreePattern::dump() const { print(std::cerr); }
1060
1061
1062
1063//===----------------------------------------------------------------------===//
1064// DAGISelEmitter implementation
1065//
1066
Chris Lattnerca559d02005-09-08 21:03:01 +00001067// Parse all of the SDNode definitions for the target, populating SDNodes.
1068void DAGISelEmitter::ParseNodeInfo() {
1069 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1070 while (!Nodes.empty()) {
1071 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1072 Nodes.pop_back();
1073 }
Chris Lattner5a1df382006-03-24 23:10:39 +00001074
1075 // Get the buildin intrinsic nodes.
1076 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1077 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1078 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
Chris Lattnerca559d02005-09-08 21:03:01 +00001079}
1080
Chris Lattner24eeeb82005-09-13 21:51:00 +00001081/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1082/// map, and emit them to the file as functions.
1083void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1084 OS << "\n// Node transformations.\n";
1085 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1086 while (!Xforms.empty()) {
1087 Record *XFormNode = Xforms.back();
1088 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1089 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1090 SDNodeXForms.insert(std::make_pair(XFormNode,
1091 std::make_pair(SDNode, Code)));
1092
Chris Lattner1048b7a2005-09-13 22:03:37 +00001093 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +00001094 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1095 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1096
Chris Lattner1048b7a2005-09-13 22:03:37 +00001097 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +00001098 << "(SDNode *" << C2 << ") {\n";
1099 if (ClassName != "SDNode")
1100 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1101 OS << Code << "\n}\n";
1102 }
1103
1104 Xforms.pop_back();
1105 }
1106}
1107
Evan Cheng0fc71982005-12-08 02:00:36 +00001108void DAGISelEmitter::ParseComplexPatterns() {
1109 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1110 while (!AMs.empty()) {
1111 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1112 AMs.pop_back();
1113 }
1114}
Chris Lattner24eeeb82005-09-13 21:51:00 +00001115
1116
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001117/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1118/// file, building up the PatternFragments map. After we've collected them all,
1119/// inline fragments together as necessary, so that there are no references left
1120/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001121///
1122/// This also emits all of the predicate functions to the output file.
1123///
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001124void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001125 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1126
1127 // First step, parse all of the fragments and emit predicate functions.
1128 OS << "\n// Predicate functions.\n";
1129 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001130 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +00001131 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001132 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +00001133
1134 // Validate the argument list, converting it to map, to discard duplicates.
1135 std::vector<std::string> &Args = P->getArgList();
1136 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1137
1138 if (OperandsMap.count(""))
1139 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1140
1141 // Parse the operands list.
1142 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Chris Lattner8c063182006-03-30 22:50:40 +00001143 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1144 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
Chris Lattneree9f0c32005-09-13 21:20:49 +00001145 P->error("Operands list should start with '(ops ... '!");
1146
1147 // Copy over the arguments.
1148 Args.clear();
1149 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1150 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1151 static_cast<DefInit*>(OpsList->getArg(j))->
1152 getDef()->getName() != "node")
1153 P->error("Operands list should all be 'node' values.");
1154 if (OpsList->getArgName(j).empty())
1155 P->error("Operands list should have names for each operand!");
1156 if (!OperandsMap.count(OpsList->getArgName(j)))
1157 P->error("'" + OpsList->getArgName(j) +
1158 "' does not occur in pattern or was multiply specified!");
1159 OperandsMap.erase(OpsList->getArgName(j));
1160 Args.push_back(OpsList->getArgName(j));
1161 }
1162
1163 if (!OperandsMap.empty())
1164 P->error("Operands list does not contain an entry for operand '" +
1165 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001166
1167 // If there is a code init for this fragment, emit the predicate code and
1168 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001169 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1170 if (!Code.empty()) {
Evan Chengd46bd602006-09-19 19:08:04 +00001171 if (P->getOnlyTree()->isLeaf())
1172 OS << "inline bool Predicate_" << Fragments[i]->getName()
1173 << "(SDNode *N) {\n";
1174 else {
1175 std::string ClassName =
1176 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1177 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001178
Evan Chengd46bd602006-09-19 19:08:04 +00001179 OS << "inline bool Predicate_" << Fragments[i]->getName()
1180 << "(SDNode *" << C2 << ") {\n";
1181 if (ClassName != "SDNode")
1182 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1183 }
Chris Lattner24eeeb82005-09-13 21:51:00 +00001184 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001185 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001186 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001187
1188 // If there is a node transformation corresponding to this, keep track of
1189 // it.
1190 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1191 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001192 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001193 }
1194
1195 OS << "\n\n";
1196
1197 // Now that we've parsed all of the tree fragments, do a closure on them so
1198 // that there are not references to PatFrags left inside of them.
1199 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1200 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001201 TreePattern *ThePat = I->second;
1202 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001203
Chris Lattner32707602005-09-08 23:22:48 +00001204 // Infer as many types as possible. Don't worry about it if we don't infer
1205 // all of them, some may depend on the inputs of the pattern.
1206 try {
1207 ThePat->InferAllTypes();
1208 } catch (...) {
1209 // If this pattern fragment is not supported by this target (no types can
1210 // satisfy its constraints), just ignore it. If the bogus pattern is
1211 // actually used by instructions, the type consistency error will be
1212 // reported there.
1213 }
1214
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001215 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001216 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001217 }
1218}
1219
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001220/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001221/// instruction input. Return true if this is a real use.
1222static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001223 std::map<std::string, TreePatternNode*> &InstInputs,
1224 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001225 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001226 if (Pat->getName().empty()) {
1227 if (Pat->isLeaf()) {
1228 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1229 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1230 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001231 else if (DI && DI->getDef()->isSubClassOf("Register"))
1232 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001233 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001234 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001235 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001236
1237 Record *Rec;
1238 if (Pat->isLeaf()) {
1239 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1240 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1241 Rec = DI->getDef();
1242 } else {
1243 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1244 Rec = Pat->getOperator();
1245 }
1246
Evan Cheng01f318b2005-12-14 02:21:57 +00001247 // SRCVALUE nodes are ignored.
1248 if (Rec->getName() == "srcvalue")
1249 return false;
1250
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001251 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1252 if (!Slot) {
1253 Slot = Pat;
1254 } else {
1255 Record *SlotRec;
1256 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001257 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001258 } else {
1259 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1260 SlotRec = Slot->getOperator();
1261 }
1262
1263 // Ensure that the inputs agree if we've already seen this input.
1264 if (Rec != SlotRec)
1265 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001266 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001267 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1268 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001269 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001270}
1271
1272/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1273/// part of "I", the instruction), computing the set of inputs and outputs of
1274/// the pattern. Report errors if we see anything naughty.
1275void DAGISelEmitter::
1276FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1277 std::map<std::string, TreePatternNode*> &InstInputs,
Chris Lattner947604b2006-03-24 21:52:20 +00001278 std::map<std::string, TreePatternNode*>&InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001279 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001280 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001281 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001282 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001283 if (!isUse && Pat->getTransformFn())
1284 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001285 return;
1286 } else if (Pat->getOperator()->getName() != "set") {
1287 // If this is not a set, verify that the children nodes are not void typed,
1288 // and recurse.
1289 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001290 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001291 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001292 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001293 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001294 }
1295
1296 // If this is a non-leaf node with no children, treat it basically as if
1297 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001298 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001299 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001300 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001301
Chris Lattnerf1311842005-09-14 23:05:13 +00001302 if (!isUse && Pat->getTransformFn())
1303 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001304 return;
1305 }
1306
1307 // Otherwise, this is a set, validate and collect instruction results.
1308 if (Pat->getNumChildren() == 0)
1309 I->error("set requires operands!");
1310 else if (Pat->getNumChildren() & 1)
1311 I->error("set requires an even number of operands");
1312
Chris Lattnerf1311842005-09-14 23:05:13 +00001313 if (Pat->getTransformFn())
1314 I->error("Cannot specify a transform function on a set node!");
1315
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001316 // Check the set destinations.
1317 unsigned NumValues = Pat->getNumChildren()/2;
1318 for (unsigned i = 0; i != NumValues; ++i) {
1319 TreePatternNode *Dest = Pat->getChild(i);
1320 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001321 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001322
1323 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1324 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001325 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001326
Evan Chengbcecf332005-12-17 01:19:28 +00001327 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1328 if (Dest->getName().empty())
1329 I->error("set destination must have a name!");
1330 if (InstResults.count(Dest->getName()))
1331 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001332 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001333 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001334 InstImpResults.push_back(Val->getDef());
1335 } else {
1336 I->error("set destination should be a register!");
1337 }
1338
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001339 // Verify and collect info from the computation.
1340 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001341 InstInputs, InstResults,
1342 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001343 }
1344}
1345
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001346/// ParseInstructions - Parse all of the instructions, inlining and resolving
1347/// any fragments involved. This populates the Instructions list with fully
1348/// resolved instructions.
1349void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001350 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1351
1352 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001353 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001354
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001355 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1356 LI = Instrs[i]->getValueAsListInit("Pattern");
1357
1358 // If there is no pattern, only collect minimal information about the
1359 // instruction for its operand list. We have to assume that there is one
1360 // result, as we have no detailed info.
1361 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001362 std::vector<Record*> Results;
1363 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001364
1365 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001366
Evan Cheng3a217f32005-12-22 02:35:21 +00001367 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001368 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001369 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001370 // These produce no results
1371 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1372 Operands.push_back(InstInfo.OperandList[j].Rec);
1373 } else {
1374 // Assume the first operand is the result.
1375 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001376
Evan Cheng3a217f32005-12-22 02:35:21 +00001377 // The rest are inputs.
1378 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1379 Operands.push_back(InstInfo.OperandList[j].Rec);
1380 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001381 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001382
1383 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001384 std::vector<Record*> ImpResults;
1385 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001386 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001387 DAGInstruction(0, Results, Operands, ImpResults,
1388 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001389 continue; // no pattern.
1390 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001391
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001392 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001393 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001394 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001395 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001396
Chris Lattner95f6b762005-09-08 23:26:30 +00001397 // Infer as many types as possible. If we cannot infer all of them, we can
1398 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001399 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001400 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001401
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001402 // InstInputs - Keep track of all of the inputs of the instruction, along
1403 // with the record they are declared as.
1404 std::map<std::string, TreePatternNode*> InstInputs;
1405
1406 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001407 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001408 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001409
1410 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001411 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001412
Chris Lattner1f39e292005-09-14 00:09:24 +00001413 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001414 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001415 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1416 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001417 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001418 I->error("Top-level forms in instruction pattern should have"
1419 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001420
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001421 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001422 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001423 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001424 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001425
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001426 // Now that we have inputs and outputs of the pattern, inspect the operands
1427 // list for the instruction. This determines the order that operands are
1428 // added to the machine instruction the node corresponds to.
1429 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001430
1431 // Parse the operands list from the (ops) list, validating it.
1432 std::vector<std::string> &Args = I->getArgList();
1433 assert(Args.empty() && "Args list should still be empty here!");
1434 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1435
1436 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001437 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001438 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001439 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001440 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001441 I->error("'" + InstResults.begin()->first +
1442 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001443 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001444
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001445 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001446 TreePatternNode *RNode = InstResults[OpName];
Chris Lattner5c4c7742006-03-25 22:12:44 +00001447 if (RNode == 0)
1448 I->error("Operand $" + OpName + " does not exist in operand list!");
1449
Evan Cheng420132e2006-03-20 06:04:09 +00001450 if (i == 0)
1451 Res0Node = RNode;
1452 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001453 if (R == 0)
1454 I->error("Operand $" + OpName + " should be a set destination: all "
1455 "outputs must occur before inputs in operand list!");
1456
1457 if (CGI.OperandList[i].Rec != R)
1458 I->error("Operand $" + OpName + " class mismatch!");
1459
Chris Lattnerae6d8282005-09-15 21:51:12 +00001460 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001461 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001462
Chris Lattner39e8af92005-09-14 18:19:25 +00001463 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001464 InstResults.erase(OpName);
1465 }
1466
Chris Lattner0b592252005-09-14 21:59:34 +00001467 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1468 // the copy while we're checking the inputs.
1469 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001470
1471 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001472 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001473 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1474 const std::string &OpName = CGI.OperandList[i].Name;
1475 if (OpName.empty())
1476 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1477
Chris Lattner0b592252005-09-14 21:59:34 +00001478 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001479 I->error("Operand $" + OpName +
1480 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001481 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001482 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001483
1484 if (InVal->isLeaf() &&
1485 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1486 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001487 if (CGI.OperandList[i].Rec != InRec &&
1488 !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001489 I->error("Operand $" + OpName + "'s register class disagrees"
1490 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001491 }
1492 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001493
Chris Lattner2175c182005-09-14 23:01:59 +00001494 // Construct the result for the dest-pattern operand list.
1495 TreePatternNode *OpNode = InVal->clone();
1496
1497 // No predicate is useful on the result.
1498 OpNode->setPredicateFn("");
1499
1500 // Promote the xform function to be an explicit node if set.
1501 if (Record *Xform = OpNode->getTransformFn()) {
1502 OpNode->setTransformFn(0);
1503 std::vector<TreePatternNode*> Children;
1504 Children.push_back(OpNode);
1505 OpNode = new TreePatternNode(Xform, Children);
1506 }
1507
1508 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001509 }
1510
Chris Lattner0b592252005-09-14 21:59:34 +00001511 if (!InstInputsCheck.empty())
1512 I->error("Input operand $" + InstInputsCheck.begin()->first +
1513 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001514
1515 TreePatternNode *ResultPattern =
1516 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001517 // Copy fully inferred output node type to instruction result pattern.
1518 if (NumResults > 0)
1519 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001520
1521 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001522 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001523 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1524
1525 // Use a temporary tree pattern to infer all types and make sure that the
1526 // constructed result is correct. This depends on the instruction already
1527 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001528 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001529 Temp.InferAllTypes();
1530
1531 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1532 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001533
Chris Lattner32707602005-09-08 23:22:48 +00001534 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001535 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001536
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001537 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001538 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1539 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001540 DAGInstruction &TheInst = II->second;
1541 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001542 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001543
Chris Lattner1f39e292005-09-14 00:09:24 +00001544 if (I->getNumTrees() != 1) {
1545 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1546 continue;
1547 }
1548 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001549 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001550 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001551 if (Pattern->getNumChildren() != 2)
1552 continue; // Not a set of a single value (not handled so far)
1553
1554 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001555 } else{
1556 // Not a set (store or something?)
1557 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001558 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001559
1560 std::string Reason;
1561 if (!SrcPattern->canPatternMatch(Reason, *this))
1562 I->error("Instruction can never match: " + Reason);
1563
Evan Cheng58e84a62005-12-14 22:02:59 +00001564 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001565 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001566 PatternsToMatch.
1567 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
Evan Cheng59413202006-04-19 18:07:24 +00001568 SrcPattern, DstPattern,
Evan Chengc81d2a02006-04-19 20:36:09 +00001569 Instr->getValueAsInt("AddedComplexity")));
Chris Lattner1f39e292005-09-14 00:09:24 +00001570 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001571}
1572
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001573void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001574 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001575
Chris Lattnerabbb6052005-09-15 21:42:00 +00001576 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001577 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001578 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001579
Chris Lattnerabbb6052005-09-15 21:42:00 +00001580 // Inline pattern fragments into it.
1581 Pattern->InlinePatternFragments();
1582
Chris Lattnera3548492006-06-20 00:18:02 +00001583 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1584 if (LI->getSize() == 0) continue; // no pattern.
1585
1586 // Parse the instruction.
1587 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1588
1589 // Inline pattern fragments into it.
1590 Result->InlinePatternFragments();
Chris Lattner09c03392005-11-17 17:43:52 +00001591
Chris Lattnera3548492006-06-20 00:18:02 +00001592 if (Result->getNumTrees() != 1)
1593 Result->error("Cannot handle instructions producing instructions "
1594 "with temporaries yet!");
1595
1596 bool IterateInference;
Chris Lattner186fb7d2006-06-20 00:31:27 +00001597 bool InferredAllPatternTypes, InferredAllResultTypes;
Chris Lattnera3548492006-06-20 00:18:02 +00001598 do {
1599 // Infer as many types as possible. If we cannot infer all of them, we
1600 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001601 InferredAllPatternTypes = Pattern->InferAllTypes();
Chris Lattnera3548492006-06-20 00:18:02 +00001602
Chris Lattner64906972006-09-21 18:28:27 +00001603 // Infer as many types as possible. If we cannot infer all of them, we
1604 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001605 InferredAllResultTypes = Result->InferAllTypes();
1606
Chris Lattnera3548492006-06-20 00:18:02 +00001607 // Apply the type of the result to the source pattern. This helps us
1608 // resolve cases where the input type is known to be a pointer type (which
1609 // is considered resolved), but the result knows it needs to be 32- or
1610 // 64-bits. Infer the other way for good measure.
1611 IterateInference = Pattern->getOnlyTree()->
1612 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1613 IterateInference |= Result->getOnlyTree()->
1614 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1615 } while (IterateInference);
Chris Lattner186fb7d2006-06-20 00:31:27 +00001616
1617 // Verify that we inferred enough types that we can do something with the
1618 // pattern and result. If these fire the user has to add type casts.
1619 if (!InferredAllPatternTypes)
1620 Pattern->error("Could not infer all types in pattern!");
1621 if (!InferredAllResultTypes)
1622 Result->error("Could not infer all types in pattern result!");
Chris Lattnera3548492006-06-20 00:18:02 +00001623
Chris Lattner09c03392005-11-17 17:43:52 +00001624 // Validate that the input pattern is correct.
1625 {
1626 std::map<std::string, TreePatternNode*> InstInputs;
Evan Cheng420132e2006-03-20 06:04:09 +00001627 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001628 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001629 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001630 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001631 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001632 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001633 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001634
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001635 // Promote the xform function to be an explicit node if set.
1636 std::vector<TreePatternNode*> ResultNodeOperands;
1637 TreePatternNode *DstPattern = Result->getOnlyTree();
1638 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1639 TreePatternNode *OpNode = DstPattern->getChild(ii);
1640 if (Record *Xform = OpNode->getTransformFn()) {
1641 OpNode->setTransformFn(0);
1642 std::vector<TreePatternNode*> Children;
1643 Children.push_back(OpNode);
1644 OpNode = new TreePatternNode(Xform, Children);
1645 }
1646 ResultNodeOperands.push_back(OpNode);
1647 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00001648 DstPattern = Result->getOnlyTree();
1649 if (!DstPattern->isLeaf())
1650 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1651 ResultNodeOperands);
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001652 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1653 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1654 Temp.InferAllTypes();
1655
Chris Lattnere97603f2005-09-28 19:27:25 +00001656 std::string Reason;
1657 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1658 Pattern->error("Pattern can never match: " + Reason);
1659
Evan Cheng58e84a62005-12-14 22:02:59 +00001660 PatternsToMatch.
1661 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1662 Pattern->getOnlyTree(),
Evan Cheng59413202006-04-19 18:07:24 +00001663 Temp.getOnlyTree(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001664 Patterns[i]->getValueAsInt("AddedComplexity")));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001665 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001666}
1667
Chris Lattnere46e17b2005-09-29 19:28:10 +00001668/// CombineChildVariants - Given a bunch of permutations of each child of the
1669/// 'operator' node, put them together in all possible ways.
1670static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001671 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001672 std::vector<TreePatternNode*> &OutVariants,
1673 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001674 // Make sure that each operand has at least one variant to choose from.
1675 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1676 if (ChildVariants[i].empty())
1677 return;
1678
Chris Lattnere46e17b2005-09-29 19:28:10 +00001679 // The end result is an all-pairs construction of the resultant pattern.
1680 std::vector<unsigned> Idxs;
1681 Idxs.resize(ChildVariants.size());
1682 bool NotDone = true;
1683 while (NotDone) {
1684 // Create the variant and add it to the output list.
1685 std::vector<TreePatternNode*> NewChildren;
1686 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1687 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1688 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1689
1690 // Copy over properties.
1691 R->setName(Orig->getName());
1692 R->setPredicateFn(Orig->getPredicateFn());
1693 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001694 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001695
1696 // If this pattern cannot every match, do not include it as a variant.
1697 std::string ErrString;
1698 if (!R->canPatternMatch(ErrString, ISE)) {
1699 delete R;
1700 } else {
1701 bool AlreadyExists = false;
1702
1703 // Scan to see if this pattern has already been emitted. We can get
1704 // duplication due to things like commuting:
1705 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1706 // which are the same pattern. Ignore the dups.
1707 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1708 if (R->isIsomorphicTo(OutVariants[i])) {
1709 AlreadyExists = true;
1710 break;
1711 }
1712
1713 if (AlreadyExists)
1714 delete R;
1715 else
1716 OutVariants.push_back(R);
1717 }
1718
1719 // Increment indices to the next permutation.
1720 NotDone = false;
1721 // Look for something we can increment without causing a wrap-around.
1722 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1723 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1724 NotDone = true; // Found something to increment.
1725 break;
1726 }
1727 Idxs[IdxsIdx] = 0;
1728 }
1729 }
1730}
1731
Chris Lattneraf302912005-09-29 22:36:54 +00001732/// CombineChildVariants - A helper function for binary operators.
1733///
1734static void CombineChildVariants(TreePatternNode *Orig,
1735 const std::vector<TreePatternNode*> &LHS,
1736 const std::vector<TreePatternNode*> &RHS,
1737 std::vector<TreePatternNode*> &OutVariants,
1738 DAGISelEmitter &ISE) {
1739 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1740 ChildVariants.push_back(LHS);
1741 ChildVariants.push_back(RHS);
1742 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1743}
1744
1745
1746static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1747 std::vector<TreePatternNode *> &Children) {
1748 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1749 Record *Operator = N->getOperator();
1750
1751 // Only permit raw nodes.
1752 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1753 N->getTransformFn()) {
1754 Children.push_back(N);
1755 return;
1756 }
1757
1758 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1759 Children.push_back(N->getChild(0));
1760 else
1761 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1762
1763 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1764 Children.push_back(N->getChild(1));
1765 else
1766 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1767}
1768
Chris Lattnere46e17b2005-09-29 19:28:10 +00001769/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1770/// the (potentially recursive) pattern by using algebraic laws.
1771///
1772static void GenerateVariantsOf(TreePatternNode *N,
1773 std::vector<TreePatternNode*> &OutVariants,
1774 DAGISelEmitter &ISE) {
1775 // We cannot permute leaves.
1776 if (N->isLeaf()) {
1777 OutVariants.push_back(N);
1778 return;
1779 }
1780
1781 // Look up interesting info about the node.
Chris Lattner5a1df382006-03-24 23:10:39 +00001782 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001783
1784 // If this node is associative, reassociate.
Evan Cheng94b30402006-10-11 21:02:01 +00001785 if (NodeInfo.hasProperty(SDNPAssociative)) {
Chris Lattneraf302912005-09-29 22:36:54 +00001786 // Reassociate by pulling together all of the linked operators
1787 std::vector<TreePatternNode*> MaximalChildren;
1788 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1789
1790 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1791 // permutations.
1792 if (MaximalChildren.size() == 3) {
1793 // Find the variants of all of our maximal children.
1794 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1795 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1796 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1797 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1798
1799 // There are only two ways we can permute the tree:
1800 // (A op B) op C and A op (B op C)
1801 // Within these forms, we can also permute A/B/C.
1802
1803 // Generate legal pair permutations of A/B/C.
1804 std::vector<TreePatternNode*> ABVariants;
1805 std::vector<TreePatternNode*> BAVariants;
1806 std::vector<TreePatternNode*> ACVariants;
1807 std::vector<TreePatternNode*> CAVariants;
1808 std::vector<TreePatternNode*> BCVariants;
1809 std::vector<TreePatternNode*> CBVariants;
1810 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1811 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1812 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1813 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1814 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1815 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1816
1817 // Combine those into the result: (x op x) op x
1818 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1819 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1820 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1821 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1822 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1823 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1824
1825 // Combine those into the result: x op (x op x)
1826 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1827 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1828 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1829 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1830 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1831 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1832 return;
1833 }
1834 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001835
1836 // Compute permutations of all children.
1837 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1838 ChildVariants.resize(N->getNumChildren());
1839 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1840 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1841
1842 // Build all permutations based on how the children were formed.
1843 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1844
1845 // If this node is commutative, consider the commuted order.
Evan Cheng94b30402006-10-11 21:02:01 +00001846 if (NodeInfo.hasProperty(SDNPCommutative)) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001847 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattner706d2d32006-08-09 16:44:44 +00001848 // Don't count children which are actually register references.
1849 unsigned NC = 0;
1850 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1851 TreePatternNode *Child = N->getChild(i);
1852 if (Child->isLeaf())
1853 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1854 Record *RR = DI->getDef();
1855 if (RR->isSubClassOf("Register"))
1856 continue;
1857 }
1858 NC++;
1859 }
Chris Lattneraf302912005-09-29 22:36:54 +00001860 // Consider the commuted order.
Chris Lattner706d2d32006-08-09 16:44:44 +00001861 if (NC == 2)
1862 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1863 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001864 }
1865}
1866
1867
Chris Lattnere97603f2005-09-28 19:27:25 +00001868// GenerateVariants - Generate variants. For example, commutative patterns can
1869// match multiple ways. Add them to PatternsToMatch as well.
1870void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001871
1872 DEBUG(std::cerr << "Generating instruction variants.\n");
1873
1874 // Loop over all of the patterns we've collected, checking to see if we can
1875 // generate variants of the instruction, through the exploitation of
1876 // identities. This permits the target to provide agressive matching without
1877 // the .td file having to contain tons of variants of instructions.
1878 //
1879 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1880 // intentionally do not reconsider these. Any variants of added patterns have
1881 // already been added.
1882 //
1883 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1884 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001885 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001886
1887 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001888 Variants.erase(Variants.begin()); // Remove the original pattern.
1889
1890 if (Variants.empty()) // No variants for this pattern.
1891 continue;
1892
1893 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001894 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001895 std::cerr << "\n");
1896
1897 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1898 TreePatternNode *Variant = Variants[v];
1899
1900 DEBUG(std::cerr << " VAR#" << v << ": ";
1901 Variant->dump();
1902 std::cerr << "\n");
1903
1904 // Scan to see if an instruction or explicit pattern already matches this.
1905 bool AlreadyExists = false;
1906 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1907 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001908 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001909 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1910 AlreadyExists = true;
1911 break;
1912 }
1913 }
1914 // If we already have it, ignore the variant.
1915 if (AlreadyExists) continue;
1916
1917 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001918 PatternsToMatch.
1919 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
Evan Cheng59413202006-04-19 18:07:24 +00001920 Variant, PatternsToMatch[i].getDstPattern(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001921 PatternsToMatch[i].getAddedComplexity()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001922 }
1923
1924 DEBUG(std::cerr << "\n");
1925 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001926}
1927
Evan Cheng0fc71982005-12-08 02:00:36 +00001928// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1929// ComplexPattern.
1930static bool NodeIsComplexPattern(TreePatternNode *N)
1931{
1932 return (N->isLeaf() &&
1933 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1934 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1935 isSubClassOf("ComplexPattern"));
1936}
1937
1938// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1939// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1940static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1941 DAGISelEmitter &ISE)
1942{
1943 if (N->isLeaf() &&
1944 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1945 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1946 isSubClassOf("ComplexPattern")) {
1947 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1948 ->getDef());
1949 }
1950 return NULL;
1951}
1952
Chris Lattner05814af2005-09-28 17:57:56 +00001953/// getPatternSize - Return the 'size' of this pattern. We want to match large
1954/// patterns before small ones. This is used to determine the size of a
1955/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001956static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng2618d072006-05-17 20:37:59 +00001957 assert((isExtIntegerInVTs(P->getExtTypes()) ||
1958 isExtFloatingPointInVTs(P->getExtTypes()) ||
1959 P->getExtTypeNum(0) == MVT::isVoid ||
1960 P->getExtTypeNum(0) == MVT::Flag ||
1961 P->getExtTypeNum(0) == MVT::iPTR) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +00001962 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +00001963 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00001964 // If the root node is a ConstantSDNode, increases its size.
1965 // e.g. (set R32:$dst, 0).
1966 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +00001967 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +00001968
1969 // FIXME: This is a hack to statically increase the priority of patterns
1970 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1971 // Later we can allow complexity / cost for each pattern to be (optionally)
1972 // specified. To get best possible pattern match we'll need to dynamically
1973 // calculate the complexity of all patterns a dag can potentially map to.
1974 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1975 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +00001976 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +00001977
1978 // If this node has some predicate function that must match, it adds to the
1979 // complexity of this node.
1980 if (!P->getPredicateFn().empty())
1981 ++Size;
1982
Chris Lattner05814af2005-09-28 17:57:56 +00001983 // Count children in the count if they are also nodes.
1984 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1985 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001986 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001987 Size += getPatternSize(Child, ISE);
1988 else if (Child->isLeaf()) {
1989 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +00001990 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Evan Cheng4a7c2842006-01-06 22:19:44 +00001991 else if (NodeIsComplexPattern(Child))
1992 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00001993 else if (!Child->getPredicateFn().empty())
1994 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001995 }
Chris Lattner05814af2005-09-28 17:57:56 +00001996 }
1997
1998 return Size;
1999}
2000
2001/// getResultPatternCost - Compute the number of instructions for this pattern.
2002/// This is a temporary hack. We should really include the instruction
2003/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00002004static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00002005 if (P->isLeaf()) return 0;
2006
Evan Chengfbad7082006-02-18 02:33:09 +00002007 unsigned Cost = 0;
2008 Record *Op = P->getOperator();
2009 if (Op->isSubClassOf("Instruction")) {
2010 Cost++;
2011 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
2012 if (II.usesCustomDAGSchedInserter)
2013 Cost += 10;
2014 }
Chris Lattner05814af2005-09-28 17:57:56 +00002015 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00002016 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002017 return Cost;
2018}
2019
Evan Chenge6f32032006-07-19 00:24:41 +00002020/// getResultPatternCodeSize - Compute the code size of instructions for this
2021/// pattern.
2022static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
2023 if (P->isLeaf()) return 0;
2024
2025 unsigned Cost = 0;
2026 Record *Op = P->getOperator();
2027 if (Op->isSubClassOf("Instruction")) {
2028 Cost += Op->getValueAsInt("CodeSize");
2029 }
2030 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2031 Cost += getResultPatternSize(P->getChild(i), ISE);
2032 return Cost;
2033}
2034
Chris Lattner05814af2005-09-28 17:57:56 +00002035// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2036// In particular, we want to match maximal patterns first and lowest cost within
2037// a particular complexity first.
2038struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00002039 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2040 DAGISelEmitter &ISE;
2041
Evan Cheng58e84a62005-12-14 22:02:59 +00002042 bool operator()(PatternToMatch *LHS,
2043 PatternToMatch *RHS) {
2044 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2045 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Evan Chengc81d2a02006-04-19 20:36:09 +00002046 LHSSize += LHS->getAddedComplexity();
2047 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +00002048 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2049 if (LHSSize < RHSSize) return false;
2050
2051 // If the patterns have equal complexity, compare generated instruction cost
Evan Chenge6f32032006-07-19 00:24:41 +00002052 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2053 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2054 if (LHSCost < RHSCost) return true;
2055 if (LHSCost > RHSCost) return false;
2056
2057 return getResultPatternSize(LHS->getDstPattern(), ISE) <
2058 getResultPatternSize(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002059 }
2060};
2061
Nate Begeman6510b222005-12-01 04:51:06 +00002062/// getRegisterValueType - Look up and return the first ValueType of specified
2063/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00002064static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00002065 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2066 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00002067 return MVT::Other;
2068}
2069
Chris Lattner72fe91c2005-09-24 00:40:24 +00002070
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002071/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2072/// type information from it.
2073static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00002074 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002075 if (!N->isLeaf())
2076 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2077 RemoveAllTypes(N->getChild(i));
2078}
Chris Lattner72fe91c2005-09-24 00:40:24 +00002079
Chris Lattner0614b622005-11-02 06:49:14 +00002080Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2081 Record *N = Records.getDef(Name);
Chris Lattner5a1df382006-03-24 23:10:39 +00002082 if (!N || !N->isSubClassOf("SDNode")) {
2083 std::cerr << "Error getting SDNode '" << Name << "'!\n";
2084 exit(1);
2085 }
Chris Lattner0614b622005-11-02 06:49:14 +00002086 return N;
2087}
2088
Evan Cheng51fecc82006-01-09 18:27:06 +00002089/// NodeHasProperty - return true if TreePatternNode has the specified
2090/// property.
Evan Cheng94b30402006-10-11 21:02:01 +00002091static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Evan Cheng51fecc82006-01-09 18:27:06 +00002092 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002093{
Evan Cheng94b30402006-10-11 21:02:01 +00002094 if (N->isLeaf()) {
2095 const ComplexPattern *CP = NodeGetComplexPattern(N, ISE);
2096 if (CP)
2097 return CP->hasProperty(Property);
2098 return false;
2099 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002100 Record *Operator = N->getOperator();
2101 if (!Operator->isSubClassOf("SDNode")) return false;
2102
2103 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00002104 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002105}
2106
Evan Cheng94b30402006-10-11 21:02:01 +00002107static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Evan Cheng51fecc82006-01-09 18:27:06 +00002108 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002109{
Evan Cheng51fecc82006-01-09 18:27:06 +00002110 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00002111 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00002112
2113 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2114 TreePatternNode *Child = N->getChild(i);
2115 if (PatternHasProperty(Child, Property, ISE))
2116 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002117 }
2118
2119 return false;
2120}
2121
Evan Chengb915f312005-12-09 22:45:35 +00002122class PatternCodeEmitter {
2123private:
2124 DAGISelEmitter &ISE;
2125
Evan Cheng58e84a62005-12-14 22:02:59 +00002126 // Predicates.
2127 ListInit *Predicates;
Evan Cheng59413202006-04-19 18:07:24 +00002128 // Pattern cost.
2129 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +00002130 // Instruction selector pattern.
2131 TreePatternNode *Pattern;
2132 // Matched instruction.
2133 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002134
Evan Chengb915f312005-12-09 22:45:35 +00002135 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00002136 std::map<std::string, std::string> VariableMap;
2137 // Node to operator mapping
2138 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00002139 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002140 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +00002141 // Original input chain(s).
2142 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00002143 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +00002144
Evan Cheng676d7312006-08-26 00:59:04 +00002145 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +00002146 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +00002147 /// tested, and if true, the match fails) [when 1], or normal code to emit
2148 /// [when 0], or initialization code to emit [when 2].
2149 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002150 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2151 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +00002152 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +00002153 /// TargetOpcodes - The target specific opcodes used by the resulting
2154 /// instructions.
2155 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +00002156 std::vector<std::string> &TargetVTs;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002157
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002158 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002159 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002160 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +00002161 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002162
2163 void emitCheck(const std::string &S) {
2164 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +00002165 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002166 }
2167 void emitCode(const std::string &S) {
2168 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +00002169 GeneratedCode.push_back(std::make_pair(0, S));
2170 }
2171 void emitInit(const std::string &S) {
2172 if (!S.empty())
2173 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002174 }
Evan Chengf5493192006-08-26 01:02:19 +00002175 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002176 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +00002177 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +00002178 }
Evan Chengfceb57a2006-07-15 08:45:20 +00002179 void emitOpcode(const std::string &Opc) {
2180 TargetOpcodes.push_back(Opc);
2181 OpcNo++;
2182 }
Evan Chengf8729402006-07-16 06:12:52 +00002183 void emitVT(const std::string &VT) {
2184 TargetVTs.push_back(VT);
2185 VTNo++;
2186 }
Evan Chengb915f312005-12-09 22:45:35 +00002187public:
Evan Cheng58e84a62005-12-14 22:02:59 +00002188 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2189 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +00002190 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +00002191 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +00002192 std::vector<std::string> &to,
Chris Lattner706d2d32006-08-09 16:44:44 +00002193 std::vector<std::string> &tv)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002194 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +00002195 GeneratedCode(gc), GeneratedDecl(gd),
2196 TargetOpcodes(to), TargetVTs(tv),
Chris Lattner706d2d32006-08-09 16:44:44 +00002197 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00002198
2199 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2200 /// if the match fails. At this point, we already know that the opcode for N
2201 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00002202 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002203 const std::string &RootName,
Evan Chenge41bf822006-02-05 06:43:12 +00002204 const std::string &ChainSuffix, bool &FoundChain) {
2205 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00002206 // Emit instruction predicates. Each predicate is just a string for now.
2207 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002208 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00002209 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2210 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2211 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002212 if (!Def->isSubClassOf("Predicate")) {
Jim Laskey16d42c62006-07-11 18:25:13 +00002213#ifndef NDEBUG
2214 Def->dump();
2215#endif
Evan Cheng58e84a62005-12-14 22:02:59 +00002216 assert(0 && "Unknown predicate type!");
2217 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002218 if (!PredicateCheck.empty())
Chris Lattnerbc7fa522006-09-19 00:41:36 +00002219 PredicateCheck += " && ";
Chris Lattner67a202b2006-01-28 20:43:52 +00002220 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00002221 }
2222 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002223
2224 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00002225 }
2226
Evan Chengb915f312005-12-09 22:45:35 +00002227 if (N->isLeaf()) {
2228 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002229 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00002230 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002231 return;
2232 } else if (!NodeIsComplexPattern(N)) {
2233 assert(0 && "Cannot match this as a leaf value!");
2234 abort();
2235 }
2236 }
2237
Chris Lattner488580c2006-01-28 19:06:51 +00002238 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002239 // we already saw this in the pattern, emit code to verify dagness.
2240 if (!N->getName().empty()) {
2241 std::string &VarMapEntry = VariableMap[N->getName()];
2242 if (VarMapEntry.empty()) {
2243 VarMapEntry = RootName;
2244 } else {
2245 // If we get here, this is a second reference to a specific name. Since
2246 // we already have checked that the first reference is valid, we don't
2247 // have to recursively match it, just check that it's the same as the
2248 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002249 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00002250 return;
2251 }
Evan Chengf805c2e2006-01-12 19:35:54 +00002252
2253 if (!N->isLeaf())
2254 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00002255 }
2256
2257
2258 // Emit code to load the child nodes and match their contents recursively.
2259 unsigned OpNo = 0;
Evan Cheng94b30402006-10-11 21:02:01 +00002260 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, ISE);
2261 bool HasChain = PatternHasProperty(N, SDNPHasChain, ISE);
2262 bool HasOutFlag = PatternHasProperty(N, SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00002263 bool EmittedUseCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00002264 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00002265 if (NodeHasChain)
2266 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00002267 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00002268 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattner8a0604b2006-01-28 20:31:24 +00002269 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002270 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002271 EmittedUseCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002272 if (NodeHasChain) {
Evan Chenge41bf822006-02-05 06:43:12 +00002273 // If the immediate use can somehow reach this node through another
2274 // path, then can't fold it either or it will create a cycle.
2275 // e.g. In the following diagram, XX can reach ld through YY. If
2276 // ld is folded into XX, then YY is both a predecessor and a successor
2277 // of XX.
2278 //
2279 // [ld]
2280 // ^ ^
2281 // | |
2282 // / \---
2283 // / [YY]
2284 // | ^
2285 // [XX]-------|
2286 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2287 if (PInfo.getNumOperands() > 1 ||
Evan Cheng94b30402006-10-11 21:02:01 +00002288 PInfo.hasProperty(SDNPHasChain) ||
2289 PInfo.hasProperty(SDNPInFlag) ||
2290 PInfo.hasProperty(SDNPOptInFlag)) {
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002291 std::string ParentName(RootName.begin(), RootName.end()-1);
Chris Lattner706d2d32006-08-09 16:44:44 +00002292 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
2293 ".Val)");
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002294 }
Evan Chenge41bf822006-02-05 06:43:12 +00002295 }
Evan Chengb915f312005-12-09 22:45:35 +00002296 }
Evan Chenge41bf822006-02-05 06:43:12 +00002297
Evan Chengc15d18c2006-01-27 22:13:45 +00002298 if (NodeHasChain) {
Evan Cheng4326ef52006-10-12 02:08:53 +00002299 if (FoundChain) {
2300 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
2301 "IsChainCompatible(" + ChainName + ".Val, " +
2302 RootName + ".Val))");
2303 OrigChains.push_back(std::make_pair(ChainName, RootName));
2304 } else
Evan Chenge6389932006-07-21 22:19:51 +00002305 FoundChain = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002306 ChainName = "Chain" + ChainSuffix;
Evan Cheng676d7312006-08-26 00:59:04 +00002307 emitInit("SDOperand " + ChainName + " = " + RootName +
Evan Chenge6389932006-07-21 22:19:51 +00002308 ".getOperand(0);");
Evan Cheng1cf6db22006-01-06 00:41:12 +00002309 }
Evan Chengb915f312005-12-09 22:45:35 +00002310 }
2311
Evan Cheng54597732006-01-26 00:22:25 +00002312 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002313 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002314 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002315 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2316 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002317 if (!isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002318 (PatternHasProperty(N, SDNPInFlag, ISE) ||
2319 PatternHasProperty(N, SDNPOptInFlag, ISE) ||
2320 PatternHasProperty(N, SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002321 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2322 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002323 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002324 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002325 }
2326 }
2327
Evan Chengd3eea902006-10-09 21:02:17 +00002328 // If there is a node predicate for this, emit the call.
2329 if (!N->getPredicateFn().empty())
2330 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2331
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002332
Chris Lattner39e73f72006-10-11 04:05:55 +00002333 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
2334 // a constant without a predicate fn that has more that one bit set, handle
2335 // this as a special case. This is usually for targets that have special
2336 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
2337 // handling stuff). Using these instructions is often far more efficient
2338 // than materializing the constant. Unfortunately, both the instcombiner
2339 // and the dag combiner can often infer that bits are dead, and thus drop
2340 // them from the mask in the dag. For example, it might turn 'AND X, 255'
2341 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
2342 // to handle this.
2343 if (!N->isLeaf() &&
2344 (N->getOperator()->getName() == "and" ||
2345 N->getOperator()->getName() == "or") &&
2346 N->getChild(1)->isLeaf() &&
2347 N->getChild(1)->getPredicateFn().empty()) {
2348 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
2349 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
2350 emitInit("SDOperand " + RootName + "0" + " = " +
2351 RootName + ".getOperand(" + utostr(0) + ");");
2352 emitInit("SDOperand " + RootName + "1" + " = " +
2353 RootName + ".getOperand(" + utostr(1) + ");");
2354
2355 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
2356 const char *MaskPredicate = N->getOperator()->getName() == "or"
2357 ? "CheckOrMask(" : "CheckAndMask(";
2358 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
2359 RootName + "1), " + itostr(II->getValue()) + ")");
2360
2361 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
2362 ChainSuffix + utostr(0), FoundChain);
2363 return;
2364 }
2365 }
2366 }
2367
Evan Chengb915f312005-12-09 22:45:35 +00002368 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng676d7312006-08-26 00:59:04 +00002369 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002370 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002371
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002372 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
2373 ChainSuffix + utostr(OpNo), FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002374 }
2375
Evan Cheng676d7312006-08-26 00:59:04 +00002376 // Handle cases when root is a complex pattern.
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002377 const ComplexPattern *CP;
Evan Cheng676d7312006-08-26 00:59:04 +00002378 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2379 std::string Fn = CP->getSelectFunc();
2380 unsigned NumOps = CP->getNumOperands();
2381 for (unsigned i = 0; i < NumOps; ++i) {
2382 emitDecl("CPTmp" + utostr(i));
2383 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2384 }
Evan Cheng94b30402006-10-11 21:02:01 +00002385 if (CP->hasProperty(SDNPHasChain)) {
2386 emitDecl("CPInChain");
2387 emitDecl("Chain" + ChainSuffix);
2388 emitCode("SDOperand CPInChain;");
2389 emitCode("SDOperand Chain" + ChainSuffix + ";");
2390 }
Evan Cheng676d7312006-08-26 00:59:04 +00002391
2392 std::string Code = Fn + "(" + RootName;
2393 for (unsigned i = 0; i < NumOps; i++)
2394 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +00002395 if (CP->hasProperty(SDNPHasChain)) {
2396 ChainName = "Chain" + ChainSuffix;
2397 Code += ", CPInChain, Chain" + ChainSuffix;
2398 }
Evan Cheng676d7312006-08-26 00:59:04 +00002399 emitCheck(Code + ")");
2400 }
Evan Chengb915f312005-12-09 22:45:35 +00002401 }
Chris Lattner39e73f72006-10-11 04:05:55 +00002402
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002403 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
2404 const std::string &RootName,
2405 const std::string &ChainSuffix, bool &FoundChain) {
2406 if (!Child->isLeaf()) {
2407 // If it's not a leaf, recursively match.
2408 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2409 emitCheck(RootName + ".getOpcode() == " +
2410 CInfo.getEnumName());
2411 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Evan Cheng94b30402006-10-11 21:02:01 +00002412 if (NodeHasProperty(Child, SDNPHasChain, ISE))
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002413 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
2414 } else {
2415 // If this child has a name associated with it, capture it in VarMap. If
2416 // we already saw this in the pattern, emit code to verify dagness.
2417 if (!Child->getName().empty()) {
2418 std::string &VarMapEntry = VariableMap[Child->getName()];
2419 if (VarMapEntry.empty()) {
2420 VarMapEntry = RootName;
2421 } else {
2422 // If we get here, this is a second reference to a specific name.
2423 // Since we already have checked that the first reference is valid,
2424 // we don't have to recursively match it, just check that it's the
2425 // same as the previously named thing.
2426 emitCheck(VarMapEntry + " == " + RootName);
2427 Duplicates.insert(RootName);
2428 return;
2429 }
2430 }
2431
2432 // Handle leaves of various types.
2433 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2434 Record *LeafRec = DI->getDef();
2435 if (LeafRec->isSubClassOf("RegisterClass")) {
2436 // Handle register references. Nothing to do here.
2437 } else if (LeafRec->isSubClassOf("Register")) {
2438 // Handle register references.
2439 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2440 // Handle complex pattern.
2441 const ComplexPattern *CP = NodeGetComplexPattern(Child, ISE);
2442 std::string Fn = CP->getSelectFunc();
2443 unsigned NumOps = CP->getNumOperands();
2444 for (unsigned i = 0; i < NumOps; ++i) {
2445 emitDecl("CPTmp" + utostr(i));
2446 emitCode("SDOperand CPTmp" + utostr(i) + ";");
2447 }
Evan Cheng94b30402006-10-11 21:02:01 +00002448 if (CP->hasProperty(SDNPHasChain)) {
2449 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(Parent->getOperator());
2450 FoldedChains.push_back(std::make_pair("CPInChain",
2451 PInfo.getNumResults()));
2452 ChainName = "Chain" + ChainSuffix;
2453 emitDecl("CPInChain");
2454 emitDecl(ChainName);
2455 emitCode("SDOperand CPInChain;");
2456 emitCode("SDOperand " + ChainName + ";");
2457 }
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002458
2459 std::string Code = Fn + "(" + RootName;
2460 for (unsigned i = 0; i < NumOps; i++)
2461 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +00002462 if (CP->hasProperty(SDNPHasChain))
2463 Code += ", CPInChain, Chain" + ChainSuffix;
Chris Lattnerbe8e7212006-10-11 03:35:34 +00002464 emitCheck(Code + ")");
2465 } else if (LeafRec->getName() == "srcvalue") {
2466 // Place holder for SRCVALUE nodes. Nothing to do here.
2467 } else if (LeafRec->isSubClassOf("ValueType")) {
2468 // Make sure this is the specified value type.
2469 emitCheck("cast<VTSDNode>(" + RootName +
2470 ")->getVT() == MVT::" + LeafRec->getName());
2471 } else if (LeafRec->isSubClassOf("CondCode")) {
2472 // Make sure this is the specified cond code.
2473 emitCheck("cast<CondCodeSDNode>(" + RootName +
2474 ")->get() == ISD::" + LeafRec->getName());
2475 } else {
2476#ifndef NDEBUG
2477 Child->dump();
2478 std::cerr << " ";
2479#endif
2480 assert(0 && "Unknown leaf type!");
2481 }
2482
2483 // If there is a node predicate for this, emit the call.
2484 if (!Child->getPredicateFn().empty())
2485 emitCheck(Child->getPredicateFn() + "(" + RootName +
2486 ".Val)");
2487 } else if (IntInit *II =
2488 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2489 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
2490 unsigned CTmp = TmpNo++;
2491 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2492 RootName + ")->getSignExtended();");
2493
2494 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2495 } else {
2496#ifndef NDEBUG
2497 Child->dump();
2498#endif
2499 assert(0 && "Unknown leaf type!");
2500 }
2501 }
2502 }
Evan Chengb915f312005-12-09 22:45:35 +00002503
2504 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2505 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +00002506 std::vector<std::string>
2507 EmitResultCode(TreePatternNode *N, bool RetSelected,
2508 bool InFlagDecled, bool ResNodeDecled,
2509 bool LikeLeaf = false, bool isRoot = false) {
2510 // List of arguments of getTargetNode() or SelectNodeTo().
2511 std::vector<std::string> NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002512 // This is something selected from the pattern we matched.
2513 if (!N->getName().empty()) {
Evan Chengb915f312005-12-09 22:45:35 +00002514 std::string &Val = VariableMap[N->getName()];
2515 assert(!Val.empty() &&
2516 "Variable referenced but not defined and not caught earlier!");
2517 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2518 // Already selected this operand, just return the tmpval.
Evan Cheng676d7312006-08-26 00:59:04 +00002519 NodeOps.push_back(Val);
2520 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002521 }
2522
2523 const ComplexPattern *CP;
2524 unsigned ResNo = TmpNo++;
Evan Chengb915f312005-12-09 22:45:35 +00002525 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002526 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002527 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002528 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002529 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002530 case MVT::i1: CastType = "bool"; break;
2531 case MVT::i8: CastType = "unsigned char"; break;
2532 case MVT::i16: CastType = "unsigned short"; break;
2533 case MVT::i32: CastType = "unsigned"; break;
2534 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002535 }
Evan Cheng676d7312006-08-26 00:59:04 +00002536 emitCode("SDOperand Tmp" + utostr(ResNo) +
Evan Chengfceb57a2006-07-15 08:45:20 +00002537 " = CurDAG->getTargetConstant(((" + CastType +
2538 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2539 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002540 NodeOps.push_back("Tmp" + utostr(ResNo));
2541 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2542 // value if used multiple times by this pattern result.
2543 Val = "Tmp"+utostr(ResNo);
Evan Chengbb48e332006-01-12 07:54:57 +00002544 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002545 Record *Op = OperatorMap[N->getName()];
2546 // Transform ExternalSymbol to TargetExternalSymbol
2547 if (Op && Op->getName() == "externalsym") {
Evan Cheng676d7312006-08-26 00:59:04 +00002548 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002549 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002550 Val + ")->getSymbol(), " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002551 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002552 NodeOps.push_back("Tmp" + utostr(ResNo));
Chris Lattner64906972006-09-21 18:28:27 +00002553 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2554 // this value if used multiple times by this pattern result.
Evan Cheng676d7312006-08-26 00:59:04 +00002555 Val = "Tmp"+utostr(ResNo);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002556 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002557 NodeOps.push_back(Val);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002558 }
Evan Chengb915f312005-12-09 22:45:35 +00002559 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002560 Record *Op = OperatorMap[N->getName()];
2561 // Transform GlobalAddress to TargetGlobalAddress
2562 if (Op && Op->getName() == "globaladdr") {
Evan Cheng676d7312006-08-26 00:59:04 +00002563 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002564 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
Evan Cheng2618d072006-05-17 20:37:59 +00002565 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002566 ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002567 NodeOps.push_back("Tmp" + utostr(ResNo));
Chris Lattner64906972006-09-21 18:28:27 +00002568 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
2569 // this value if used multiple times by this pattern result.
Evan Cheng676d7312006-08-26 00:59:04 +00002570 Val = "Tmp"+utostr(ResNo);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002571 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002572 NodeOps.push_back(Val);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002573 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002574 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng676d7312006-08-26 00:59:04 +00002575 NodeOps.push_back(Val);
2576 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2577 // value if used multiple times by this pattern result.
2578 Val = "Tmp"+utostr(ResNo);
Evan Chengbb48e332006-01-12 07:54:57 +00002579 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng676d7312006-08-26 00:59:04 +00002580 NodeOps.push_back(Val);
2581 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2582 // value if used multiple times by this pattern result.
2583 Val = "Tmp"+utostr(ResNo);
Evan Chengb915f312005-12-09 22:45:35 +00002584 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2585 std::string Fn = CP->getSelectFunc();
Evan Cheng676d7312006-08-26 00:59:04 +00002586 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
2587 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
2588 NodeOps.push_back("CPTmp" + utostr(i));
Evan Chengb0793f92006-05-25 00:21:44 +00002589 }
Evan Chengb915f312005-12-09 22:45:35 +00002590 } else {
Evan Cheng676d7312006-08-26 00:59:04 +00002591 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
Evan Cheng863bf5a2006-03-20 22:53:06 +00002592 // node even if it isn't one. Don't select it.
Evan Cheng676d7312006-08-26 00:59:04 +00002593 if (!LikeLeaf) {
2594 emitCode("AddToISelQueue(" + Val + ");");
Chris Lattner706d2d32006-08-09 16:44:44 +00002595 if (isRoot && N->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00002596 emitCode("ReplaceUses(N, " + Val + ");");
Evan Cheng06d64702006-08-11 08:59:35 +00002597 emitCode("return NULL;");
Chris Lattner706d2d32006-08-09 16:44:44 +00002598 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00002599 }
Evan Cheng676d7312006-08-26 00:59:04 +00002600 NodeOps.push_back(Val);
Evan Chengb915f312005-12-09 22:45:35 +00002601 }
Evan Cheng676d7312006-08-26 00:59:04 +00002602 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002603 }
Evan Chengb915f312005-12-09 22:45:35 +00002604 if (N->isLeaf()) {
2605 // If this is an explicit register reference, handle it.
2606 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2607 unsigned ResNo = TmpNo++;
2608 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng676d7312006-08-26 00:59:04 +00002609 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002610 ISE.getQualifiedName(DI->getDef()) + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002611 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002612 NodeOps.push_back("Tmp" + utostr(ResNo));
2613 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002614 }
2615 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2616 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002617 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng676d7312006-08-26 00:59:04 +00002618 emitCode("SDOperand Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002619 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
Evan Cheng2618d072006-05-17 20:37:59 +00002620 ", " + getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002621 NodeOps.push_back("Tmp" + utostr(ResNo));
2622 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002623 }
2624
Jim Laskey16d42c62006-07-11 18:25:13 +00002625#ifndef NDEBUG
2626 N->dump();
2627#endif
Evan Chengb915f312005-12-09 22:45:35 +00002628 assert(0 && "Unknown leaf type!");
Evan Cheng676d7312006-08-26 00:59:04 +00002629 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002630 }
2631
2632 Record *Op = N->getOperator();
2633 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002634 const CodeGenTarget &CGT = ISE.getTargetInfo();
2635 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002636 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng045953c2006-05-10 00:05:46 +00002637 TreePattern *InstPat = Inst.getPattern();
2638 TreePatternNode *InstPatNode =
2639 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2640 : (InstPat ? InstPat->getOnlyTree() : NULL);
2641 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2642 InstPatNode = InstPatNode->getChild(1);
2643 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002644 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
Evan Cheng045953c2006-05-10 00:05:46 +00002645 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2646 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2647 bool NodeHasOptInFlag = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002648 PatternHasProperty(Pattern, SDNPOptInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002649 bool NodeHasInFlag = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002650 PatternHasProperty(Pattern, SDNPInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002651 bool NodeHasOutFlag = HasImpResults || (isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002652 PatternHasProperty(Pattern, SDNPOutFlag, ISE));
Evan Cheng045953c2006-05-10 00:05:46 +00002653 bool NodeHasChain = InstPatNode &&
Evan Cheng94b30402006-10-11 21:02:01 +00002654 PatternHasProperty(InstPatNode, SDNPHasChain, ISE);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002655 bool InputHasChain = isRoot &&
Evan Cheng94b30402006-10-11 21:02:01 +00002656 NodeHasProperty(Pattern, SDNPHasChain, ISE);
Evan Cheng4fba2812005-12-20 07:37:41 +00002657
Evan Chengfceb57a2006-07-15 08:45:20 +00002658 if (NodeHasOptInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +00002659 emitCode("bool HasInFlag = "
Evan Chengf8729402006-07-16 06:12:52 +00002660 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
Evan Chengfceb57a2006-07-15 08:45:20 +00002661 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002662 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00002663 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
Evan Cheng4fba2812005-12-20 07:37:41 +00002664
Evan Cheng823b7522006-01-19 21:57:10 +00002665 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002666 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002667 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2668 MVT::ValueType VT = Pattern->getTypeNum(i);
2669 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002670 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002671 }
2672
Evan Cheng4326ef52006-10-12 02:08:53 +00002673 if (OrigChains.size() > 0) {
2674 // The original input chain is being ignored. If it is not just
2675 // pointing to the op that's being folded, we should create a
2676 // TokenFactor with it and the chain of the folded op as the new chain.
2677 // We could potentially be doing multiple levels of folding, in that
2678 // case, the TokenFactor can have more operands.
2679 emitCode("SmallVector<SDOperand, 8> InChains;");
2680 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
2681 emitCode("if (" + OrigChains[i].first + ".Val != " +
2682 OrigChains[i].second + ".Val) {");
2683 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
2684 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
2685 emitCode("}");
2686 }
2687 emitCode("AddToISelQueue(" + ChainName + ");");
2688 emitCode("InChains.push_back(" + ChainName + ");");
2689 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
2690 "&InChains[0], InChains.size());");
2691 }
2692
Evan Cheng676d7312006-08-26 00:59:04 +00002693 std::vector<std::string> AllOps;
Evan Chengb915f312005-12-09 22:45:35 +00002694 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Evan Cheng676d7312006-08-26 00:59:04 +00002695 std::vector<std::string> Ops = EmitResultCode(N->getChild(i),
2696 RetSelected, InFlagDecled, ResNodeDecled);
2697 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
Evan Chengb915f312005-12-09 22:45:35 +00002698 }
2699
Evan Chengb915f312005-12-09 22:45:35 +00002700 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +00002701 bool ChainEmitted = NodeHasChain;
2702 if (NodeHasChain)
Evan Cheng676d7312006-08-26 00:59:04 +00002703 emitCode("AddToISelQueue(" + ChainName + ");");
Evan Chengbc6b86a2006-06-14 19:27:50 +00002704 if (NodeHasInFlag || HasImpInputs)
Evan Cheng676d7312006-08-26 00:59:04 +00002705 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
2706 InFlagDecled, ResNodeDecled, true);
Evan Chengf037ca62006-08-27 08:11:28 +00002707 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
Evan Cheng676d7312006-08-26 00:59:04 +00002708 if (!InFlagDecled) {
2709 emitCode("SDOperand InFlag(0, 0);");
2710 InFlagDecled = true;
2711 }
Evan Chengf037ca62006-08-27 08:11:28 +00002712 if (NodeHasOptInFlag) {
2713 emitCode("if (HasInFlag) {");
2714 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
2715 emitCode(" AddToISelQueue(InFlag);");
2716 emitCode("}");
2717 }
Evan Chengbc6b86a2006-06-14 19:27:50 +00002718 }
Evan Chengb915f312005-12-09 22:45:35 +00002719
Evan Chengb915f312005-12-09 22:45:35 +00002720 unsigned NumResults = Inst.getNumResults();
2721 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002722 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2723 NodeHasOptInFlag) {
Evan Chenge945f4d2006-06-14 22:22:20 +00002724 std::string Code;
2725 std::string Code2;
2726 std::string NodeName;
2727 if (!isRoot) {
2728 NodeName = "Tmp" + utostr(ResNo);
Evan Cheng676d7312006-08-26 00:59:04 +00002729 Code2 = "SDOperand " + NodeName + " = SDOperand(";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002730 } else {
Evan Chenge945f4d2006-06-14 22:22:20 +00002731 NodeName = "ResNode";
Evan Cheng676d7312006-08-26 00:59:04 +00002732 if (!ResNodeDecled)
2733 Code2 = "SDNode *" + NodeName + " = ";
2734 else
2735 Code2 = NodeName + " = ";
Evan Chengbcecf332005-12-17 01:19:28 +00002736 }
Evan Chengf037ca62006-08-27 08:11:28 +00002737
Evan Chengfceb57a2006-07-15 08:45:20 +00002738 Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
Evan Chengf037ca62006-08-27 08:11:28 +00002739 unsigned OpsNo = OpcNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002740 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
Evan Chenge945f4d2006-06-14 22:22:20 +00002741
2742 // Output order: results, chain, flags
2743 // Result types.
Evan Chengf8729402006-07-16 06:12:52 +00002744 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2745 Code += ", VT" + utostr(VTNo);
2746 emitVT(getEnumName(N->getTypeNum(0)));
2747 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002748 if (NodeHasChain)
2749 Code += ", MVT::Other";
2750 if (NodeHasOutFlag)
2751 Code += ", MVT::Flag";
2752
2753 // Inputs.
Evan Chengf037ca62006-08-27 08:11:28 +00002754 if (HasVarOps) {
2755 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
2756 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
2757 AllOps.clear();
Evan Chenge945f4d2006-06-14 22:22:20 +00002758 }
2759
2760 if (HasVarOps) {
2761 if (NodeHasInFlag || HasImpInputs)
2762 emitCode("for (unsigned i = 2, e = N.getNumOperands()-1; "
2763 "i != e; ++i) {");
2764 else if (NodeHasOptInFlag)
Evan Chengfceb57a2006-07-15 08:45:20 +00002765 emitCode("for (unsigned i = 2, e = N.getNumOperands()-"
2766 "(HasInFlag?1:0); i != e; ++i) {");
Evan Chenge945f4d2006-06-14 22:22:20 +00002767 else
2768 emitCode("for (unsigned i = 2, e = N.getNumOperands(); "
2769 "i != e; ++i) {");
Evan Cheng676d7312006-08-26 00:59:04 +00002770 emitCode(" AddToISelQueue(N.getOperand(i));");
Evan Chengf037ca62006-08-27 08:11:28 +00002771 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
Evan Chenge945f4d2006-06-14 22:22:20 +00002772 emitCode("}");
2773 }
2774
2775 if (NodeHasChain) {
2776 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00002777 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
Evan Chenge945f4d2006-06-14 22:22:20 +00002778 else
Evan Chengf037ca62006-08-27 08:11:28 +00002779 AllOps.push_back(ChainName);
Evan Chenge945f4d2006-06-14 22:22:20 +00002780 }
2781
Evan Chengf037ca62006-08-27 08:11:28 +00002782 if (HasVarOps) {
2783 if (NodeHasInFlag || HasImpInputs)
2784 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2785 else if (NodeHasOptInFlag) {
2786 emitCode("if (HasInFlag)");
2787 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
2788 }
2789 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
2790 ".size()";
2791 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2792 AllOps.push_back("InFlag");
Evan Chenge945f4d2006-06-14 22:22:20 +00002793
Evan Chengf037ca62006-08-27 08:11:28 +00002794 unsigned NumOps = AllOps.size();
2795 if (NumOps) {
2796 if (!NodeHasOptInFlag && NumOps < 4) {
2797 for (unsigned i = 0; i != NumOps; ++i)
2798 Code += ", " + AllOps[i];
2799 } else {
2800 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
2801 for (unsigned i = 0; i != NumOps; ++i) {
2802 OpsCode += AllOps[i];
2803 if (i != NumOps-1)
2804 OpsCode += ", ";
2805 }
2806 emitCode(OpsCode + " };");
2807 Code += ", Ops" + utostr(OpsNo) + ", ";
2808 if (NodeHasOptInFlag) {
2809 Code += "HasInFlag ? ";
2810 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
2811 } else
2812 Code += utostr(NumOps);
2813 }
2814 }
2815
Evan Chenge945f4d2006-06-14 22:22:20 +00002816 if (!isRoot)
2817 Code += "), 0";
2818 emitCode(Code2 + Code + ");");
2819
2820 if (NodeHasChain)
2821 // Remember which op produces the chain.
2822 if (!isRoot)
2823 emitCode(ChainName + " = SDOperand(" + NodeName +
2824 ".Val, " + utostr(PatResults) + ");");
2825 else
2826 emitCode(ChainName + " = SDOperand(" + NodeName +
2827 ", " + utostr(PatResults) + ");");
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002828
Evan Cheng676d7312006-08-26 00:59:04 +00002829 if (!isRoot) {
2830 NodeOps.push_back("Tmp" + utostr(ResNo));
2831 return NodeOps;
2832 }
Evan Cheng045953c2006-05-10 00:05:46 +00002833
Evan Cheng06d64702006-08-11 08:59:35 +00002834 bool NeedReplace = false;
Evan Cheng676d7312006-08-26 00:59:04 +00002835 if (NodeHasOutFlag) {
2836 if (!InFlagDecled) {
2837 emitCode("SDOperand InFlag = SDOperand(ResNode, " +
2838 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2839 InFlagDecled = true;
2840 } else
2841 emitCode("InFlag = SDOperand(ResNode, " +
2842 utostr(NumResults + (unsigned)NodeHasChain) + ");");
2843 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002844
Evan Cheng676d7312006-08-26 00:59:04 +00002845 if (HasImpResults && EmitCopyFromRegs(N, ResNodeDecled, ChainEmitted)) {
Chris Lattner706d2d32006-08-09 16:44:44 +00002846 emitCode("ReplaceUses(SDOperand(N.Val, 0), SDOperand(ResNode, 0));");
Evan Chenged66e852006-03-09 08:19:11 +00002847 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00002848 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002849
Evan Cheng97938882005-12-22 02:24:50 +00002850 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002851 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002852 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Chris Lattner706d2d32006-08-09 16:44:44 +00002853 emitCode("ReplaceUses(SDOperand(" +
Evan Cheng67212a02006-02-09 22:12:27 +00002854 FoldedChains[j].first + ".Val, " +
Chris Lattner706d2d32006-08-09 16:44:44 +00002855 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
2856 utostr(NumResults) + "));");
Evan Cheng06d64702006-08-11 08:59:35 +00002857 NeedReplace = true;
Evan Chengb915f312005-12-09 22:45:35 +00002858 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002859
Evan Cheng06d64702006-08-11 08:59:35 +00002860 if (NodeHasOutFlag) {
Chris Lattner706d2d32006-08-09 16:44:44 +00002861 emitCode("ReplaceUses(SDOperand(N.Val, " +
2862 utostr(PatResults + (unsigned)InputHasChain) +"), InFlag);");
Evan Cheng06d64702006-08-11 08:59:35 +00002863 NeedReplace = true;
2864 }
2865
2866 if (NeedReplace) {
2867 for (unsigned i = 0; i < NumResults; i++)
2868 emitCode("ReplaceUses(SDOperand(N.Val, " +
2869 utostr(i) + "), SDOperand(ResNode, " + utostr(i) + "));");
2870 if (InputHasChain)
2871 emitCode("ReplaceUses(SDOperand(N.Val, " +
Chris Lattner64906972006-09-21 18:28:27 +00002872 utostr(PatResults) + "), SDOperand(" + ChainName + ".Val, "
2873 + ChainName + ".ResNo" + "));");
Evan Chengf037ca62006-08-27 08:11:28 +00002874 } else
Evan Cheng06d64702006-08-11 08:59:35 +00002875 RetSelected = true;
Evan Cheng97938882005-12-22 02:24:50 +00002876
Evan Chenged66e852006-03-09 08:19:11 +00002877 // User does not expect the instruction would produce a chain!
Evan Cheng06d64702006-08-11 08:59:35 +00002878 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
Evan Cheng9ade2182006-08-26 05:34:46 +00002879 ;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002880 } else if (InputHasChain && !NodeHasChain) {
2881 // One of the inner node produces a chain.
Evan Cheng9ade2182006-08-26 05:34:46 +00002882 if (NodeHasOutFlag)
Evan Cheng06d64702006-08-11 08:59:35 +00002883 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults+1) +
2884 "), SDOperand(ResNode, N.ResNo-1));");
Evan Cheng06d64702006-08-11 08:59:35 +00002885 for (unsigned i = 0; i < PatResults; ++i)
2886 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(i) +
2887 "), SDOperand(ResNode, " + utostr(i) + "));");
2888 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(PatResults) +
2889 "), " + ChainName + ");");
2890 RetSelected = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002891 }
Evan Cheng06d64702006-08-11 08:59:35 +00002892
2893 if (RetSelected)
Evan Cheng9ade2182006-08-26 05:34:46 +00002894 emitCode("return ResNode;");
Evan Cheng06d64702006-08-11 08:59:35 +00002895 else
2896 emitCode("return NULL;");
Evan Chengb915f312005-12-09 22:45:35 +00002897 } else {
Evan Cheng9ade2182006-08-26 05:34:46 +00002898 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
Evan Chengfceb57a2006-07-15 08:45:20 +00002899 utostr(OpcNo);
Nate Begemanb73628b2005-12-30 00:12:56 +00002900 if (N->getTypeNum(0) != MVT::isVoid)
Evan Chengf8729402006-07-16 06:12:52 +00002901 Code += ", VT" + utostr(VTNo);
Evan Cheng54597732006-01-26 00:22:25 +00002902 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002903 Code += ", MVT::Flag";
Evan Chengf037ca62006-08-27 08:11:28 +00002904
2905 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
2906 AllOps.push_back("InFlag");
2907
2908 unsigned NumOps = AllOps.size();
2909 if (NumOps) {
2910 if (!NodeHasOptInFlag && NumOps < 4) {
2911 for (unsigned i = 0; i != NumOps; ++i)
2912 Code += ", " + AllOps[i];
2913 } else {
2914 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
2915 for (unsigned i = 0; i != NumOps; ++i) {
2916 OpsCode += AllOps[i];
2917 if (i != NumOps-1)
2918 OpsCode += ", ";
2919 }
2920 emitCode(OpsCode + " };");
2921 Code += ", Ops" + utostr(OpcNo) + ", ";
2922 Code += utostr(NumOps);
2923 }
2924 }
Evan Cheng95514ba2006-08-26 08:00:10 +00002925 emitCode(Code + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00002926 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
2927 if (N->getTypeNum(0) != MVT::isVoid)
2928 emitVT(getEnumName(N->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002929 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002930
Evan Cheng676d7312006-08-26 00:59:04 +00002931 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002932 } else if (Op->isSubClassOf("SDNodeXForm")) {
2933 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00002934 // PatLeaf node - the operand may or may not be a leaf node. But it should
2935 // behave like one.
Evan Cheng676d7312006-08-26 00:59:04 +00002936 std::vector<std::string> Ops =
2937 EmitResultCode(N->getChild(0), RetSelected, InFlagDecled,
2938 ResNodeDecled, true);
Evan Chengb915f312005-12-09 22:45:35 +00002939 unsigned ResNo = TmpNo++;
Evan Cheng676d7312006-08-26 00:59:04 +00002940 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2941 + "(" + Ops.back() + ".Val);");
2942 NodeOps.push_back("Tmp" + utostr(ResNo));
Evan Cheng9ade2182006-08-26 05:34:46 +00002943 if (isRoot)
2944 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00002945 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00002946 } else {
2947 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002948 std::cerr << "\n";
2949 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002950 }
2951 }
2952
Chris Lattner488580c2006-01-28 19:06:51 +00002953 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2954 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002955 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2956 /// for, this returns true otherwise false if Pat has all types.
2957 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +00002958 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002959 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +00002960 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +00002961 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002962 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +00002963 // The top level node type is checked outside of the select function.
2964 if (!isRoot)
2965 emitCheck(Prefix + ".Val->getValueType(0) == " +
2966 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002967 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002968 }
2969
Evan Cheng51fecc82006-01-09 18:27:06 +00002970 unsigned OpNo =
Evan Cheng94b30402006-10-11 21:02:01 +00002971 (unsigned) NodeHasProperty(Pat, SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002972 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2973 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2974 Prefix + utostr(OpNo)))
2975 return true;
2976 return false;
2977 }
2978
2979private:
Evan Cheng54597732006-01-26 00:22:25 +00002980 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002981 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002982 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +00002983 bool &ChainEmitted, bool &InFlagDecled,
2984 bool &ResNodeDecled, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002985 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002986 unsigned OpNo =
Evan Cheng94b30402006-10-11 21:02:01 +00002987 (unsigned) NodeHasProperty(N, SDNPHasChain, ISE);
2988 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002989 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2990 TreePatternNode *Child = N->getChild(i);
2991 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00002992 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
2993 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +00002994 } else {
2995 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002996 if (!Child->getName().empty()) {
2997 std::string Name = RootName + utostr(OpNo);
2998 if (Duplicates.find(Name) != Duplicates.end())
2999 // A duplicate! Do not emit a copy for this node.
3000 continue;
3001 }
3002
Evan Chengb915f312005-12-09 22:45:35 +00003003 Record *RR = DI->getDef();
3004 if (RR->isSubClassOf("Register")) {
3005 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00003006 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +00003007 if (!InFlagDecled) {
3008 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
3009 InFlagDecled = true;
3010 } else
3011 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
3012 emitCode("AddToISelQueue(InFlag);");
Evan Chengb2c6d492006-01-11 22:16:13 +00003013 } else {
3014 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00003015 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00003016 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00003017 ChainEmitted = true;
3018 }
Evan Cheng676d7312006-08-26 00:59:04 +00003019 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
3020 if (!InFlagDecled) {
3021 emitCode("SDOperand InFlag(0, 0);");
3022 InFlagDecled = true;
3023 }
3024 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3025 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Cheng7a33db02006-08-26 07:39:28 +00003026 ", " + ISE.getQualifiedName(RR) +
3027 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00003028 ResNodeDecled = true;
Evan Cheng67212a02006-02-09 22:12:27 +00003029 emitCode(ChainName + " = SDOperand(ResNode, 0);");
3030 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00003031 }
3032 }
3033 }
3034 }
3035 }
Evan Cheng54597732006-01-26 00:22:25 +00003036
Evan Cheng676d7312006-08-26 00:59:04 +00003037 if (HasInFlag) {
3038 if (!InFlagDecled) {
3039 emitCode("SDOperand InFlag = " + RootName +
3040 ".getOperand(" + utostr(OpNo) + ");");
3041 InFlagDecled = true;
3042 } else
3043 emitCode("InFlag = " + RootName +
3044 ".getOperand(" + utostr(OpNo) + ");");
3045 emitCode("AddToISelQueue(InFlag);");
3046 }
Evan Chengb915f312005-12-09 22:45:35 +00003047 }
Evan Cheng4fba2812005-12-20 07:37:41 +00003048
3049 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00003050 /// as specified by the instruction. It returns true if any copy is
3051 /// emitted.
Evan Cheng676d7312006-08-26 00:59:04 +00003052 bool EmitCopyFromRegs(TreePatternNode *N, bool &ResNodeDecled,
3053 bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00003054 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00003055 Record *Op = N->getOperator();
3056 if (Op->isSubClassOf("Instruction")) {
3057 const DAGInstruction &Inst = ISE.getInstruction(Op);
3058 const CodeGenTarget &CGT = ISE.getTargetInfo();
Evan Cheng4fba2812005-12-20 07:37:41 +00003059 unsigned NumImpResults = Inst.getNumImpResults();
3060 for (unsigned i = 0; i < NumImpResults; i++) {
3061 Record *RR = Inst.getImpResult(i);
3062 if (RR->isSubClassOf("Register")) {
3063 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
3064 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00003065 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00003066 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00003067 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00003068 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00003069 }
Evan Cheng676d7312006-08-26 00:59:04 +00003070 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
3071 emitCode(Decl + "ResNode = CurDAG->getCopyFromReg(" + ChainName +
Evan Chengfceb57a2006-07-15 08:45:20 +00003072 ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00003073 ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00003074 ResNodeDecled = true;
Evan Chengd7805a72006-02-09 07:16:09 +00003075 emitCode(ChainName + " = SDOperand(ResNode, 1);");
3076 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00003077 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00003078 }
3079 }
3080 }
3081 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00003082 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00003083 }
Evan Chengb915f312005-12-09 22:45:35 +00003084};
3085
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00003086/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
3087/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00003088/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00003089void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00003090 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00003091 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00003092 std::vector<std::string> &TargetOpcodes,
Evan Chengf5493192006-08-26 01:02:19 +00003093 std::vector<std::string> &TargetVTs) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003094 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
3095 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00003096 GeneratedCode, GeneratedDecl,
Chris Lattner706d2d32006-08-09 16:44:44 +00003097 TargetOpcodes, TargetVTs);
Evan Chengb915f312005-12-09 22:45:35 +00003098
Chris Lattner8fc35682005-09-23 23:16:51 +00003099 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00003100 bool FoundChain = false;
Chris Lattnerbe8e7212006-10-11 03:35:34 +00003101 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00003102
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003103 // TP - Get *SOME* tree pattern, we don't care which.
3104 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00003105
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003106 // At this point, we know that we structurally match the pattern, but the
3107 // types of the nodes may not match. Figure out the fewest number of type
3108 // comparisons we need to emit. For example, if there is only one integer
3109 // type supported by a target, there should be no type comparisons at all for
3110 // integer patterns!
3111 //
3112 // To figure out the fewest number of type checks needed, clone the pattern,
3113 // remove the types, then perform type inference on the pattern as a whole.
3114 // If there are unresolved types, emit an explicit check for those types,
3115 // apply the type to the tree, then rerun type inference. Iterate until all
3116 // types are resolved.
3117 //
Evan Cheng58e84a62005-12-14 22:02:59 +00003118 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003119 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00003120
3121 do {
3122 // Resolve/propagate as many types as possible.
3123 try {
3124 bool MadeChange = true;
3125 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00003126 MadeChange = Pat->ApplyTypeConstraints(TP,
3127 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00003128 } catch (...) {
3129 assert(0 && "Error: could not find consistent types for something we"
3130 " already decided was ok!");
3131 abort();
3132 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003133
Chris Lattner7e82f132005-10-15 21:34:21 +00003134 // Insert a check for an unresolved type and add it to the tree. If we find
3135 // an unresolved type to add a check for, this returns true and we iterate,
3136 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00003137 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00003138
Evan Cheng676d7312006-08-26 00:59:04 +00003139 Emitter.EmitResultCode(Pattern.getDstPattern(),
3140 false, false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003141 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00003142}
3143
Chris Lattner24e00a42006-01-29 04:41:05 +00003144/// EraseCodeLine - Erase one code line from all of the patterns. If removing
3145/// a line causes any of them to be empty, remove them and return true when
3146/// done.
3147static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00003148 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00003149 &Patterns) {
3150 bool ErasedPatterns = false;
3151 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3152 Patterns[i].second.pop_back();
3153 if (Patterns[i].second.empty()) {
3154 Patterns.erase(Patterns.begin()+i);
3155 --i; --e;
3156 ErasedPatterns = true;
3157 }
3158 }
3159 return ErasedPatterns;
3160}
3161
Chris Lattner8bc74722006-01-29 04:25:26 +00003162/// EmitPatterns - Emit code for at least one pattern, but try to group common
3163/// code together between the patterns.
3164void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00003165 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00003166 &Patterns, unsigned Indent,
3167 std::ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00003168 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00003169 typedef std::vector<CodeLine> CodeList;
3170 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3171
3172 if (Patterns.empty()) return;
3173
Chris Lattner24e00a42006-01-29 04:41:05 +00003174 // Figure out how many patterns share the next code line. Explicitly copy
3175 // FirstCodeLine so that we don't invalidate a reference when changing
3176 // Patterns.
3177 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00003178 unsigned LastMatch = Patterns.size()-1;
3179 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3180 --LastMatch;
3181
3182 // If not all patterns share this line, split the list into two pieces. The
3183 // first chunk will use this line, the second chunk won't.
3184 if (LastMatch != 0) {
3185 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3186 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3187
3188 // FIXME: Emit braces?
3189 if (Shared.size() == 1) {
3190 PatternToMatch &Pattern = *Shared.back().first;
3191 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3192 Pattern.getSrcPattern()->print(OS);
3193 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3194 Pattern.getDstPattern()->print(OS);
3195 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003196 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003197 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003198 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003199 << " cost = "
Evan Chenge6f32032006-07-19 00:24:41 +00003200 << getResultPatternCost(Pattern.getDstPattern(), *this)
3201 << " size = "
3202 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003203 }
Evan Cheng676d7312006-08-26 00:59:04 +00003204 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00003205 OS << std::string(Indent, ' ') << "{\n";
3206 Indent += 2;
3207 }
3208 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00003209 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00003210 Indent -= 2;
3211 OS << std::string(Indent, ' ') << "}\n";
3212 }
3213
3214 if (Other.size() == 1) {
3215 PatternToMatch &Pattern = *Other.back().first;
3216 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3217 Pattern.getSrcPattern()->print(OS);
3218 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3219 Pattern.getDstPattern()->print(OS);
3220 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003221 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003222 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003223 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003224 << " cost = "
Chris Lattner706d2d32006-08-09 16:44:44 +00003225 << getResultPatternCost(Pattern.getDstPattern(), *this)
3226 << " size = "
3227 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003228 }
3229 EmitPatterns(Other, Indent, OS);
3230 return;
3231 }
3232
Chris Lattner24e00a42006-01-29 04:41:05 +00003233 // Remove this code from all of the patterns that share it.
3234 bool ErasedPatterns = EraseCodeLine(Patterns);
3235
Evan Cheng676d7312006-08-26 00:59:04 +00003236 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00003237
3238 // Otherwise, every pattern in the list has this line. Emit it.
3239 if (!isPredicate) {
3240 // Normal code.
3241 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3242 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00003243 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3244
3245 // If the next code line is another predicate, and if all of the pattern
3246 // in this group share the same next line, emit it inline now. Do this
3247 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00003248 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Chris Lattner24e00a42006-01-29 04:41:05 +00003249 // Check that all of fhe patterns in Patterns end with the same predicate.
3250 bool AllEndWithSamePredicate = true;
3251 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3252 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3253 AllEndWithSamePredicate = false;
3254 break;
3255 }
3256 // If all of the predicates aren't the same, we can't share them.
3257 if (!AllEndWithSamePredicate) break;
3258
3259 // Otherwise we can. Emit it shared now.
3260 OS << " &&\n" << std::string(Indent+4, ' ')
3261 << Patterns.back().second.back().second;
3262 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00003263 }
Chris Lattner24e00a42006-01-29 04:41:05 +00003264
3265 OS << ") {\n";
3266 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00003267 }
3268
3269 EmitPatterns(Patterns, Indent, OS);
3270
3271 if (isPredicate)
3272 OS << std::string(Indent-2, ' ') << "}\n";
3273}
3274
3275
Chris Lattner37481472005-09-26 21:59:35 +00003276
3277namespace {
3278 /// CompareByRecordName - An ordering predicate that implements less-than by
3279 /// comparing the names records.
3280 struct CompareByRecordName {
3281 bool operator()(const Record *LHS, const Record *RHS) const {
3282 // Sort by name first.
3283 if (LHS->getName() < RHS->getName()) return true;
3284 // If both names are equal, sort by pointer.
3285 return LHS->getName() == RHS->getName() && LHS < RHS;
3286 }
3287 };
3288}
3289
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003290void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003291 std::string InstNS = Target.inst_begin()->second.Namespace;
3292 if (!InstNS.empty()) InstNS += "::";
3293
Chris Lattner602f6922006-01-04 00:25:00 +00003294 // Group the patterns by their top-level opcodes.
3295 std::map<Record*, std::vector<PatternToMatch*>,
3296 CompareByRecordName> PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00003297 // All unique target node emission functions.
3298 std::map<std::string, unsigned> EmitFunctions;
Chris Lattner602f6922006-01-04 00:25:00 +00003299 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3300 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3301 if (!Node->isLeaf()) {
3302 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3303 } else {
3304 const ComplexPattern *CP;
3305 if (IntInit *II =
3306 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3307 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3308 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3309 std::vector<Record*> OpNodes = CP->getRootNodes();
3310 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00003311 PatternsByOpcode[OpNodes[j]]
3312 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003313 }
3314 } else {
3315 std::cerr << "Unrecognized opcode '";
3316 Node->dump();
3317 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00003318 std::cerr <<
3319 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00003320 std::cerr << "'!\n";
3321 exit(1);
3322 }
3323 }
3324 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003325
3326 // For each opcode, there might be multiple select functions, one per
3327 // ValueType of the node (or its first operand if it doesn't produce a
3328 // non-chain result.
3329 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
3330
Chris Lattner602f6922006-01-04 00:25:00 +00003331 // Emit one Select_* method for each top-level opcode. We do this instead of
3332 // emitting one giant switch statement to support compilers where this will
3333 // result in the recursive functions taking less stack space.
3334 for (std::map<Record*, std::vector<PatternToMatch*>,
3335 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3336 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00003337 const std::string &OpName = PBOI->first->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00003338 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner706d2d32006-08-09 16:44:44 +00003339 std::vector<PatternToMatch*> &PatternsOfOp = PBOI->second;
3340 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
3341
Chris Lattner602f6922006-01-04 00:25:00 +00003342 // We want to emit all of the matching code now. However, we want to emit
3343 // the matches in order of minimal cost. Sort the patterns so the least
3344 // cost one is at the start.
Chris Lattner706d2d32006-08-09 16:44:44 +00003345 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner602f6922006-01-04 00:25:00 +00003346 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00003347
Chris Lattner706d2d32006-08-09 16:44:44 +00003348 // Split them into groups by type.
3349 std::map<MVT::ValueType, std::vector<PatternToMatch*> > PatternsByType;
3350 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
3351 PatternToMatch *Pat = PatternsOfOp[i];
3352 TreePatternNode *SrcPat = Pat->getSrcPattern();
3353 if (OpcodeInfo.getNumResults() == 0 && SrcPat->getNumChildren() > 0)
3354 SrcPat = SrcPat->getChild(0);
3355 MVT::ValueType VT = SrcPat->getTypeNum(0);
3356 std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator TI =
3357 PatternsByType.find(VT);
3358 if (TI != PatternsByType.end())
3359 TI->second.push_back(Pat);
3360 else {
3361 std::vector<PatternToMatch*> PVec;
3362 PVec.push_back(Pat);
3363 PatternsByType.insert(std::make_pair(VT, PVec));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003364 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003365 }
3366
3367 for (std::map<MVT::ValueType, std::vector<PatternToMatch*> >::iterator
3368 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
3369 ++II) {
3370 MVT::ValueType OpVT = II->first;
3371 std::vector<PatternToMatch*> &Patterns = II->second;
Chris Lattner64906972006-09-21 18:28:27 +00003372 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
3373 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00003374
3375 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3376 std::vector<std::vector<std::string> > PatternOpcodes;
3377 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00003378 std::vector<std::set<std::string> > PatternDecls;
Chris Lattner706d2d32006-08-09 16:44:44 +00003379 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3380 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00003381 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00003382 std::vector<std::string> TargetOpcodes;
3383 std::vector<std::string> TargetVTs;
3384 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3385 TargetOpcodes, TargetVTs);
Chris Lattner706d2d32006-08-09 16:44:44 +00003386 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3387 PatternDecls.push_back(GeneratedDecl);
3388 PatternOpcodes.push_back(TargetOpcodes);
3389 PatternVTs.push_back(TargetVTs);
3390 }
3391
3392 // Scan the code to see if all of the patterns are reachable and if it is
3393 // possible that the last one might not match.
3394 bool mightNotMatch = true;
3395 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3396 CodeList &GeneratedCode = CodeForPatterns[i].second;
3397 mightNotMatch = false;
3398
3399 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
Evan Cheng676d7312006-08-26 00:59:04 +00003400 if (GeneratedCode[j].first == 1) { // predicate.
Chris Lattner706d2d32006-08-09 16:44:44 +00003401 mightNotMatch = true;
3402 break;
3403 }
3404 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003405
Chris Lattner706d2d32006-08-09 16:44:44 +00003406 // If this pattern definitely matches, and if it isn't the last one, the
3407 // patterns after it CANNOT ever match. Error out.
3408 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3409 std::cerr << "Pattern '";
Evan Cheng676d7312006-08-26 00:59:04 +00003410 CodeForPatterns[i].first->getSrcPattern()->print(std::cerr);
Chris Lattner706d2d32006-08-09 16:44:44 +00003411 std::cerr << "' is impossible to select!\n";
3412 exit(1);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003413 }
3414 }
3415
Chris Lattner706d2d32006-08-09 16:44:44 +00003416 // Factor target node emission code (emitted by EmitResultCode) into
3417 // separate functions. Uniquing and share them among all instruction
3418 // selection routines.
3419 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3420 CodeList &GeneratedCode = CodeForPatterns[i].second;
3421 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
3422 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00003423 std::set<std::string> Decls = PatternDecls[i];
Evan Cheng676d7312006-08-26 00:59:04 +00003424 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00003425 int CodeSize = (int)GeneratedCode.size();
3426 int LastPred = -1;
3427 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00003428 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00003429 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00003430 else if (LastPred != -1 && GeneratedCode[j].first == 2)
3431 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00003432 }
3433
Evan Cheng9ade2182006-08-26 05:34:46 +00003434 std::string CalleeCode = "(const SDOperand &N";
3435 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00003436 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3437 CalleeCode += ", unsigned Opc" + utostr(j);
3438 CallerCode += ", " + TargetOpcodes[j];
3439 }
3440 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3441 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3442 CallerCode += ", " + TargetVTs[j];
3443 }
Evan Chengf5493192006-08-26 01:02:19 +00003444 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00003445 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00003446 std::string Name = *I;
Evan Cheng676d7312006-08-26 00:59:04 +00003447 CalleeCode += ", SDOperand &" + Name;
3448 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00003449 }
3450 CallerCode += ");";
3451 CalleeCode += ") ";
3452 // Prevent emission routines from being inlined to reduce selection
3453 // routines stack frame sizes.
Chris Lattner8dc728e2006-08-27 13:16:24 +00003454 CalleeCode += "DISABLE_INLINE ";
Evan Cheng676d7312006-08-26 00:59:04 +00003455 CalleeCode += "{\n";
3456
3457 for (std::vector<std::string>::const_reverse_iterator
3458 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
3459 CalleeCode += " " + *I + "\n";
3460
Evan Chengf5493192006-08-26 01:02:19 +00003461 for (int j = LastPred+1; j < CodeSize; ++j)
3462 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003463 for (int j = LastPred+1; j < CodeSize; ++j)
3464 GeneratedCode.pop_back();
3465 CalleeCode += "}\n";
3466
3467 // Uniquing the emission routines.
3468 unsigned EmitFuncNum;
3469 std::map<std::string, unsigned>::iterator EFI =
3470 EmitFunctions.find(CalleeCode);
3471 if (EFI != EmitFunctions.end()) {
3472 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003473 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00003474 EmitFuncNum = EmitFunctions.size();
3475 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Evan Cheng06d64702006-08-11 08:59:35 +00003476 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003477 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003478
Chris Lattner706d2d32006-08-09 16:44:44 +00003479 // Replace the emission code within selection routines with calls to the
3480 // emission functions.
Evan Cheng06d64702006-08-11 08:59:35 +00003481 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
Chris Lattner706d2d32006-08-09 16:44:44 +00003482 GeneratedCode.push_back(std::make_pair(false, CallerCode));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003483 }
3484
Chris Lattner706d2d32006-08-09 16:44:44 +00003485 // Print function.
3486 std::string OpVTStr = (OpVT != MVT::isVoid && OpVT != MVT::iPTR)
3487 ? getEnumName(OpVT).substr(5) : "" ;
3488 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3489 OpcodeVTMap.find(OpName);
3490 if (OpVTI == OpcodeVTMap.end()) {
3491 std::vector<std::string> VTSet;
3492 VTSet.push_back(OpVTStr);
3493 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
3494 } else
3495 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003496
Evan Cheng06d64702006-08-11 08:59:35 +00003497 OS << "SDNode *Select_" << OpName << (OpVTStr != "" ? "_" : "")
Evan Cheng9ade2182006-08-26 05:34:46 +00003498 << OpVTStr << "(const SDOperand &N) {\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003499
Chris Lattner706d2d32006-08-09 16:44:44 +00003500 // Loop through and reverse all of the CodeList vectors, as we will be
3501 // accessing them from their logical front, but accessing the end of a
3502 // vector is more efficient.
3503 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3504 CodeList &GeneratedCode = CodeForPatterns[i].second;
3505 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003506 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003507
3508 // Next, reverse the list of patterns itself for the same reason.
3509 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3510
3511 // Emit all of the patterns now, grouped together to share code.
3512 EmitPatterns(CodeForPatterns, 2, OS);
3513
Chris Lattner64906972006-09-21 18:28:27 +00003514 // If the last pattern has predicates (which could fail) emit code to
3515 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00003516 if (mightNotMatch) {
3517 OS << " std::cerr << \"Cannot yet select: \";\n";
3518 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3519 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3520 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3521 OS << " N.Val->dump(CurDAG);\n";
3522 } else {
3523 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3524 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3525 << " std::cerr << \"intrinsic %\"<< "
3526 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3527 }
3528 OS << " std::cerr << '\\n';\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003529 << " abort();\n"
3530 << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003531 }
3532 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003533 }
Chris Lattner602f6922006-01-04 00:25:00 +00003534 }
3535
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003536 // Emit boilerplate.
Evan Cheng9ade2182006-08-26 05:34:46 +00003537 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003538 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003539 << " AddToISelQueue(N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003540 << " // Select the flag operand.\n"
3541 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003542 << " AddToISelQueue(Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00003543 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003544 << " std::vector<MVT::ValueType> VTs;\n"
3545 << " VTs.push_back(MVT::Other);\n"
3546 << " VTs.push_back(MVT::Flag);\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00003547 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
3548 "Ops.size());\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003549 << " return New.Val;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003550 << "}\n\n";
3551
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003552 OS << "// The main instruction selector code.\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003553 << "SDNode *SelectCode(SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003554 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003555 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003556 << "INSTRUCTION_LIST_END)) {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003557 << " return NULL; // Already selected.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003558 << " }\n\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003559 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003560 << " default: break;\n"
3561 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003562 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003563 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003564 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003565 << " case ISD::TargetConstant:\n"
3566 << " case ISD::TargetConstantPool:\n"
3567 << " case ISD::TargetFrameIndex:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00003568 << " case ISD::TargetJumpTable:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003569 << " case ISD::TargetGlobalAddress: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003570 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003571 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003572 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003573 << " case ISD::AssertZext: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003574 << " AddToISelQueue(N.getOperand(0));\n"
3575 << " ReplaceUses(N, N.getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003576 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003577 << " }\n"
3578 << " case ISD::TokenFactor:\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00003579 << " case ISD::CopyFromReg:\n"
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003580 << " case ISD::CopyToReg: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00003581 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
3582 << " AddToISelQueue(N.getOperand(i));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003583 << " return NULL;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003584 << " }\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00003585 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003586
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003587
Chris Lattner602f6922006-01-04 00:25:00 +00003588 // Loop over all of the case statements, emiting a call to each method we
3589 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003590 for (std::map<Record*, std::vector<PatternToMatch*>,
3591 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3592 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003593 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner706d2d32006-08-09 16:44:44 +00003594 const std::string &OpName = PBOI->first->getName();
3595 // Potentially multiple versions of select for this opcode. One for each
3596 // ValueType of the node (or its first true operand if it doesn't produce a
3597 // result.
3598 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
3599 OpcodeVTMap.find(OpName);
3600 std::vector<std::string> &OpVTs = OpVTI->second;
3601 OS << " case " << OpcodeInfo.getEnumName() << ": {\n";
3602 if (OpVTs.size() == 1) {
3603 std::string &VTStr = OpVTs[0];
Evan Cheng06d64702006-08-11 08:59:35 +00003604 OS << " return Select_" << OpName
Evan Cheng9ade2182006-08-26 05:34:46 +00003605 << (VTStr != "" ? "_" : "") << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003606 } else {
3607 if (OpcodeInfo.getNumResults())
3608 OS << " MVT::ValueType NVT = N.Val->getValueType(0);\n";
Evan Cheng94b30402006-10-11 21:02:01 +00003609 else if (OpcodeInfo.hasProperty(SDNPHasChain))
Chris Lattner706d2d32006-08-09 16:44:44 +00003610 OS << " MVT::ValueType NVT = (N.getNumOperands() > 1) ?"
3611 << " N.getOperand(1).Val->getValueType(0) : MVT::isVoid;\n";
3612 else
3613 OS << " MVT::ValueType NVT = (N.getNumOperands() > 0) ?"
3614 << " N.getOperand(0).Val->getValueType(0) : MVT::isVoid;\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003615 int Default = -1;
3616 OS << " switch (NVT) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003617 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
3618 std::string &VTStr = OpVTs[i];
3619 if (VTStr == "") {
Evan Cheng06d64702006-08-11 08:59:35 +00003620 Default = i;
Chris Lattner706d2d32006-08-09 16:44:44 +00003621 continue;
3622 }
Evan Cheng06d64702006-08-11 08:59:35 +00003623 OS << " case MVT::" << VTStr << ":\n"
3624 << " return Select_" << OpName
Evan Cheng9ade2182006-08-26 05:34:46 +00003625 << "_" << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003626 }
Evan Cheng06d64702006-08-11 08:59:35 +00003627 OS << " default:\n";
3628 if (Default != -1)
Evan Cheng9ade2182006-08-26 05:34:46 +00003629 OS << " return Select_" << OpName << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003630 else
Evan Cheng06d64702006-08-11 08:59:35 +00003631 OS << " break;\n";
3632 OS << " }\n";
3633 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003634 }
Chris Lattner706d2d32006-08-09 16:44:44 +00003635 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00003636 }
Chris Lattner81303322005-09-23 19:36:15 +00003637
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003638 OS << " } // end of big switch.\n\n"
3639 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00003640 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3641 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3642 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003643 << " N.Val->dump(CurDAG);\n"
3644 << " } else {\n"
3645 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3646 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3647 << " std::cerr << \"intrinsic %\"<< "
3648 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3649 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003650 << " std::cerr << '\\n';\n"
3651 << " abort();\n"
Evan Cheng06d64702006-08-11 08:59:35 +00003652 << " return NULL;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003653 << "}\n";
3654}
3655
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003656void DAGISelEmitter::run(std::ostream &OS) {
3657 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3658 " target", OS);
3659
Chris Lattner1f39e292005-09-14 00:09:24 +00003660 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3661 << "// *** instruction selector class. These functions are really "
3662 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003663
Chris Lattner8dc728e2006-08-27 13:16:24 +00003664 OS << "#include \"llvm/Support/Compiler.h\"\n";
Evan Cheng233baf12006-07-26 23:06:27 +00003665
Chris Lattner706d2d32006-08-09 16:44:44 +00003666 OS << "// Instruction selector priority queue:\n"
3667 << "std::vector<SDNode*> ISelQueue;\n";
3668 OS << "/// Keep track of nodes which have already been added to queue.\n"
3669 << "unsigned char *ISelQueued;\n";
3670 OS << "/// Keep track of nodes which have already been selected.\n"
3671 << "unsigned char *ISelSelected;\n";
3672 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
3673 << "std::vector<SDNode*> ISelKilled;\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003674
Evan Cheng4326ef52006-10-12 02:08:53 +00003675 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
3676 OS << "/// not reach Op.\n";
3677 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
3678 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
3679 OS << " return true;\n";
3680 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
3681 OS << " return false;\n";
3682 OS << " else if (Chain->getNumOperands() > 0) {\n";
3683 OS << " SDOperand C0 = Chain->getOperand(0);\n";
3684 OS << " if (C0.getValueType() == MVT::Other)\n";
3685 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
3686 OS << " }\n";
3687 OS << " return true;\n";
3688 OS << "}\n";
3689
Chris Lattner706d2d32006-08-09 16:44:44 +00003690 OS << "/// Sorting functions for the selection queue.\n"
3691 << "struct isel_sort : public std::binary_function"
3692 << "<SDNode*, SDNode*, bool> {\n"
3693 << " bool operator()(const SDNode* left, const SDNode* right) "
3694 << "const {\n"
3695 << " return (left->getNodeId() > right->getNodeId());\n"
3696 << " }\n"
3697 << "};\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003698
Chris Lattner706d2d32006-08-09 16:44:44 +00003699 OS << "inline void setQueued(int Id) {\n";
3700 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003701 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003702 OS << "inline bool isQueued(int Id) {\n";
3703 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003704 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003705 OS << "inline void setSelected(int Id) {\n";
3706 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003707 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003708 OS << "inline bool isSelected(int Id) {\n";
3709 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
3710 OS << "}\n\n";
Evan Cheng9bdca032006-08-07 22:17:58 +00003711
Chris Lattner8dc728e2006-08-27 13:16:24 +00003712 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003713 OS << " int Id = N.Val->getNodeId();\n";
3714 OS << " if (Id != -1 && !isQueued(Id)) {\n";
3715 OS << " ISelQueue.push_back(N.Val);\n";
3716 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3717 OS << " setQueued(Id);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003718 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003719 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00003720
Chris Lattner706d2d32006-08-09 16:44:44 +00003721 OS << "inline void RemoveKilled() {\n";
3722OS << " unsigned NumKilled = ISelKilled.size();\n";
3723 OS << " if (NumKilled) {\n";
3724 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
3725 OS << " SDNode *Temp = ISelKilled[i];\n";
3726 OS << " std::remove(ISelQueue.begin(), ISelQueue.end(), Temp);\n";
3727 OS << " };\n";
3728 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3729 OS << " ISelKilled.clear();\n";
3730 OS << " }\n";
3731 OS << "}\n\n";
3732
Chris Lattner8dc728e2006-08-27 13:16:24 +00003733 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003734 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, ISelKilled);\n";
3735 OS << " setSelected(F.Val->getNodeId());\n";
3736 OS << " RemoveKilled();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003737 OS << "}\n";
3738 OS << "inline void ReplaceUses(SDNode *F, SDNode *T) {\n";
3739 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
3740 OS << " setSelected(F->getNodeId());\n";
3741 OS << " RemoveKilled();\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003742 OS << "}\n\n";
3743
Evan Cheng966fd372006-09-11 02:24:43 +00003744 OS << "void DeleteNode(SDNode *N) {\n";
3745 OS << " CurDAG->DeleteNode(N);\n";
3746 OS << " for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); "
3747 << "I != E; ++I) {\n";
3748 OS << " SDNode *Operand = I->Val;\n";
3749 OS << " if (Operand->use_empty())\n";
3750 OS << " DeleteNode(Operand);\n";
3751 OS << " }\n";
3752 OS << "}\n";
3753
Evan Chenge41bf822006-02-05 06:43:12 +00003754 OS << "// SelectRoot - Top level entry to DAG isel.\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003755 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
3756 OS << " SelectRootInit();\n";
3757 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
3758 OS << " ISelQueued = new unsigned char[NumBytes];\n";
3759 OS << " ISelSelected = new unsigned char[NumBytes];\n";
3760 OS << " memset(ISelQueued, 0, NumBytes);\n";
3761 OS << " memset(ISelSelected, 0, NumBytes);\n";
3762 OS << "\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00003763 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
3764 << " // a reference to the root node, preventing it from being deleted,\n"
3765 << " // and tracking any changes of the root.\n"
3766 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
3767 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003768 OS << " while (!ISelQueue.empty()) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003769 OS << " SDNode *Node = ISelQueue.front();\n";
3770 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
3771 OS << " ISelQueue.pop_back();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003772 OS << " if (!isSelected(Node->getNodeId())) {\n";
Evan Cheng9ade2182006-08-26 05:34:46 +00003773 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
Evan Cheng966fd372006-09-11 02:24:43 +00003774 OS << " if (ResNode != Node) {\n";
3775 OS << " if (ResNode)\n";
3776 OS << " ReplaceUses(Node, ResNode);\n";
3777 OS << " if (Node->use_empty()) // Don't delete EntryToken, etc.\n";
3778 OS << " DeleteNode(Node);\n";
3779 OS << " }\n";
Evan Cheng06d64702006-08-11 08:59:35 +00003780 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00003781 OS << " }\n";
3782 OS << "\n";
3783 OS << " delete[] ISelQueued;\n";
3784 OS << " ISelQueued = NULL;\n";
3785 OS << " delete[] ISelSelected;\n";
3786 OS << " ISelSelected = NULL;\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00003787 OS << " return Dummy.getValue();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003788 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003789
Chris Lattner550525e2006-03-24 21:48:51 +00003790 Intrinsics = LoadIntrinsics(Records);
Chris Lattnerca559d02005-09-08 21:03:01 +00003791 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003792 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003793 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003794 ParsePatternFragments(OS);
3795 ParseInstructions();
3796 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003797
Chris Lattnere97603f2005-09-28 19:27:25 +00003798 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003799 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003800 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003801
Chris Lattnere46e17b2005-09-29 19:28:10 +00003802
3803 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3804 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003805 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3806 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003807 std::cerr << "\n";
3808 });
3809
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003810 // At this point, we have full information about the 'Patterns' we need to
3811 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003812 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003813 EmitInstructionSelector(OS);
3814
3815 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3816 E = PatternFragments.end(); I != E; ++I)
3817 delete I->second;
3818 PatternFragments.clear();
3819
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003820 Instructions.clear();
3821}