blob: 5983fb7c020637ec502586987bc632ce51c23b56 [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000018#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000019#include <set>
20using namespace llvm;
21
Chris Lattnerca559d02005-09-08 21:03:01 +000022//===----------------------------------------------------------------------===//
Chris Lattner3c7e18d2005-10-14 06:12:03 +000023// Helpers for working with extended types.
24
25/// FilterVTs - Filter a list of VT's according to a predicate.
26///
27template<typename T>
28static std::vector<MVT::ValueType>
29FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32 if (Filter(InVTs[i]))
33 Result.push_back(InVTs[i]);
34 return Result;
35}
36
Nate Begemanb73628b2005-12-30 00:12:56 +000037template<typename T>
38static std::vector<unsigned char>
39FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40 std::vector<unsigned char> Result;
41 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42 if (Filter((MVT::ValueType)InVTs[i]))
43 Result.push_back(InVTs[i]);
44 return Result;
Chris Lattner3c7e18d2005-10-14 06:12:03 +000045}
46
Nate Begemanb73628b2005-12-30 00:12:56 +000047static std::vector<unsigned char>
48ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49 std::vector<unsigned char> Result;
50 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51 Result.push_back(InVTs[i]);
52 return Result;
53}
54
55static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56 const std::vector<unsigned char> &RHS) {
57 if (LHS.size() > RHS.size()) return false;
58 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
Duraid Madinad47ae092005-12-30 16:41:48 +000059 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
Nate Begemanb73628b2005-12-30 00:12:56 +000060 return false;
61 return true;
62}
63
64/// isExtIntegerVT - Return true if the specified extended value type vector
65/// contains isInt or an integer value type.
Chris Lattner697f8842006-03-20 05:39:48 +000066static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000067 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
69}
70
71/// isExtFloatingPointVT - Return true if the specified extended value type
72/// vector contains isFP or a FP value type.
Chris Lattner697f8842006-03-20 05:39:48 +000073static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000074 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
Chris Lattner488580c2006-01-28 19:06:51 +000075 return EVTs[0] == MVT::isFP ||
76 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
Chris Lattner3c7e18d2005-10-14 06:12:03 +000077}
78
79//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000080// SDTypeConstraint implementation
81//
82
83SDTypeConstraint::SDTypeConstraint(Record *R) {
84 OperandNo = R->getValueAsInt("OperandNum");
85
86 if (R->isSubClassOf("SDTCisVT")) {
87 ConstraintType = SDTCisVT;
88 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattner5b21be72005-12-09 22:57:42 +000089 } else if (R->isSubClassOf("SDTCisPtrTy")) {
90 ConstraintType = SDTCisPtrTy;
Chris Lattner33c92e92005-09-08 21:27:15 +000091 } else if (R->isSubClassOf("SDTCisInt")) {
92 ConstraintType = SDTCisInt;
93 } else if (R->isSubClassOf("SDTCisFP")) {
94 ConstraintType = SDTCisFP;
95 } else if (R->isSubClassOf("SDTCisSameAs")) {
96 ConstraintType = SDTCisSameAs;
97 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99 ConstraintType = SDTCisVTSmallerThanOp;
100 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
101 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +0000102 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103 ConstraintType = SDTCisOpSmallerThanOp;
104 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
105 R->getValueAsInt("BigOperandNum");
Chris Lattner697f8842006-03-20 05:39:48 +0000106 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107 ConstraintType = SDTCisIntVectorOfSameSize;
108 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109 R->getValueAsInt("OtherOpNum");
Chris Lattner33c92e92005-09-08 21:27:15 +0000110 } else {
111 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
112 exit(1);
113 }
114}
115
Chris Lattner32707602005-09-08 23:22:48 +0000116/// getOperandNum - Return the node corresponding to operand #OpNo in tree
117/// N, which has NumResults results.
118TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
119 TreePatternNode *N,
120 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000121 assert(NumResults <= 1 &&
122 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000123
Evan Cheng50c997e2006-06-13 21:47:27 +0000124 if (OpNo >= (NumResults + N->getNumChildren())) {
125 std::cerr << "Invalid operand number " << OpNo << " ";
126 N->dump();
127 std::cerr << '\n';
128 exit(1);
129 }
130
Chris Lattner32707602005-09-08 23:22:48 +0000131 if (OpNo < NumResults)
132 return N; // FIXME: need value #
133 else
134 return N->getChild(OpNo-NumResults);
135}
136
137/// ApplyTypeConstraint - Given a node in a pattern, apply this type
138/// constraint to the nodes operands. This returns true if it makes a
139/// change, false otherwise. If a type contradiction is found, throw an
140/// exception.
141bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
142 const SDNodeInfo &NodeInfo,
143 TreePattern &TP) const {
144 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000145 assert(NumResults <= 1 &&
146 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000147
Chris Lattner8f60d542006-06-16 18:25:06 +0000148 // Check that the number of operands is sane. Negative operands -> varargs.
Chris Lattner32707602005-09-08 23:22:48 +0000149 if (NodeInfo.getNumOperands() >= 0) {
150 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
151 TP.error(N->getOperator()->getName() + " node requires exactly " +
152 itostr(NodeInfo.getNumOperands()) + " operands!");
153 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000154
155 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000156
157 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
158
159 switch (ConstraintType) {
160 default: assert(0 && "Unknown constraint type!");
161 case SDTCisVT:
162 // Operand must be a particular type.
163 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000164 case SDTCisPtrTy: {
165 // Operand must be same as target pointer type.
Evan Cheng2618d072006-05-17 20:37:59 +0000166 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000167 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000168 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000169 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000170 std::vector<MVT::ValueType> IntVTs =
171 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000172
173 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000174 if (IntVTs.size() == 1)
175 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000176 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000177 }
178 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000179 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000180 std::vector<MVT::ValueType> FPVTs =
181 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000182
183 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000184 if (FPVTs.size() == 1)
185 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000186 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000187 }
Chris Lattner32707602005-09-08 23:22:48 +0000188 case SDTCisSameAs: {
189 TreePatternNode *OtherNode =
190 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000191 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
192 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000193 }
194 case SDTCisVTSmallerThanOp: {
195 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
196 // have an integer type that is smaller than the VT.
197 if (!NodeToApply->isLeaf() ||
198 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
199 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
200 ->isSubClassOf("ValueType"))
201 TP.error(N->getOperator()->getName() + " expects a VT operand!");
202 MVT::ValueType VT =
203 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
204 if (!MVT::isInteger(VT))
205 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
206
207 TreePatternNode *OtherNode =
208 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000209
210 // It must be integer.
211 bool MadeChange = false;
212 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
213
Nate Begemanb73628b2005-12-30 00:12:56 +0000214 // This code only handles nodes that have one type set. Assert here so
215 // that we can change this if we ever need to deal with multiple value
216 // types at this point.
217 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
218 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000219 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
220 return false;
221 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000222 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000223 TreePatternNode *BigOperand =
224 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
225
226 // Both operands must be integer or FP, but we don't care which.
227 bool MadeChange = false;
228
Nate Begemanb73628b2005-12-30 00:12:56 +0000229 // This code does not currently handle nodes which have multiple types,
230 // where some types are integer, and some are fp. Assert that this is not
231 // the case.
232 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
233 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
234 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
235 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
236 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
237 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000238 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000239 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000240 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000241 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000242 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000243 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000244 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
245
246 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
247
Nate Begemanb73628b2005-12-30 00:12:56 +0000248 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000249 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000250 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000251 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
252 } else {
253 VTs.clear();
254 }
255
256 switch (VTs.size()) {
257 default: // Too many VT's to pick from.
258 case 0: break; // No info yet.
259 case 1:
260 // Only one VT of this flavor. Cannot ever satisify the constraints.
261 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
262 case 2:
263 // If we have exactly two possible types, the little operand must be the
264 // small one, the big operand should be the big one. Common with
265 // float/double for example.
266 assert(VTs[0] < VTs[1] && "Should be sorted!");
267 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
268 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
269 break;
270 }
271 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000272 }
Chris Lattner697f8842006-03-20 05:39:48 +0000273 case SDTCisIntVectorOfSameSize: {
274 TreePatternNode *OtherOperand =
275 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
276 N, NumResults);
277 if (OtherOperand->hasTypeSet()) {
278 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
279 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
280 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
281 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
282 return NodeToApply->UpdateNodeType(IVT, TP);
283 }
284 return false;
285 }
Chris Lattner32707602005-09-08 23:22:48 +0000286 }
287 return false;
288}
289
290
Chris Lattner33c92e92005-09-08 21:27:15 +0000291//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000292// SDNodeInfo implementation
293//
294SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
295 EnumName = R->getValueAsString("Opcode");
296 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000297 Record *TypeProfile = R->getValueAsDef("TypeProfile");
298 NumResults = TypeProfile->getValueAsInt("NumResults");
299 NumOperands = TypeProfile->getValueAsInt("NumOperands");
300
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000301 // Parse the properties.
302 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000303 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000304 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
305 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000306 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000307 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000308 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000309 } else if (PropList[i]->getName() == "SDNPHasChain") {
310 Properties |= 1 << SDNPHasChain;
Evan Cheng51fecc82006-01-09 18:27:06 +0000311 } else if (PropList[i]->getName() == "SDNPOutFlag") {
312 Properties |= 1 << SDNPOutFlag;
313 } else if (PropList[i]->getName() == "SDNPInFlag") {
314 Properties |= 1 << SDNPInFlag;
315 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
316 Properties |= 1 << SDNPOptInFlag;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000317 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000318 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000319 << "' on node '" << R->getName() << "'!\n";
320 exit(1);
321 }
322 }
323
324
Chris Lattner33c92e92005-09-08 21:27:15 +0000325 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000326 std::vector<Record*> ConstraintList =
327 TypeProfile->getValueAsListOfDefs("Constraints");
328 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000329}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000330
331//===----------------------------------------------------------------------===//
332// TreePatternNode implementation
333//
334
335TreePatternNode::~TreePatternNode() {
336#if 0 // FIXME: implement refcounted tree nodes!
337 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
338 delete getChild(i);
339#endif
340}
341
Chris Lattner32707602005-09-08 23:22:48 +0000342/// UpdateNodeType - Set the node type of N to VT if VT contains
343/// information. If N already contains a conflicting type, then throw an
344/// exception. This returns true if any information was updated.
345///
Nate Begemanb73628b2005-12-30 00:12:56 +0000346bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
347 TreePattern &TP) {
348 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
349
350 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
351 return false;
352 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
353 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000354 return true;
355 }
Evan Cheng2618d072006-05-17 20:37:59 +0000356
357 if (getExtTypeNum(0) == MVT::iPTR) {
358 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
359 return false;
360 if (isExtIntegerInVTs(ExtVTs)) {
361 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
362 if (FVTs.size()) {
363 setTypes(ExtVTs);
364 return true;
365 }
366 }
367 }
Chris Lattner32707602005-09-08 23:22:48 +0000368
Nate Begemanb73628b2005-12-30 00:12:56 +0000369 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
370 assert(hasTypeSet() && "should be handled above!");
371 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
372 if (getExtTypes() == FVTs)
373 return false;
374 setTypes(FVTs);
375 return true;
376 }
Evan Cheng2618d072006-05-17 20:37:59 +0000377 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
378 //assert(hasTypeSet() && "should be handled above!");
379 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
380 if (getExtTypes() == FVTs)
381 return false;
382 if (FVTs.size()) {
383 setTypes(FVTs);
384 return true;
385 }
386 }
Nate Begemanb73628b2005-12-30 00:12:56 +0000387 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
388 assert(hasTypeSet() && "should be handled above!");
Chris Lattner488580c2006-01-28 19:06:51 +0000389 std::vector<unsigned char> FVTs =
390 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
Nate Begemanb73628b2005-12-30 00:12:56 +0000391 if (getExtTypes() == FVTs)
392 return false;
393 setTypes(FVTs);
394 return true;
395 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000396
397 // If we know this is an int or fp type, and we are told it is a specific one,
398 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000399 //
400 // Similarly, we should probably set the type here to the intersection of
401 // {isInt|isFP} and ExtVTs
402 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
403 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
404 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000405 return true;
Evan Cheng2618d072006-05-17 20:37:59 +0000406 }
407 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
408 setTypes(ExtVTs);
409 return true;
410 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000411
Chris Lattner1531f202005-10-26 16:59:37 +0000412 if (isLeaf()) {
413 dump();
Evan Chengbcecf332005-12-17 01:19:28 +0000414 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000415 TP.error("Type inference contradiction found in node!");
416 } else {
417 TP.error("Type inference contradiction found in node " +
418 getOperator()->getName() + "!");
419 }
Chris Lattner32707602005-09-08 23:22:48 +0000420 return true; // unreachable
421}
422
423
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000424void TreePatternNode::print(std::ostream &OS) const {
425 if (isLeaf()) {
426 OS << *getLeafValue();
427 } else {
428 OS << "(" << getOperator()->getName();
429 }
430
Nate Begemanb73628b2005-12-30 00:12:56 +0000431 // FIXME: At some point we should handle printing all the value types for
432 // nodes that are multiply typed.
433 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000434 case MVT::Other: OS << ":Other"; break;
435 case MVT::isInt: OS << ":isInt"; break;
436 case MVT::isFP : OS << ":isFP"; break;
437 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Evan Cheng2618d072006-05-17 20:37:59 +0000438 case MVT::iPTR: OS << ":iPTR"; break;
Nate Begemanb73628b2005-12-30 00:12:56 +0000439 default: OS << ":" << getTypeNum(0); break;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000440 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000441
442 if (!isLeaf()) {
443 if (getNumChildren() != 0) {
444 OS << " ";
445 getChild(0)->print(OS);
446 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
447 OS << ", ";
448 getChild(i)->print(OS);
449 }
450 }
451 OS << ")";
452 }
453
454 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000455 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000456 if (TransformFn)
457 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000458 if (!getName().empty())
459 OS << ":$" << getName();
460
461}
462void TreePatternNode::dump() const {
463 print(std::cerr);
464}
465
Chris Lattnere46e17b2005-09-29 19:28:10 +0000466/// isIsomorphicTo - Return true if this node is recursively isomorphic to
467/// the specified node. For this comparison, all of the state of the node
468/// is considered, except for the assigned name. Nodes with differing names
469/// that are otherwise identical are considered isomorphic.
470bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
471 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000472 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000473 getPredicateFn() != N->getPredicateFn() ||
474 getTransformFn() != N->getTransformFn())
475 return false;
476
477 if (isLeaf()) {
478 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
479 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
480 return DI->getDef() == NDI->getDef();
481 return getLeafValue() == N->getLeafValue();
482 }
483
484 if (N->getOperator() != getOperator() ||
485 N->getNumChildren() != getNumChildren()) return false;
486 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
487 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
488 return false;
489 return true;
490}
491
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000492/// clone - Make a copy of this tree and all of its children.
493///
494TreePatternNode *TreePatternNode::clone() const {
495 TreePatternNode *New;
496 if (isLeaf()) {
497 New = new TreePatternNode(getLeafValue());
498 } else {
499 std::vector<TreePatternNode*> CChildren;
500 CChildren.reserve(Children.size());
501 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
502 CChildren.push_back(getChild(i)->clone());
503 New = new TreePatternNode(getOperator(), CChildren);
504 }
505 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000506 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000507 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000508 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000509 return New;
510}
511
Chris Lattner32707602005-09-08 23:22:48 +0000512/// SubstituteFormalArguments - Replace the formal arguments in this tree
513/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000514void TreePatternNode::
515SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
516 if (isLeaf()) return;
517
518 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
519 TreePatternNode *Child = getChild(i);
520 if (Child->isLeaf()) {
521 Init *Val = Child->getLeafValue();
522 if (dynamic_cast<DefInit*>(Val) &&
523 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
524 // We found a use of a formal argument, replace it with its value.
525 Child = ArgMap[Child->getName()];
526 assert(Child && "Couldn't find formal argument!");
527 setChild(i, Child);
528 }
529 } else {
530 getChild(i)->SubstituteFormalArguments(ArgMap);
531 }
532 }
533}
534
535
536/// InlinePatternFragments - If this pattern refers to any pattern
537/// fragments, inline them into place, giving us a pattern without any
538/// PatFrag references.
539TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
540 if (isLeaf()) return this; // nothing to do.
541 Record *Op = getOperator();
542
543 if (!Op->isSubClassOf("PatFrag")) {
544 // Just recursively inline children nodes.
545 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
546 setChild(i, getChild(i)->InlinePatternFragments(TP));
547 return this;
548 }
549
550 // Otherwise, we found a reference to a fragment. First, look up its
551 // TreePattern record.
552 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
553
554 // Verify that we are passing the right number of operands.
555 if (Frag->getNumArgs() != Children.size())
556 TP.error("'" + Op->getName() + "' fragment requires " +
557 utostr(Frag->getNumArgs()) + " operands!");
558
Chris Lattner37937092005-09-09 01:15:01 +0000559 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000560
561 // Resolve formal arguments to their actual value.
562 if (Frag->getNumArgs()) {
563 // Compute the map of formal to actual arguments.
564 std::map<std::string, TreePatternNode*> ArgMap;
565 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
566 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
567
568 FragTree->SubstituteFormalArguments(ArgMap);
569 }
570
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000571 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000572 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000573
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000574 // Get a new copy of this fragment to stitch into here.
575 //delete this; // FIXME: implement refcounting!
576 return FragTree;
577}
578
Chris Lattner52793e22006-04-06 20:19:52 +0000579/// getImplicitType - Check to see if the specified record has an implicit
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000580/// type which should be applied to it. This infer the type of register
581/// references from the register file information, for example.
582///
Chris Lattner52793e22006-04-06 20:19:52 +0000583static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000584 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000585 // Some common return values
586 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
587 std::vector<unsigned char> Other(1, MVT::Other);
588
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000589 // Check to see if this is a register or a register class...
590 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000591 if (NotRegisters)
592 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000593 const CodeGenRegisterClass &RC =
594 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000595 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000596 } else if (R->isSubClassOf("PatFrag")) {
597 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000598 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000599 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000600 if (NotRegisters)
601 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000602 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
Evan Cheng44a65fa2006-05-16 07:05:30 +0000603 return T.getRegisterVTs(R);
Chris Lattner1531f202005-10-26 16:59:37 +0000604 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
605 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000606 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000607 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000608 if (NotRegisters)
609 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000610 std::vector<unsigned char>
611 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
612 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000613 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000614 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000615 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000616 }
617
618 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000619 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000620}
621
Chris Lattner32707602005-09-08 23:22:48 +0000622/// ApplyTypeConstraints - Apply all of the type constraints relevent to
623/// this node and its children in the tree. This returns true if it makes a
624/// change, false otherwise. If a type contradiction is found, throw an
625/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000626bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000627 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000628 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000629 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000630 // If it's a regclass or something else known, include the type.
Chris Lattner52793e22006-04-06 20:19:52 +0000631 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000632 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
633 // Int inits are always integers. :)
634 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
635
636 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000637 // At some point, it may make sense for this tree pattern to have
638 // multiple types. Assert here that it does not, so we revisit this
639 // code when appropriate.
Evan Cheng2618d072006-05-17 20:37:59 +0000640 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Evan Cheng44a65fa2006-05-16 07:05:30 +0000641 MVT::ValueType VT = getTypeNum(0);
642 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
643 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000644
Evan Cheng2618d072006-05-17 20:37:59 +0000645 VT = getTypeNum(0);
646 if (VT != MVT::iPTR) {
647 unsigned Size = MVT::getSizeInBits(VT);
648 // Make sure that the value is representable for this type.
649 if (Size < 32) {
650 int Val = (II->getValue() << (32-Size)) >> (32-Size);
651 if (Val != II->getValue())
652 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
653 "' is out of range for type '" +
654 getEnumName(getTypeNum(0)) + "'!");
655 }
Chris Lattner465c7372005-11-03 05:46:11 +0000656 }
657 }
658
659 return MadeChange;
660 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000661 return false;
662 }
Chris Lattner32707602005-09-08 23:22:48 +0000663
664 // special handling for set, which isn't really an SDNode.
665 if (getOperator()->getName() == "set") {
666 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000667 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
668 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000669
670 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000671 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
672 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000673 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
674 return MadeChange;
Chris Lattner5a1df382006-03-24 23:10:39 +0000675 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
676 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
677 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
678 unsigned IID =
679 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
680 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
681 bool MadeChange = false;
682
683 // Apply the result type to the node.
684 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
685
686 if (getNumChildren() != Int.ArgVTs.size())
Chris Lattner2c4e65d2006-03-27 22:21:18 +0000687 TP.error("Intrinsic '" + Int.Name + "' expects " +
Chris Lattner5a1df382006-03-24 23:10:39 +0000688 utostr(Int.ArgVTs.size()-1) + " operands, not " +
689 utostr(getNumChildren()-1) + " operands!");
690
691 // Apply type info to the intrinsic ID.
Evan Cheng2618d072006-05-17 20:37:59 +0000692 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5a1df382006-03-24 23:10:39 +0000693
694 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
695 MVT::ValueType OpVT = Int.ArgVTs[i];
696 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
697 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
698 }
699 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000700 } else if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000701 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
Chris Lattnerabbb6052005-09-15 21:42:00 +0000702
703 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
704 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000705 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000706 // Branch, etc. do not produce results and top-level forms in instr pattern
707 // must have void types.
708 if (NI.getNumResults() == 0)
709 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner91ded082006-04-06 20:36:51 +0000710
711 // If this is a vector_shuffle operation, apply types to the build_vector
712 // operation. The types of the integers don't matter, but this ensures they
713 // won't get checked.
714 if (getOperator()->getName() == "vector_shuffle" &&
715 getChild(2)->getOperator()->getName() == "build_vector") {
716 TreePatternNode *BV = getChild(2);
717 const std::vector<MVT::ValueType> &LegalVTs
718 = ISE.getTargetInfo().getLegalValueTypes();
719 MVT::ValueType LegalIntVT = MVT::Other;
720 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
721 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
722 LegalIntVT = LegalVTs[i];
723 break;
724 }
725 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
726
727 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
728 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
729 }
Chris Lattnerabbb6052005-09-15 21:42:00 +0000730 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000731 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000732 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000733 bool MadeChange = false;
734 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000735
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000736 assert(NumResults <= 1 &&
737 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000738 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000739 if (NumResults == 0) {
740 MadeChange = UpdateNodeType(MVT::isVoid, TP);
741 } else {
742 Record *ResultNode = Inst.getResult(0);
743 assert(ResultNode->isSubClassOf("RegisterClass") &&
744 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000745
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000746 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000747 ISE.getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000748 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000749 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000750
751 if (getNumChildren() != Inst.getNumOperands())
752 TP.error("Instruction '" + getOperator()->getName() + " expects " +
753 utostr(Inst.getNumOperands()) + " operands, not " +
754 utostr(getNumChildren()) + " operands!");
755 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000756 Record *OperandNode = Inst.getOperand(i);
757 MVT::ValueType VT;
758 if (OperandNode->isSubClassOf("RegisterClass")) {
759 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000760 ISE.getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000761 //VT = RC.getValueTypeNum(0);
762 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
763 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000764 } else if (OperandNode->isSubClassOf("Operand")) {
765 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000766 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000767 } else {
768 assert(0 && "Unknown operand type!");
769 abort();
770 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000771 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000772 }
773 return MadeChange;
774 } else {
775 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
776
Evan Chengf26ba692006-03-20 08:09:17 +0000777 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000778 if (getNumChildren() != 1)
779 TP.error("Node transform '" + getOperator()->getName() +
780 "' requires one operand!");
Chris Lattner4e2f54d2006-03-21 06:42:58 +0000781
782 // If either the output or input of the xform does not have exact
783 // type info. We assume they must be the same. Otherwise, it is perfectly
784 // legal to transform from one type to a completely different type.
785 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Evan Chengf26ba692006-03-20 08:09:17 +0000786 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
787 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
788 return MadeChange;
789 }
790 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000791 }
Chris Lattner32707602005-09-08 23:22:48 +0000792}
793
Chris Lattnere97603f2005-09-28 19:27:25 +0000794/// canPatternMatch - If it is impossible for this pattern to match on this
795/// target, fill in Reason and return false. Otherwise, return true. This is
796/// used as a santity check for .td files (to prevent people from writing stuff
797/// that can never possibly work), and to prevent the pattern permuter from
798/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000799bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000800 if (isLeaf()) return true;
801
802 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
803 if (!getChild(i)->canPatternMatch(Reason, ISE))
804 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000805
Chris Lattner550525e2006-03-24 21:48:51 +0000806 // If this is an intrinsic, handle cases that would make it not match. For
807 // example, if an operand is required to be an immediate.
808 if (getOperator()->isSubClassOf("Intrinsic")) {
809 // TODO:
810 return true;
811 }
812
Chris Lattnere97603f2005-09-28 19:27:25 +0000813 // If this node is a commutative operator, check that the LHS isn't an
814 // immediate.
815 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
816 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
817 // Scan all of the operands of the node and make sure that only the last one
818 // is a constant node.
819 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
820 if (!getChild(i)->isLeaf() &&
821 getChild(i)->getOperator()->getName() == "imm") {
822 Reason = "Immediate value must be on the RHS of commutative operators!";
823 return false;
824 }
825 }
826
827 return true;
828}
Chris Lattner32707602005-09-08 23:22:48 +0000829
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000830//===----------------------------------------------------------------------===//
831// TreePattern implementation
832//
833
Chris Lattneredbd8712005-10-21 01:19:59 +0000834TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000835 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000836 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000837 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
838 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000839}
840
Chris Lattneredbd8712005-10-21 01:19:59 +0000841TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000842 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000843 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000844 Trees.push_back(ParseTreePattern(Pat));
845}
846
Chris Lattneredbd8712005-10-21 01:19:59 +0000847TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000848 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000849 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000850 Trees.push_back(Pat);
851}
852
853
854
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000855void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000856 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000857 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000858}
859
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000860TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
Chris Lattner8c063182006-03-30 22:50:40 +0000861 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
862 if (!OpDef) error("Pattern has unexpected operator type!");
863 Record *Operator = OpDef->getDef();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000864
865 if (Operator->isSubClassOf("ValueType")) {
866 // If the operator is a ValueType, then this must be "type cast" of a leaf
867 // node.
868 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000869 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000870
871 Init *Arg = Dag->getArg(0);
872 TreePatternNode *New;
873 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000874 Record *R = DI->getDef();
875 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000876 Dag->setArg(0, new DagInit(DI,
Chris Lattner72fe91c2005-09-24 00:40:24 +0000877 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000878 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000879 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000880 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000881 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
882 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000883 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
884 New = new TreePatternNode(II);
885 if (!Dag->getArgName(0).empty())
886 error("Constant int argument should not have a name!");
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000887 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
888 // Turn this into an IntInit.
889 Init *II = BI->convertInitializerTo(new IntRecTy());
890 if (II == 0 || !dynamic_cast<IntInit*>(II))
891 error("Bits value must be constants!");
892
893 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
894 if (!Dag->getArgName(0).empty())
895 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000896 } else {
897 Arg->dump();
898 error("Unknown leaf value for tree pattern!");
899 return 0;
900 }
901
Chris Lattner32707602005-09-08 23:22:48 +0000902 // Apply the type cast.
903 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000904 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000905 return New;
906 }
907
908 // Verify that this is something that makes sense for an operator.
909 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000910 !Operator->isSubClassOf("Instruction") &&
911 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner550525e2006-03-24 21:48:51 +0000912 !Operator->isSubClassOf("Intrinsic") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000913 Operator->getName() != "set")
914 error("Unrecognized node '" + Operator->getName() + "'!");
915
Chris Lattneredbd8712005-10-21 01:19:59 +0000916 // Check to see if this is something that is illegal in an input pattern.
917 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
Chris Lattner5a1df382006-03-24 23:10:39 +0000918 Operator->isSubClassOf("SDNodeXForm")))
Chris Lattneredbd8712005-10-21 01:19:59 +0000919 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
920
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000921 std::vector<TreePatternNode*> Children;
922
923 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
924 Init *Arg = Dag->getArg(i);
925 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
926 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000927 if (Children.back()->getName().empty())
928 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000929 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
930 Record *R = DefI->getDef();
931 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
932 // TreePatternNode if its own.
933 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000934 Dag->setArg(i, new DagInit(DefI,
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000935 std::vector<std::pair<Init*, std::string> >()));
936 --i; // Revisit this node...
937 } else {
938 TreePatternNode *Node = new TreePatternNode(DefI);
939 Node->setName(Dag->getArgName(i));
940 Children.push_back(Node);
941
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000942 // Input argument?
943 if (R->getName() == "node") {
944 if (Dag->getArgName(i).empty())
945 error("'node' argument requires a name to match with operand list");
946 Args.push_back(Dag->getArgName(i));
947 }
948 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000949 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
950 TreePatternNode *Node = new TreePatternNode(II);
951 if (!Dag->getArgName(i).empty())
952 error("Constant int argument should not have a name!");
953 Children.push_back(Node);
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000954 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
955 // Turn this into an IntInit.
956 Init *II = BI->convertInitializerTo(new IntRecTy());
957 if (II == 0 || !dynamic_cast<IntInit*>(II))
958 error("Bits value must be constants!");
959
960 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
961 if (!Dag->getArgName(i).empty())
962 error("Constant int argument should not have a name!");
963 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000964 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000965 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000966 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000967 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000968 error("Unknown leaf value for tree pattern!");
969 }
970 }
971
Chris Lattner5a1df382006-03-24 23:10:39 +0000972 // If the operator is an intrinsic, then this is just syntactic sugar for for
973 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
974 // convert the intrinsic name to a number.
975 if (Operator->isSubClassOf("Intrinsic")) {
976 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
977 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
978
979 // If this intrinsic returns void, it must have side-effects and thus a
980 // chain.
981 if (Int.ArgVTs[0] == MVT::isVoid) {
982 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
983 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
984 // Has side-effects, requires chain.
985 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
986 } else {
987 // Otherwise, no chain.
988 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
989 }
990
991 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
992 Children.insert(Children.begin(), IIDNode);
993 }
994
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000995 return new TreePatternNode(Operator, Children);
996}
997
Chris Lattner32707602005-09-08 23:22:48 +0000998/// InferAllTypes - Infer/propagate as many types throughout the expression
999/// patterns as possible. Return true if all types are infered, false
1000/// otherwise. Throw an exception if a type contradiction is found.
1001bool TreePattern::InferAllTypes() {
1002 bool MadeChange = true;
1003 while (MadeChange) {
1004 MadeChange = false;
1005 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001006 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +00001007 }
1008
1009 bool HasUnresolvedTypes = false;
1010 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1011 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1012 return !HasUnresolvedTypes;
1013}
1014
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001015void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001016 OS << getRecord()->getName();
1017 if (!Args.empty()) {
1018 OS << "(" << Args[0];
1019 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1020 OS << ", " << Args[i];
1021 OS << ")";
1022 }
1023 OS << ": ";
1024
1025 if (Trees.size() > 1)
1026 OS << "[\n";
1027 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1028 OS << "\t";
1029 Trees[i]->print(OS);
1030 OS << "\n";
1031 }
1032
1033 if (Trees.size() > 1)
1034 OS << "]\n";
1035}
1036
1037void TreePattern::dump() const { print(std::cerr); }
1038
1039
1040
1041//===----------------------------------------------------------------------===//
1042// DAGISelEmitter implementation
1043//
1044
Chris Lattnerca559d02005-09-08 21:03:01 +00001045// Parse all of the SDNode definitions for the target, populating SDNodes.
1046void DAGISelEmitter::ParseNodeInfo() {
1047 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1048 while (!Nodes.empty()) {
1049 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1050 Nodes.pop_back();
1051 }
Chris Lattner5a1df382006-03-24 23:10:39 +00001052
1053 // Get the buildin intrinsic nodes.
1054 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1055 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1056 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
Chris Lattnerca559d02005-09-08 21:03:01 +00001057}
1058
Chris Lattner24eeeb82005-09-13 21:51:00 +00001059/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1060/// map, and emit them to the file as functions.
1061void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1062 OS << "\n// Node transformations.\n";
1063 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1064 while (!Xforms.empty()) {
1065 Record *XFormNode = Xforms.back();
1066 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1067 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1068 SDNodeXForms.insert(std::make_pair(XFormNode,
1069 std::make_pair(SDNode, Code)));
1070
Chris Lattner1048b7a2005-09-13 22:03:37 +00001071 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +00001072 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1073 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1074
Chris Lattner1048b7a2005-09-13 22:03:37 +00001075 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +00001076 << "(SDNode *" << C2 << ") {\n";
1077 if (ClassName != "SDNode")
1078 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1079 OS << Code << "\n}\n";
1080 }
1081
1082 Xforms.pop_back();
1083 }
1084}
1085
Evan Cheng0fc71982005-12-08 02:00:36 +00001086void DAGISelEmitter::ParseComplexPatterns() {
1087 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1088 while (!AMs.empty()) {
1089 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1090 AMs.pop_back();
1091 }
1092}
Chris Lattner24eeeb82005-09-13 21:51:00 +00001093
1094
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001095/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1096/// file, building up the PatternFragments map. After we've collected them all,
1097/// inline fragments together as necessary, so that there are no references left
1098/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001099///
1100/// This also emits all of the predicate functions to the output file.
1101///
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001102void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001103 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1104
1105 // First step, parse all of the fragments and emit predicate functions.
1106 OS << "\n// Predicate functions.\n";
1107 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001108 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +00001109 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001110 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +00001111
1112 // Validate the argument list, converting it to map, to discard duplicates.
1113 std::vector<std::string> &Args = P->getArgList();
1114 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1115
1116 if (OperandsMap.count(""))
1117 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1118
1119 // Parse the operands list.
1120 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Chris Lattner8c063182006-03-30 22:50:40 +00001121 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1122 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
Chris Lattneree9f0c32005-09-13 21:20:49 +00001123 P->error("Operands list should start with '(ops ... '!");
1124
1125 // Copy over the arguments.
1126 Args.clear();
1127 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1128 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1129 static_cast<DefInit*>(OpsList->getArg(j))->
1130 getDef()->getName() != "node")
1131 P->error("Operands list should all be 'node' values.");
1132 if (OpsList->getArgName(j).empty())
1133 P->error("Operands list should have names for each operand!");
1134 if (!OperandsMap.count(OpsList->getArgName(j)))
1135 P->error("'" + OpsList->getArgName(j) +
1136 "' does not occur in pattern or was multiply specified!");
1137 OperandsMap.erase(OpsList->getArgName(j));
1138 Args.push_back(OpsList->getArgName(j));
1139 }
1140
1141 if (!OperandsMap.empty())
1142 P->error("Operands list does not contain an entry for operand '" +
1143 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001144
1145 // If there is a code init for this fragment, emit the predicate code and
1146 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001147 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1148 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +00001149 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001150 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +00001151 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001152 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1153
Chris Lattner1048b7a2005-09-13 22:03:37 +00001154 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001155 << "(SDNode *" << C2 << ") {\n";
1156 if (ClassName != "SDNode")
1157 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +00001158 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001159 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001160 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001161
1162 // If there is a node transformation corresponding to this, keep track of
1163 // it.
1164 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1165 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001166 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001167 }
1168
1169 OS << "\n\n";
1170
1171 // Now that we've parsed all of the tree fragments, do a closure on them so
1172 // that there are not references to PatFrags left inside of them.
1173 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1174 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001175 TreePattern *ThePat = I->second;
1176 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001177
Chris Lattner32707602005-09-08 23:22:48 +00001178 // Infer as many types as possible. Don't worry about it if we don't infer
1179 // all of them, some may depend on the inputs of the pattern.
1180 try {
1181 ThePat->InferAllTypes();
1182 } catch (...) {
1183 // If this pattern fragment is not supported by this target (no types can
1184 // satisfy its constraints), just ignore it. If the bogus pattern is
1185 // actually used by instructions, the type consistency error will be
1186 // reported there.
1187 }
1188
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001189 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001190 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001191 }
1192}
1193
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001194/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001195/// instruction input. Return true if this is a real use.
1196static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001197 std::map<std::string, TreePatternNode*> &InstInputs,
1198 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001199 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001200 if (Pat->getName().empty()) {
1201 if (Pat->isLeaf()) {
1202 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1203 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1204 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001205 else if (DI && DI->getDef()->isSubClassOf("Register"))
1206 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001207 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001208 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001209 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001210
1211 Record *Rec;
1212 if (Pat->isLeaf()) {
1213 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1214 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1215 Rec = DI->getDef();
1216 } else {
1217 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1218 Rec = Pat->getOperator();
1219 }
1220
Evan Cheng01f318b2005-12-14 02:21:57 +00001221 // SRCVALUE nodes are ignored.
1222 if (Rec->getName() == "srcvalue")
1223 return false;
1224
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001225 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1226 if (!Slot) {
1227 Slot = Pat;
1228 } else {
1229 Record *SlotRec;
1230 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001231 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001232 } else {
1233 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1234 SlotRec = Slot->getOperator();
1235 }
1236
1237 // Ensure that the inputs agree if we've already seen this input.
1238 if (Rec != SlotRec)
1239 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001240 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001241 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1242 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001243 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001244}
1245
1246/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1247/// part of "I", the instruction), computing the set of inputs and outputs of
1248/// the pattern. Report errors if we see anything naughty.
1249void DAGISelEmitter::
1250FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1251 std::map<std::string, TreePatternNode*> &InstInputs,
Chris Lattner947604b2006-03-24 21:52:20 +00001252 std::map<std::string, TreePatternNode*>&InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001253 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001254 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001255 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001256 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001257 if (!isUse && Pat->getTransformFn())
1258 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001259 return;
1260 } else if (Pat->getOperator()->getName() != "set") {
1261 // If this is not a set, verify that the children nodes are not void typed,
1262 // and recurse.
1263 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001264 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001265 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001266 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001267 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001268 }
1269
1270 // If this is a non-leaf node with no children, treat it basically as if
1271 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001272 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001273 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001274 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001275
Chris Lattnerf1311842005-09-14 23:05:13 +00001276 if (!isUse && Pat->getTransformFn())
1277 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001278 return;
1279 }
1280
1281 // Otherwise, this is a set, validate and collect instruction results.
1282 if (Pat->getNumChildren() == 0)
1283 I->error("set requires operands!");
1284 else if (Pat->getNumChildren() & 1)
1285 I->error("set requires an even number of operands");
1286
Chris Lattnerf1311842005-09-14 23:05:13 +00001287 if (Pat->getTransformFn())
1288 I->error("Cannot specify a transform function on a set node!");
1289
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001290 // Check the set destinations.
1291 unsigned NumValues = Pat->getNumChildren()/2;
1292 for (unsigned i = 0; i != NumValues; ++i) {
1293 TreePatternNode *Dest = Pat->getChild(i);
1294 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001295 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001296
1297 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1298 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001299 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001300
Evan Chengbcecf332005-12-17 01:19:28 +00001301 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1302 if (Dest->getName().empty())
1303 I->error("set destination must have a name!");
1304 if (InstResults.count(Dest->getName()))
1305 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001306 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001307 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001308 InstImpResults.push_back(Val->getDef());
1309 } else {
1310 I->error("set destination should be a register!");
1311 }
1312
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001313 // Verify and collect info from the computation.
1314 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001315 InstInputs, InstResults,
1316 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001317 }
1318}
1319
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001320/// ParseInstructions - Parse all of the instructions, inlining and resolving
1321/// any fragments involved. This populates the Instructions list with fully
1322/// resolved instructions.
1323void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001324 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1325
1326 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001327 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001328
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001329 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1330 LI = Instrs[i]->getValueAsListInit("Pattern");
1331
1332 // If there is no pattern, only collect minimal information about the
1333 // instruction for its operand list. We have to assume that there is one
1334 // result, as we have no detailed info.
1335 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001336 std::vector<Record*> Results;
1337 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001338
1339 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001340
Evan Cheng3a217f32005-12-22 02:35:21 +00001341 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001342 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001343 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001344 // These produce no results
1345 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1346 Operands.push_back(InstInfo.OperandList[j].Rec);
1347 } else {
1348 // Assume the first operand is the result.
1349 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001350
Evan Cheng3a217f32005-12-22 02:35:21 +00001351 // The rest are inputs.
1352 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1353 Operands.push_back(InstInfo.OperandList[j].Rec);
1354 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001355 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001356
1357 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001358 std::vector<Record*> ImpResults;
1359 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001360 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001361 DAGInstruction(0, Results, Operands, ImpResults,
1362 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001363 continue; // no pattern.
1364 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001365
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001366 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001367 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001368 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001369 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001370
Chris Lattner95f6b762005-09-08 23:26:30 +00001371 // Infer as many types as possible. If we cannot infer all of them, we can
1372 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001373 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001374 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001375
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001376 // InstInputs - Keep track of all of the inputs of the instruction, along
1377 // with the record they are declared as.
1378 std::map<std::string, TreePatternNode*> InstInputs;
1379
1380 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001381 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001382 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001383
1384 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001385 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001386
Chris Lattner1f39e292005-09-14 00:09:24 +00001387 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001388 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001389 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1390 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001391 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001392 I->error("Top-level forms in instruction pattern should have"
1393 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001394
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001395 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001396 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001397 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001398 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001399
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001400 // Now that we have inputs and outputs of the pattern, inspect the operands
1401 // list for the instruction. This determines the order that operands are
1402 // added to the machine instruction the node corresponds to.
1403 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001404
1405 // Parse the operands list from the (ops) list, validating it.
1406 std::vector<std::string> &Args = I->getArgList();
1407 assert(Args.empty() && "Args list should still be empty here!");
1408 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1409
1410 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001411 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001412 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001413 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001414 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001415 I->error("'" + InstResults.begin()->first +
1416 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001417 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001418
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001419 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001420 TreePatternNode *RNode = InstResults[OpName];
Chris Lattner5c4c7742006-03-25 22:12:44 +00001421 if (RNode == 0)
1422 I->error("Operand $" + OpName + " does not exist in operand list!");
1423
Evan Cheng420132e2006-03-20 06:04:09 +00001424 if (i == 0)
1425 Res0Node = RNode;
1426 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001427 if (R == 0)
1428 I->error("Operand $" + OpName + " should be a set destination: all "
1429 "outputs must occur before inputs in operand list!");
1430
1431 if (CGI.OperandList[i].Rec != R)
1432 I->error("Operand $" + OpName + " class mismatch!");
1433
Chris Lattnerae6d8282005-09-15 21:51:12 +00001434 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001435 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001436
Chris Lattner39e8af92005-09-14 18:19:25 +00001437 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001438 InstResults.erase(OpName);
1439 }
1440
Chris Lattner0b592252005-09-14 21:59:34 +00001441 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1442 // the copy while we're checking the inputs.
1443 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001444
1445 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001446 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001447 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1448 const std::string &OpName = CGI.OperandList[i].Name;
1449 if (OpName.empty())
1450 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1451
Chris Lattner0b592252005-09-14 21:59:34 +00001452 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001453 I->error("Operand $" + OpName +
1454 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001455 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001456 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001457
1458 if (InVal->isLeaf() &&
1459 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1460 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001461 if (CGI.OperandList[i].Rec != InRec &&
1462 !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001463 I->error("Operand $" + OpName + "'s register class disagrees"
1464 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001465 }
1466 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001467
Chris Lattner2175c182005-09-14 23:01:59 +00001468 // Construct the result for the dest-pattern operand list.
1469 TreePatternNode *OpNode = InVal->clone();
1470
1471 // No predicate is useful on the result.
1472 OpNode->setPredicateFn("");
1473
1474 // Promote the xform function to be an explicit node if set.
1475 if (Record *Xform = OpNode->getTransformFn()) {
1476 OpNode->setTransformFn(0);
1477 std::vector<TreePatternNode*> Children;
1478 Children.push_back(OpNode);
1479 OpNode = new TreePatternNode(Xform, Children);
1480 }
1481
1482 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001483 }
1484
Chris Lattner0b592252005-09-14 21:59:34 +00001485 if (!InstInputsCheck.empty())
1486 I->error("Input operand $" + InstInputsCheck.begin()->first +
1487 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001488
1489 TreePatternNode *ResultPattern =
1490 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001491 // Copy fully inferred output node type to instruction result pattern.
1492 if (NumResults > 0)
1493 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001494
1495 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001496 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001497 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1498
1499 // Use a temporary tree pattern to infer all types and make sure that the
1500 // constructed result is correct. This depends on the instruction already
1501 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001502 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001503 Temp.InferAllTypes();
1504
1505 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1506 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001507
Chris Lattner32707602005-09-08 23:22:48 +00001508 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001509 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001510
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001511 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001512 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1513 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001514 DAGInstruction &TheInst = II->second;
1515 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001516 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001517
Chris Lattner1f39e292005-09-14 00:09:24 +00001518 if (I->getNumTrees() != 1) {
1519 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1520 continue;
1521 }
1522 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001523 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001524 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001525 if (Pattern->getNumChildren() != 2)
1526 continue; // Not a set of a single value (not handled so far)
1527
1528 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001529 } else{
1530 // Not a set (store or something?)
1531 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001532 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001533
1534 std::string Reason;
1535 if (!SrcPattern->canPatternMatch(Reason, *this))
1536 I->error("Instruction can never match: " + Reason);
1537
Evan Cheng58e84a62005-12-14 22:02:59 +00001538 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001539 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001540 PatternsToMatch.
1541 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
Evan Cheng59413202006-04-19 18:07:24 +00001542 SrcPattern, DstPattern,
Evan Chengc81d2a02006-04-19 20:36:09 +00001543 Instr->getValueAsInt("AddedComplexity")));
Chris Lattner1f39e292005-09-14 00:09:24 +00001544 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001545}
1546
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001547void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001548 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001549
Chris Lattnerabbb6052005-09-15 21:42:00 +00001550 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001551 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001552 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001553
Chris Lattnerabbb6052005-09-15 21:42:00 +00001554 // Inline pattern fragments into it.
1555 Pattern->InlinePatternFragments();
1556
Chris Lattnera3548492006-06-20 00:18:02 +00001557 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1558 if (LI->getSize() == 0) continue; // no pattern.
1559
1560 // Parse the instruction.
1561 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1562
1563 // Inline pattern fragments into it.
1564 Result->InlinePatternFragments();
Chris Lattner09c03392005-11-17 17:43:52 +00001565
Chris Lattnera3548492006-06-20 00:18:02 +00001566 if (Result->getNumTrees() != 1)
1567 Result->error("Cannot handle instructions producing instructions "
1568 "with temporaries yet!");
1569
1570 bool IterateInference;
Chris Lattner186fb7d2006-06-20 00:31:27 +00001571 bool InferredAllPatternTypes, InferredAllResultTypes;
Chris Lattnera3548492006-06-20 00:18:02 +00001572 do {
1573 // Infer as many types as possible. If we cannot infer all of them, we
1574 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001575 InferredAllPatternTypes = Pattern->InferAllTypes();
Chris Lattnera3548492006-06-20 00:18:02 +00001576
1577 // Infer as many types as possible. If we cannot infer all of them, we can
1578 // never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001579 InferredAllResultTypes = Result->InferAllTypes();
1580
Chris Lattnera3548492006-06-20 00:18:02 +00001581 // Apply the type of the result to the source pattern. This helps us
1582 // resolve cases where the input type is known to be a pointer type (which
1583 // is considered resolved), but the result knows it needs to be 32- or
1584 // 64-bits. Infer the other way for good measure.
1585 IterateInference = Pattern->getOnlyTree()->
1586 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1587 IterateInference |= Result->getOnlyTree()->
1588 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1589 } while (IterateInference);
Chris Lattner186fb7d2006-06-20 00:31:27 +00001590
1591 // Verify that we inferred enough types that we can do something with the
1592 // pattern and result. If these fire the user has to add type casts.
1593 if (!InferredAllPatternTypes)
1594 Pattern->error("Could not infer all types in pattern!");
1595 if (!InferredAllResultTypes)
1596 Result->error("Could not infer all types in pattern result!");
Chris Lattnera3548492006-06-20 00:18:02 +00001597
Chris Lattner09c03392005-11-17 17:43:52 +00001598 // Validate that the input pattern is correct.
1599 {
1600 std::map<std::string, TreePatternNode*> InstInputs;
Evan Cheng420132e2006-03-20 06:04:09 +00001601 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001602 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001603 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001604 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001605 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001606 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001607 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001608
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001609 // Promote the xform function to be an explicit node if set.
1610 std::vector<TreePatternNode*> ResultNodeOperands;
1611 TreePatternNode *DstPattern = Result->getOnlyTree();
1612 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1613 TreePatternNode *OpNode = DstPattern->getChild(ii);
1614 if (Record *Xform = OpNode->getTransformFn()) {
1615 OpNode->setTransformFn(0);
1616 std::vector<TreePatternNode*> Children;
1617 Children.push_back(OpNode);
1618 OpNode = new TreePatternNode(Xform, Children);
1619 }
1620 ResultNodeOperands.push_back(OpNode);
1621 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00001622 DstPattern = Result->getOnlyTree();
1623 if (!DstPattern->isLeaf())
1624 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1625 ResultNodeOperands);
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001626 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1627 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1628 Temp.InferAllTypes();
1629
Chris Lattnere97603f2005-09-28 19:27:25 +00001630 std::string Reason;
1631 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1632 Pattern->error("Pattern can never match: " + Reason);
1633
Evan Cheng58e84a62005-12-14 22:02:59 +00001634 PatternsToMatch.
1635 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1636 Pattern->getOnlyTree(),
Evan Cheng59413202006-04-19 18:07:24 +00001637 Temp.getOnlyTree(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001638 Patterns[i]->getValueAsInt("AddedComplexity")));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001639 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001640}
1641
Chris Lattnere46e17b2005-09-29 19:28:10 +00001642/// CombineChildVariants - Given a bunch of permutations of each child of the
1643/// 'operator' node, put them together in all possible ways.
1644static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001645 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001646 std::vector<TreePatternNode*> &OutVariants,
1647 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001648 // Make sure that each operand has at least one variant to choose from.
1649 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1650 if (ChildVariants[i].empty())
1651 return;
1652
Chris Lattnere46e17b2005-09-29 19:28:10 +00001653 // The end result is an all-pairs construction of the resultant pattern.
1654 std::vector<unsigned> Idxs;
1655 Idxs.resize(ChildVariants.size());
1656 bool NotDone = true;
1657 while (NotDone) {
1658 // Create the variant and add it to the output list.
1659 std::vector<TreePatternNode*> NewChildren;
1660 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1661 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1662 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1663
1664 // Copy over properties.
1665 R->setName(Orig->getName());
1666 R->setPredicateFn(Orig->getPredicateFn());
1667 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001668 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001669
1670 // If this pattern cannot every match, do not include it as a variant.
1671 std::string ErrString;
1672 if (!R->canPatternMatch(ErrString, ISE)) {
1673 delete R;
1674 } else {
1675 bool AlreadyExists = false;
1676
1677 // Scan to see if this pattern has already been emitted. We can get
1678 // duplication due to things like commuting:
1679 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1680 // which are the same pattern. Ignore the dups.
1681 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1682 if (R->isIsomorphicTo(OutVariants[i])) {
1683 AlreadyExists = true;
1684 break;
1685 }
1686
1687 if (AlreadyExists)
1688 delete R;
1689 else
1690 OutVariants.push_back(R);
1691 }
1692
1693 // Increment indices to the next permutation.
1694 NotDone = false;
1695 // Look for something we can increment without causing a wrap-around.
1696 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1697 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1698 NotDone = true; // Found something to increment.
1699 break;
1700 }
1701 Idxs[IdxsIdx] = 0;
1702 }
1703 }
1704}
1705
Chris Lattneraf302912005-09-29 22:36:54 +00001706/// CombineChildVariants - A helper function for binary operators.
1707///
1708static void CombineChildVariants(TreePatternNode *Orig,
1709 const std::vector<TreePatternNode*> &LHS,
1710 const std::vector<TreePatternNode*> &RHS,
1711 std::vector<TreePatternNode*> &OutVariants,
1712 DAGISelEmitter &ISE) {
1713 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1714 ChildVariants.push_back(LHS);
1715 ChildVariants.push_back(RHS);
1716 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1717}
1718
1719
1720static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1721 std::vector<TreePatternNode *> &Children) {
1722 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1723 Record *Operator = N->getOperator();
1724
1725 // Only permit raw nodes.
1726 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1727 N->getTransformFn()) {
1728 Children.push_back(N);
1729 return;
1730 }
1731
1732 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1733 Children.push_back(N->getChild(0));
1734 else
1735 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1736
1737 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1738 Children.push_back(N->getChild(1));
1739 else
1740 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1741}
1742
Chris Lattnere46e17b2005-09-29 19:28:10 +00001743/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1744/// the (potentially recursive) pattern by using algebraic laws.
1745///
1746static void GenerateVariantsOf(TreePatternNode *N,
1747 std::vector<TreePatternNode*> &OutVariants,
1748 DAGISelEmitter &ISE) {
1749 // We cannot permute leaves.
1750 if (N->isLeaf()) {
1751 OutVariants.push_back(N);
1752 return;
1753 }
1754
1755 // Look up interesting info about the node.
Chris Lattner5a1df382006-03-24 23:10:39 +00001756 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001757
1758 // If this node is associative, reassociate.
Chris Lattner5a1df382006-03-24 23:10:39 +00001759 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
Chris Lattneraf302912005-09-29 22:36:54 +00001760 // Reassociate by pulling together all of the linked operators
1761 std::vector<TreePatternNode*> MaximalChildren;
1762 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1763
1764 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1765 // permutations.
1766 if (MaximalChildren.size() == 3) {
1767 // Find the variants of all of our maximal children.
1768 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1769 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1770 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1771 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1772
1773 // There are only two ways we can permute the tree:
1774 // (A op B) op C and A op (B op C)
1775 // Within these forms, we can also permute A/B/C.
1776
1777 // Generate legal pair permutations of A/B/C.
1778 std::vector<TreePatternNode*> ABVariants;
1779 std::vector<TreePatternNode*> BAVariants;
1780 std::vector<TreePatternNode*> ACVariants;
1781 std::vector<TreePatternNode*> CAVariants;
1782 std::vector<TreePatternNode*> BCVariants;
1783 std::vector<TreePatternNode*> CBVariants;
1784 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1785 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1786 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1787 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1788 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1789 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1790
1791 // Combine those into the result: (x op x) op x
1792 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1793 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1794 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1795 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1796 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1797 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1798
1799 // Combine those into the result: x op (x op x)
1800 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1801 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1802 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1803 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1804 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1805 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1806 return;
1807 }
1808 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001809
1810 // Compute permutations of all children.
1811 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1812 ChildVariants.resize(N->getNumChildren());
1813 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1814 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1815
1816 // Build all permutations based on how the children were formed.
1817 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1818
1819 // If this node is commutative, consider the commuted order.
Chris Lattner5a1df382006-03-24 23:10:39 +00001820 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001821 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001822 // Consider the commuted order.
1823 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1824 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001825 }
1826}
1827
1828
Chris Lattnere97603f2005-09-28 19:27:25 +00001829// GenerateVariants - Generate variants. For example, commutative patterns can
1830// match multiple ways. Add them to PatternsToMatch as well.
1831void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001832
1833 DEBUG(std::cerr << "Generating instruction variants.\n");
1834
1835 // Loop over all of the patterns we've collected, checking to see if we can
1836 // generate variants of the instruction, through the exploitation of
1837 // identities. This permits the target to provide agressive matching without
1838 // the .td file having to contain tons of variants of instructions.
1839 //
1840 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1841 // intentionally do not reconsider these. Any variants of added patterns have
1842 // already been added.
1843 //
1844 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1845 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001846 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001847
1848 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001849 Variants.erase(Variants.begin()); // Remove the original pattern.
1850
1851 if (Variants.empty()) // No variants for this pattern.
1852 continue;
1853
1854 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001855 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001856 std::cerr << "\n");
1857
1858 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1859 TreePatternNode *Variant = Variants[v];
1860
1861 DEBUG(std::cerr << " VAR#" << v << ": ";
1862 Variant->dump();
1863 std::cerr << "\n");
1864
1865 // Scan to see if an instruction or explicit pattern already matches this.
1866 bool AlreadyExists = false;
1867 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1868 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001869 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001870 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1871 AlreadyExists = true;
1872 break;
1873 }
1874 }
1875 // If we already have it, ignore the variant.
1876 if (AlreadyExists) continue;
1877
1878 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001879 PatternsToMatch.
1880 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
Evan Cheng59413202006-04-19 18:07:24 +00001881 Variant, PatternsToMatch[i].getDstPattern(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001882 PatternsToMatch[i].getAddedComplexity()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001883 }
1884
1885 DEBUG(std::cerr << "\n");
1886 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001887}
1888
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001889
Evan Cheng0fc71982005-12-08 02:00:36 +00001890// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1891// ComplexPattern.
1892static bool NodeIsComplexPattern(TreePatternNode *N)
1893{
1894 return (N->isLeaf() &&
1895 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1896 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1897 isSubClassOf("ComplexPattern"));
1898}
1899
1900// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1901// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1902static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1903 DAGISelEmitter &ISE)
1904{
1905 if (N->isLeaf() &&
1906 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1907 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1908 isSubClassOf("ComplexPattern")) {
1909 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1910 ->getDef());
1911 }
1912 return NULL;
1913}
1914
Chris Lattner05814af2005-09-28 17:57:56 +00001915/// getPatternSize - Return the 'size' of this pattern. We want to match large
1916/// patterns before small ones. This is used to determine the size of a
1917/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001918static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng2618d072006-05-17 20:37:59 +00001919 assert((isExtIntegerInVTs(P->getExtTypes()) ||
1920 isExtFloatingPointInVTs(P->getExtTypes()) ||
1921 P->getExtTypeNum(0) == MVT::isVoid ||
1922 P->getExtTypeNum(0) == MVT::Flag ||
1923 P->getExtTypeNum(0) == MVT::iPTR) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +00001924 "Not a valid pattern node to size!");
Evan Chenge1050d62006-01-06 02:30:23 +00001925 unsigned Size = 2; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00001926 // If the root node is a ConstantSDNode, increases its size.
1927 // e.g. (set R32:$dst, 0).
1928 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1929 Size++;
Evan Cheng0fc71982005-12-08 02:00:36 +00001930
1931 // FIXME: This is a hack to statically increase the priority of patterns
1932 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1933 // Later we can allow complexity / cost for each pattern to be (optionally)
1934 // specified. To get best possible pattern match we'll need to dynamically
1935 // calculate the complexity of all patterns a dag can potentially map to.
1936 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1937 if (AM)
Evan Cheng4a7c2842006-01-06 22:19:44 +00001938 Size += AM->getNumOperands() * 2;
Chris Lattner3e179802006-02-03 18:06:02 +00001939
1940 // If this node has some predicate function that must match, it adds to the
1941 // complexity of this node.
1942 if (!P->getPredicateFn().empty())
1943 ++Size;
1944
Chris Lattner05814af2005-09-28 17:57:56 +00001945 // Count children in the count if they are also nodes.
1946 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1947 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001948 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001949 Size += getPatternSize(Child, ISE);
1950 else if (Child->isLeaf()) {
1951 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner3e179802006-02-03 18:06:02 +00001952 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
Evan Cheng4a7c2842006-01-06 22:19:44 +00001953 else if (NodeIsComplexPattern(Child))
1954 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00001955 else if (!Child->getPredicateFn().empty())
1956 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001957 }
Chris Lattner05814af2005-09-28 17:57:56 +00001958 }
1959
1960 return Size;
1961}
1962
1963/// getResultPatternCost - Compute the number of instructions for this pattern.
1964/// This is a temporary hack. We should really include the instruction
1965/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00001966static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00001967 if (P->isLeaf()) return 0;
1968
Evan Chengfbad7082006-02-18 02:33:09 +00001969 unsigned Cost = 0;
1970 Record *Op = P->getOperator();
1971 if (Op->isSubClassOf("Instruction")) {
1972 Cost++;
1973 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1974 if (II.usesCustomDAGSchedInserter)
1975 Cost += 10;
1976 }
Chris Lattner05814af2005-09-28 17:57:56 +00001977 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00001978 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001979 return Cost;
1980}
1981
1982// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1983// In particular, we want to match maximal patterns first and lowest cost within
1984// a particular complexity first.
1985struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001986 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1987 DAGISelEmitter &ISE;
1988
Evan Cheng58e84a62005-12-14 22:02:59 +00001989 bool operator()(PatternToMatch *LHS,
1990 PatternToMatch *RHS) {
1991 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1992 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Evan Chengc81d2a02006-04-19 20:36:09 +00001993 LHSSize += LHS->getAddedComplexity();
1994 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +00001995 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1996 if (LHSSize < RHSSize) return false;
1997
1998 // If the patterns have equal complexity, compare generated instruction cost
Evan Chengfbad7082006-02-18 02:33:09 +00001999 return getResultPatternCost(LHS->getDstPattern(), ISE) <
2000 getResultPatternCost(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002001 }
2002};
2003
Nate Begeman6510b222005-12-01 04:51:06 +00002004/// getRegisterValueType - Look up and return the first ValueType of specified
2005/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00002006static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00002007 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2008 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00002009 return MVT::Other;
2010}
2011
Chris Lattner72fe91c2005-09-24 00:40:24 +00002012
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002013/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2014/// type information from it.
2015static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00002016 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002017 if (!N->isLeaf())
2018 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2019 RemoveAllTypes(N->getChild(i));
2020}
Chris Lattner72fe91c2005-09-24 00:40:24 +00002021
Chris Lattner0614b622005-11-02 06:49:14 +00002022Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2023 Record *N = Records.getDef(Name);
Chris Lattner5a1df382006-03-24 23:10:39 +00002024 if (!N || !N->isSubClassOf("SDNode")) {
2025 std::cerr << "Error getting SDNode '" << Name << "'!\n";
2026 exit(1);
2027 }
Chris Lattner0614b622005-11-02 06:49:14 +00002028 return N;
2029}
2030
Evan Cheng51fecc82006-01-09 18:27:06 +00002031/// NodeHasProperty - return true if TreePatternNode has the specified
2032/// property.
2033static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2034 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002035{
2036 if (N->isLeaf()) return false;
2037 Record *Operator = N->getOperator();
2038 if (!Operator->isSubClassOf("SDNode")) return false;
2039
2040 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00002041 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002042}
2043
Evan Cheng51fecc82006-01-09 18:27:06 +00002044static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2045 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002046{
Evan Cheng51fecc82006-01-09 18:27:06 +00002047 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00002048 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00002049
2050 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2051 TreePatternNode *Child = N->getChild(i);
2052 if (PatternHasProperty(Child, Property, ISE))
2053 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002054 }
2055
2056 return false;
2057}
2058
Evan Chengb915f312005-12-09 22:45:35 +00002059class PatternCodeEmitter {
2060private:
2061 DAGISelEmitter &ISE;
2062
Evan Cheng58e84a62005-12-14 22:02:59 +00002063 // Predicates.
2064 ListInit *Predicates;
Evan Cheng59413202006-04-19 18:07:24 +00002065 // Pattern cost.
2066 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +00002067 // Instruction selector pattern.
2068 TreePatternNode *Pattern;
2069 // Matched instruction.
2070 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002071
Evan Chengb915f312005-12-09 22:45:35 +00002072 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00002073 std::map<std::string, std::string> VariableMap;
2074 // Node to operator mapping
2075 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00002076 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002077 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00002078 std::set<std::string> Duplicates;
Evan Cheng61a02092006-04-28 02:08:10 +00002079 /// These nodes are being marked "in-flight" so they cannot be folded.
2080 std::vector<std::string> InflightNodes;
Evan Chengb915f312005-12-09 22:45:35 +00002081
Chris Lattner8a0604b2006-01-28 20:31:24 +00002082 /// GeneratedCode - This is the buffer that we emit code to. The first bool
2083 /// indicates whether this is an exit predicate (something that should be
2084 /// tested, and if true, the match fails) [when true] or normal code to emit
2085 /// [when false].
2086 std::vector<std::pair<bool, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002087 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2088 /// the set of patterns for each top-level opcode.
Evan Chengd7805a72006-02-09 07:16:09 +00002089 std::set<std::pair<bool, std::string> > &GeneratedDecl;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002090
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002091 std::string ChainName;
Evan Chenged66e852006-03-09 08:19:11 +00002092 bool NewTF;
Evan Chenge41bf822006-02-05 06:43:12 +00002093 bool DoReplace;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002094 unsigned TmpNo;
2095
2096 void emitCheck(const std::string &S) {
2097 if (!S.empty())
2098 GeneratedCode.push_back(std::make_pair(true, S));
2099 }
2100 void emitCode(const std::string &S) {
2101 if (!S.empty())
2102 GeneratedCode.push_back(std::make_pair(false, S));
2103 }
Evan Chengd7805a72006-02-09 07:16:09 +00002104 void emitDecl(const std::string &S, bool isSDNode=false) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002105 assert(!S.empty() && "Invalid declaration");
Evan Chengd7805a72006-02-09 07:16:09 +00002106 GeneratedDecl.insert(std::make_pair(isSDNode, S));
Evan Cheng21ad3922006-02-07 00:37:41 +00002107 }
Evan Chengb915f312005-12-09 22:45:35 +00002108public:
Evan Cheng58e84a62005-12-14 22:02:59 +00002109 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2110 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng21ad3922006-02-07 00:37:41 +00002111 std::vector<std::pair<bool, std::string> > &gc,
Evan Chengd7805a72006-02-09 07:16:09 +00002112 std::set<std::pair<bool, std::string> > &gd,
Evan Cheng21ad3922006-02-07 00:37:41 +00002113 bool dorep)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002114 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Chenged66e852006-03-09 08:19:11 +00002115 GeneratedCode(gc), GeneratedDecl(gd),
2116 NewTF(false), DoReplace(dorep), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00002117
2118 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2119 /// if the match fails. At this point, we already know that the opcode for N
2120 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00002121 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2122 const std::string &RootName, const std::string &ParentName,
2123 const std::string &ChainSuffix, bool &FoundChain) {
2124 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00002125 // Emit instruction predicates. Each predicate is just a string for now.
2126 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002127 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00002128 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2129 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2130 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002131 if (!Def->isSubClassOf("Predicate")) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002132 Def->dump();
2133 assert(0 && "Unknown predicate type!");
2134 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002135 if (!PredicateCheck.empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002136 PredicateCheck += " || ";
2137 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00002138 }
2139 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002140
2141 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00002142 }
2143
Evan Chengb915f312005-12-09 22:45:35 +00002144 if (N->isLeaf()) {
2145 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002146 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00002147 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002148 return;
2149 } else if (!NodeIsComplexPattern(N)) {
2150 assert(0 && "Cannot match this as a leaf value!");
2151 abort();
2152 }
2153 }
2154
Chris Lattner488580c2006-01-28 19:06:51 +00002155 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002156 // we already saw this in the pattern, emit code to verify dagness.
2157 if (!N->getName().empty()) {
2158 std::string &VarMapEntry = VariableMap[N->getName()];
2159 if (VarMapEntry.empty()) {
2160 VarMapEntry = RootName;
2161 } else {
2162 // If we get here, this is a second reference to a specific name. Since
2163 // we already have checked that the first reference is valid, we don't
2164 // have to recursively match it, just check that it's the same as the
2165 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002166 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00002167 return;
2168 }
Evan Chengf805c2e2006-01-12 19:35:54 +00002169
2170 if (!N->isLeaf())
2171 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00002172 }
2173
2174
2175 // Emit code to load the child nodes and match their contents recursively.
2176 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00002177 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2178 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2179 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00002180 bool EmittedUseCheck = false;
2181 bool EmittedSlctedCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00002182 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00002183 if (NodeHasChain)
2184 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00002185 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00002186 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Evan Cheng61a02092006-04-28 02:08:10 +00002187 // Not in flight?
Evan Cheng55d0fa12006-04-28 18:54:11 +00002188 emitCheck("InFlightSet.count(" + RootName + ".Val) == 0");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002189 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002190 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002191 EmittedUseCheck = true;
2192 // hasOneUse() check is not strong enough. If the original node has
2193 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002194 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002195 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002196 "))");
2197
Evan Cheng1feeeec2006-01-26 19:13:45 +00002198 EmittedSlctedCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002199 if (NodeHasChain) {
2200 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2201 // has a chain use.
2202 // This a workaround for this problem:
2203 //
2204 // [ch, r : ld]
2205 // ^ ^
2206 // | |
2207 // [XX]--/ \- [flag : cmp]
2208 // ^ ^
2209 // | |
2210 // \---[br flag]-
2211 //
2212 // cmp + br should be considered as a single node as they are flagged
2213 // together. So, if the ld is folded into the cmp, the XX node in the
2214 // graph is now both an operand and a use of the ld/cmp/br node.
2215 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2216 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2217
2218 // If the immediate use can somehow reach this node through another
2219 // path, then can't fold it either or it will create a cycle.
2220 // e.g. In the following diagram, XX can reach ld through YY. If
2221 // ld is folded into XX, then YY is both a predecessor and a successor
2222 // of XX.
2223 //
2224 // [ld]
2225 // ^ ^
2226 // | |
2227 // / \---
2228 // / [YY]
2229 // | ^
2230 // [XX]-------|
2231 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2232 if (PInfo.getNumOperands() > 1 ||
2233 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2234 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2235 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
Evan Cheng6f8aaf22006-03-07 08:31:27 +00002236 if (PInfo.getNumOperands() > 1) {
2237 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2238 ".Val)");
2239 } else {
2240 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2241 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2242 ".Val))");
2243 }
Evan Chenge41bf822006-02-05 06:43:12 +00002244 }
Evan Chengb915f312005-12-09 22:45:35 +00002245 }
Evan Chenge41bf822006-02-05 06:43:12 +00002246
Evan Chengc15d18c2006-01-27 22:13:45 +00002247 if (NodeHasChain) {
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002248 ChainName = "Chain" + ChainSuffix;
Evan Cheng21ad3922006-02-07 00:37:41 +00002249 emitDecl(ChainName);
Evan Chenged66e852006-03-09 08:19:11 +00002250 if (FoundChain) {
2251 // FIXME: temporary workaround for a common case where chain
2252 // is a TokenFactor and the previous "inner" chain is an operand.
2253 NewTF = true;
2254 emitDecl("OldTF", true);
2255 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2256 RootName + ".Val, Chain.Val, OldTF)).Val");
2257 } else {
2258 FoundChain = true;
2259 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2260 }
Evan Cheng1cf6db22006-01-06 00:41:12 +00002261 }
Evan Chengb915f312005-12-09 22:45:35 +00002262 }
2263
Evan Cheng54597732006-01-26 00:22:25 +00002264 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002265 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002266 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002267 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2268 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002269 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002270 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2271 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2272 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002273 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2274 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002275 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002276 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002277 }
Evan Cheng1feeeec2006-01-26 19:13:45 +00002278 if (!EmittedSlctedCheck)
2279 // hasOneUse() check is not strong enough. If the original node has
2280 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002281 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002282 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002283 "))");
Evan Cheng54597732006-01-26 00:22:25 +00002284 }
2285
Evan Chengb915f312005-12-09 22:45:35 +00002286 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002287 emitDecl(RootName + utostr(OpNo));
2288 emitCode(RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002289 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002290 TreePatternNode *Child = N->getChild(i);
2291
2292 if (!Child->isLeaf()) {
2293 // If it's not a leaf, recursively match.
2294 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002295 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002296 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002297 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2298 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002299 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002300 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2301 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002302 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002303 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002304 // we already saw this in the pattern, emit code to verify dagness.
2305 if (!Child->getName().empty()) {
2306 std::string &VarMapEntry = VariableMap[Child->getName()];
2307 if (VarMapEntry.empty()) {
2308 VarMapEntry = RootName + utostr(OpNo);
2309 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002310 // If we get here, this is a second reference to a specific name.
2311 // Since we already have checked that the first reference is valid,
2312 // we don't have to recursively match it, just check that it's the
2313 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002314 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002315 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002316 continue;
2317 }
2318 }
2319
2320 // Handle leaves of various types.
2321 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2322 Record *LeafRec = DI->getDef();
2323 if (LeafRec->isSubClassOf("RegisterClass")) {
2324 // Handle register references. Nothing to do here.
2325 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002326 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002327 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2328 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00002329 } else if (LeafRec->getName() == "srcvalue") {
2330 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002331 } else if (LeafRec->isSubClassOf("ValueType")) {
2332 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002333 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002334 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002335 } else if (LeafRec->isSubClassOf("CondCode")) {
2336 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002337 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002338 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002339 } else {
2340 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002341 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00002342 assert(0 && "Unknown leaf type!");
2343 }
Chris Lattner488580c2006-01-28 19:06:51 +00002344 } else if (IntInit *II =
2345 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002346 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2347 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002348 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002349 RootName + utostr(OpNo) + ")->getSignExtended();");
2350
2351 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002352 } else {
2353 Child->dump();
2354 assert(0 && "Unknown leaf type!");
2355 }
2356 }
2357 }
2358
2359 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002360 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002361 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002362 }
2363
2364 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2365 /// we actually have to build a DAG!
2366 std::pair<unsigned, unsigned>
Chris Lattner947604b2006-03-24 21:52:20 +00002367 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2368 bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002369 // This is something selected from the pattern we matched.
2370 if (!N->getName().empty()) {
Evan Chengb915f312005-12-09 22:45:35 +00002371 std::string &Val = VariableMap[N->getName()];
2372 assert(!Val.empty() &&
2373 "Variable referenced but not defined and not caught earlier!");
2374 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2375 // Already selected this operand, just return the tmpval.
2376 return std::make_pair(1, atoi(Val.c_str()+3));
2377 }
2378
2379 const ComplexPattern *CP;
2380 unsigned ResNo = TmpNo++;
2381 unsigned NumRes = 1;
2382 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002383 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002384 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002385 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002386 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002387 case MVT::i1: CastType = "bool"; break;
2388 case MVT::i8: CastType = "unsigned char"; break;
2389 case MVT::i16: CastType = "unsigned short"; break;
2390 case MVT::i32: CastType = "unsigned"; break;
2391 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002392 }
Chris Lattner78593132006-01-29 20:01:35 +00002393 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
Andrew Lenharth2cba57c2006-01-29 05:17:22 +00002394 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
Evan Cheng21ad3922006-02-07 00:37:41 +00002395 emitDecl("Tmp" + utostr(ResNo));
2396 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002397 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
Evan Cheng2618d072006-05-17 20:37:59 +00002398 "C, " + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengbb48e332006-01-12 07:54:57 +00002399 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002400 Record *Op = OperatorMap[N->getName()];
2401 // Transform ExternalSymbol to TargetExternalSymbol
2402 if (Op && Op->getName() == "externalsym") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002403 emitDecl("Tmp" + utostr(ResNo));
2404 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002405 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002406 Val + ")->getSymbol(), " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002407 getEnumName(N->getTypeNum(0)) + ");");
2408 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002409 emitDecl("Tmp" + utostr(ResNo));
2410 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002411 }
Evan Chengb915f312005-12-09 22:45:35 +00002412 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002413 Record *Op = OperatorMap[N->getName()];
2414 // Transform GlobalAddress to TargetGlobalAddress
2415 if (Op && Op->getName() == "globaladdr") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002416 emitDecl("Tmp" + utostr(ResNo));
2417 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002418 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
Evan Cheng2618d072006-05-17 20:37:59 +00002419 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002420 ");");
2421 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002422 emitDecl("Tmp" + utostr(ResNo));
2423 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002424 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002425 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng21ad3922006-02-07 00:37:41 +00002426 emitDecl("Tmp" + utostr(ResNo));
2427 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengbb48e332006-01-12 07:54:57 +00002428 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002429 emitDecl("Tmp" + utostr(ResNo));
2430 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002431 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2432 std::string Fn = CP->getSelectFunc();
2433 NumRes = CP->getNumOperands();
Evan Cheng21ad3922006-02-07 00:37:41 +00002434 for (unsigned i = 0; i < NumRes; ++i)
Evan Chengb0793f92006-05-25 00:21:44 +00002435 emitDecl("CPTmp" + utostr(i+ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002436
Evan Chengb0793f92006-05-25 00:21:44 +00002437 std::string Code = "bool Match = " + Fn + "(" + Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002438 for (unsigned i = 0; i < NumRes; i++)
Evan Chengb0793f92006-05-25 00:21:44 +00002439 Code += ", CPTmp" + utostr(i + ResNo);
2440 emitCode(Code + ");");
2441 if (InflightNodes.size()) {
2442 // Remove the in-flight nodes if the ComplexPattern does not match!
2443 emitCode("if (!Match) {");
2444 for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2445 AE = InflightNodes.end(); AI != AE; ++AI)
2446 emitCode(" InFlightSet.erase(" + *AI + ".Val);");
2447 emitCode("}");
2448 }
2449
2450 emitCheck("Match");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002451
Evan Cheng61a02092006-04-28 02:08:10 +00002452 for (unsigned i = 0; i < NumRes; ++i) {
Evan Chengb0793f92006-05-25 00:21:44 +00002453 emitCode("InFlightSet.insert(CPTmp" + utostr(i+ResNo) + ".Val);");
2454 InflightNodes.push_back("CPTmp" + utostr(i+ResNo));
Evan Cheng61a02092006-04-28 02:08:10 +00002455 }
Evan Chengb0793f92006-05-25 00:21:44 +00002456 for (unsigned i = 0; i < NumRes; ++i) {
2457 emitDecl("Tmp" + utostr(i+ResNo));
2458 emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" +
Evan Cheng2216d8a2006-02-05 05:22:18 +00002459 utostr(i+ResNo) + ");");
Evan Chengb0793f92006-05-25 00:21:44 +00002460 }
Evan Cheng9c4815a2006-02-04 08:50:49 +00002461
Evan Chengb915f312005-12-09 22:45:35 +00002462 TmpNo = ResNo + NumRes;
2463 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002464 emitDecl("Tmp" + utostr(ResNo));
Evan Cheng863bf5a2006-03-20 22:53:06 +00002465 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2466 // node even if it isn't one. Don't select it.
2467 if (LikeLeaf)
2468 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Cheng61a02092006-04-28 02:08:10 +00002469 else {
Evan Cheng863bf5a2006-03-20 22:53:06 +00002470 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
Evan Cheng61a02092006-04-28 02:08:10 +00002471 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00002472
2473 if (isRoot && N->isLeaf()) {
2474 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2475 emitCode("return;");
2476 }
Evan Chengb915f312005-12-09 22:45:35 +00002477 }
2478 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2479 // value if used multiple times by this pattern result.
2480 Val = "Tmp"+utostr(ResNo);
2481 return std::make_pair(NumRes, ResNo);
2482 }
Evan Chengb915f312005-12-09 22:45:35 +00002483 if (N->isLeaf()) {
2484 // If this is an explicit register reference, handle it.
2485 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2486 unsigned ResNo = TmpNo++;
2487 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002488 emitDecl("Tmp" + utostr(ResNo));
2489 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002490 ISE.getQualifiedName(DI->getDef()) + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002491 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002492 return std::make_pair(1, ResNo);
2493 }
2494 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2495 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002496 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng21ad3922006-02-07 00:37:41 +00002497 emitDecl("Tmp" + utostr(ResNo));
2498 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002499 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
Evan Cheng2618d072006-05-17 20:37:59 +00002500 ", " + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002501 return std::make_pair(1, ResNo);
2502 }
2503
2504 N->dump();
2505 assert(0 && "Unknown leaf type!");
2506 return std::make_pair(1, ~0U);
2507 }
2508
2509 Record *Op = N->getOperator();
2510 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002511 const CodeGenTarget &CGT = ISE.getTargetInfo();
2512 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002513 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng045953c2006-05-10 00:05:46 +00002514 TreePattern *InstPat = Inst.getPattern();
2515 TreePatternNode *InstPatNode =
2516 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2517 : (InstPat ? InstPat->getOnlyTree() : NULL);
2518 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2519 InstPatNode = InstPatNode->getChild(1);
2520 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002521 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
Evan Cheng045953c2006-05-10 00:05:46 +00002522 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2523 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2524 bool NodeHasOptInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002525 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002526 bool NodeHasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002527 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002528 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2529 PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2530 bool NodeHasChain = InstPatNode &&
2531 PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002532 bool InputHasChain = isRoot &&
2533 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng4fba2812005-12-20 07:37:41 +00002534
Evan Cheng045953c2006-05-10 00:05:46 +00002535 if (NodeHasInFlag || NodeHasOutFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng21ad3922006-02-07 00:37:41 +00002536 emitDecl("InFlag");
Evan Chenge945f4d2006-06-14 22:22:20 +00002537 if (NodeHasOptInFlag)
2538 emitCode("bool HasInFlag = "
Evan Chengbc6b86a2006-06-14 19:27:50 +00002539 "N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag;");
Evan Chenge945f4d2006-06-14 22:22:20 +00002540 if (HasVarOps)
2541 emitCode("std::vector<SDOperand> Ops;");
Evan Cheng4fba2812005-12-20 07:37:41 +00002542
Evan Cheng823b7522006-01-19 21:57:10 +00002543 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002544 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002545 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2546 MVT::ValueType VT = Pattern->getTypeNum(i);
2547 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002548 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002549 }
2550
Evan Chengb915f312005-12-09 22:45:35 +00002551 // Determine operand emission order. Complex pattern first.
2552 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2553 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2554 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2555 TreePatternNode *Child = N->getChild(i);
2556 if (i == 0) {
2557 EmitOrder.push_back(std::make_pair(i, Child));
2558 OI = EmitOrder.begin();
2559 } else if (NodeIsComplexPattern(Child)) {
2560 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2561 } else {
2562 EmitOrder.push_back(std::make_pair(i, Child));
2563 }
2564 }
2565
Evan Cheng61a02092006-04-28 02:08:10 +00002566 // Make sure these operands which would be selected won't be folded while
2567 // the isel traverses the DAG upward.
Evan Chengb915f312005-12-09 22:45:35 +00002568 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
Evan Cheng61a02092006-04-28 02:08:10 +00002569 TreePatternNode *Child = EmitOrder[i].second;
2570 if (!Child->getName().empty()) {
2571 std::string &Val = VariableMap[Child->getName()];
2572 assert(!Val.empty() &&
2573 "Variable referenced but not defined and not caught earlier!");
2574 if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) {
2575 emitCode("InFlightSet.insert(" + Val + ".Val);");
2576 InflightNodes.push_back(Val);
2577 }
2578 }
2579 }
2580
2581 // Emit all of the operands.
Evan Chengb0793f92006-05-25 00:21:44 +00002582 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
Evan Cheng61a02092006-04-28 02:08:10 +00002583 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
Evan Chengb915f312005-12-09 22:45:35 +00002584 unsigned OpOrder = EmitOrder[i].first;
2585 TreePatternNode *Child = EmitOrder[i].second;
2586 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2587 NumTemps[OpOrder] = NumTemp;
2588 }
2589
2590 // List all the operands in the right order.
2591 std::vector<unsigned> Ops;
2592 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2593 for (unsigned j = 0; j < NumTemps[i].first; j++)
2594 Ops.push_back(NumTemps[i].second + j);
2595 }
2596
Evan Chengb915f312005-12-09 22:45:35 +00002597 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +00002598 bool ChainEmitted = NodeHasChain;
2599 if (NodeHasChain)
Evan Cheng34167212006-02-09 00:37:58 +00002600 emitCode("Select(" + ChainName + ", " + ChainName + ");");
Evan Chengbc6b86a2006-06-14 19:27:50 +00002601 if (NodeHasInFlag || HasImpInputs)
Evan Cheng54597732006-01-26 00:22:25 +00002602 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
Evan Chengbc6b86a2006-06-14 19:27:50 +00002603 if (NodeHasOptInFlag) {
Evan Chenge945f4d2006-06-14 22:22:20 +00002604 emitCode("if (HasInFlag)");
Evan Chengbc6b86a2006-06-14 19:27:50 +00002605 emitCode(" Select(InFlag, N.getOperand(N.getNumOperands()-1));");
2606 }
Evan Chengb915f312005-12-09 22:45:35 +00002607
Evan Cheng045953c2006-05-10 00:05:46 +00002608 if (isRoot) {
2609 // The operands have been selected. Remove them from InFlightSet.
2610 for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2611 AE = InflightNodes.end(); AI != AE; ++AI)
2612 emitCode("InFlightSet.erase(" + *AI + ".Val);");
2613 }
2614
Evan Chengb915f312005-12-09 22:45:35 +00002615 unsigned NumResults = Inst.getNumResults();
2616 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002617 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2618 NodeHasOptInFlag) {
Evan Chenge945f4d2006-06-14 22:22:20 +00002619 std::string Code;
2620 std::string Code2;
2621 std::string NodeName;
2622 if (!isRoot) {
2623 NodeName = "Tmp" + utostr(ResNo);
2624 emitDecl(NodeName);
2625 Code2 = NodeName + " = SDOperand(";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002626 } else {
Evan Chenge945f4d2006-06-14 22:22:20 +00002627 NodeName = "ResNode";
2628 emitDecl(NodeName, true);
2629 Code2 = NodeName + " = ";
Evan Chengbcecf332005-12-17 01:19:28 +00002630 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002631 Code = "CurDAG->getTargetNode(" +
2632 II.Namespace + "::" + II.TheDef->getName();
2633
2634 // Output order: results, chain, flags
2635 // Result types.
2636 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2637 Code += ", " + getEnumName(N->getTypeNum(0));
2638 if (NodeHasChain)
2639 Code += ", MVT::Other";
2640 if (NodeHasOutFlag)
2641 Code += ", MVT::Flag";
2642
2643 // Inputs.
2644 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2645 if (HasVarOps)
2646 emitCode("Ops.push_back(Tmp" + utostr(Ops[i]) + ");");
2647 else
2648 Code += ", Tmp" + utostr(Ops[i]);
2649 }
2650
2651 if (HasVarOps) {
2652 if (NodeHasInFlag || HasImpInputs)
2653 emitCode("for (unsigned i = 2, e = N.getNumOperands()-1; "
2654 "i != e; ++i) {");
2655 else if (NodeHasOptInFlag)
2656 emitCode("for (unsigned i = 2, e = N.getNumOperands()-HasInFlag; "
2657 "i != e; ++i) {");
2658 else
2659 emitCode("for (unsigned i = 2, e = N.getNumOperands(); "
2660 "i != e; ++i) {");
2661 emitCode(" SDOperand VarOp(0, 0);");
2662 emitCode(" Select(VarOp, N.getOperand(i));");
2663 emitCode(" Ops.push_back(VarOp);");
2664 emitCode("}");
2665 }
2666
2667 if (NodeHasChain) {
2668 if (HasVarOps)
2669 emitCode("Ops.push_back(" + ChainName + ");");
2670 else
2671 Code += ", " + ChainName;
2672 }
2673 if (NodeHasInFlag || HasImpInputs) {
2674 if (HasVarOps)
2675 emitCode("Ops.push_back(InFlag);");
2676 else
2677 Code += ", InFlag";
2678 } else if (NodeHasOptInFlag && HasVarOps) {
2679 emitCode("if (HasInFlag)");
2680 emitCode(" Ops.push_back(InFlag);");
2681 }
2682
2683 if (HasVarOps)
2684 Code += ", Ops";
2685 else if (NodeHasOptInFlag)
2686 Code = "HasInFlag ? " + Code + ", InFlag) : " + Code;
2687
2688 if (!isRoot)
2689 Code += "), 0";
2690 emitCode(Code2 + Code + ");");
2691
2692 if (NodeHasChain)
2693 // Remember which op produces the chain.
2694 if (!isRoot)
2695 emitCode(ChainName + " = SDOperand(" + NodeName +
2696 ".Val, " + utostr(PatResults) + ");");
2697 else
2698 emitCode(ChainName + " = SDOperand(" + NodeName +
2699 ", " + utostr(PatResults) + ");");
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002700
Evan Cheng045953c2006-05-10 00:05:46 +00002701 if (!isRoot)
2702 return std::make_pair(1, ResNo);
2703
Evan Chenged66e852006-03-09 08:19:11 +00002704 if (NewTF)
2705 emitCode("if (OldTF) "
2706 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2707 ChainName + ".Val, 0);");
2708
2709 for (unsigned i = 0; i < NumResults; i++)
Evan Cheng67212a02006-02-09 22:12:27 +00002710 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002711 utostr(i) + ", ResNode, " + utostr(i) + ");");
Evan Chengf9fc25d2005-12-19 22:40:04 +00002712
Evan Cheng54597732006-01-26 00:22:25 +00002713 if (NodeHasOutFlag)
Evan Chengd7805a72006-02-09 07:16:09 +00002714 emitCode("InFlag = SDOperand(ResNode, " +
Evan Cheng045953c2006-05-10 00:05:46 +00002715 utostr(NumResults + (unsigned)NodeHasChain) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002716
Chris Lattner8a0604b2006-01-28 20:31:24 +00002717 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
Evan Chenged66e852006-03-09 08:19:11 +00002718 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2719 "0, ResNode, 0);");
2720 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00002721 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002722
Evan Cheng045953c2006-05-10 00:05:46 +00002723 if (InputHasChain) {
Evan Cheng67212a02006-02-09 22:12:27 +00002724 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Cheng3eff89b2006-05-10 02:47:57 +00002725 utostr(PatResults) + ", " + ChainName + ".Val, " +
2726 ChainName + ".ResNo" + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002727 if (DoReplace)
Evan Chenged66e852006-03-09 08:19:11 +00002728 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
Evan Cheng3eff89b2006-05-10 02:47:57 +00002729 utostr(PatResults) + ", " + ChainName + ".Val, " +
2730 ChainName + ".ResNo" + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002731 }
2732
Evan Cheng97938882005-12-22 02:24:50 +00002733 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002734 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002735 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng67212a02006-02-09 22:12:27 +00002736 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2737 FoldedChains[j].first + ".Val, " +
2738 utostr(FoldedChains[j].second) + ", ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002739 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002740
2741 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2742 std::string Code =
Evan Cheng67212a02006-02-09 22:12:27 +00002743 FoldedChains[j].first + ".Val, " +
2744 utostr(FoldedChains[j].second) + ", ";
2745 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002746 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002747 }
Evan Chengb915f312005-12-09 22:45:35 +00002748 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002749
Evan Cheng54597732006-01-26 00:22:25 +00002750 if (NodeHasOutFlag)
Evan Cheng67212a02006-02-09 22:12:27 +00002751 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Cheng045953c2006-05-10 00:05:46 +00002752 utostr(PatResults + (unsigned)InputHasChain) +
Evan Chenged66e852006-03-09 08:19:11 +00002753 ", InFlag.Val, InFlag.ResNo);");
Evan Cheng97938882005-12-22 02:24:50 +00002754
Evan Chenged66e852006-03-09 08:19:11 +00002755 // User does not expect the instruction would produce a chain!
Evan Cheng045953c2006-05-10 00:05:46 +00002756 bool AddedChain = NodeHasChain && !InputHasChain;
Evan Cheng54597732006-01-26 00:22:25 +00002757 if (AddedChain && NodeHasOutFlag) {
Evan Chenged66e852006-03-09 08:19:11 +00002758 if (PatResults == 0) {
Evan Chengd7805a72006-02-09 07:16:09 +00002759 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002760 } else {
Evan Chenged66e852006-03-09 08:19:11 +00002761 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
Evan Chengd7805a72006-02-09 07:16:09 +00002762 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002763 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002764 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002765 }
Evan Cheng3eff89b2006-05-10 02:47:57 +00002766 } else if (InputHasChain && !NodeHasChain) {
2767 // One of the inner node produces a chain.
2768 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2769 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2770 if (NodeHasOutFlag) {
2771 emitCode("else if (N.ResNo > " + utostr(PatResults) + ")");
2772 emitCode(" Result = SDOperand(ResNode, N.ResNo-1);");
2773 }
2774 emitCode("else");
Chris Lattner11bcd282006-06-09 23:59:44 +00002775 emitCode(" Result = SDOperand(" + ChainName + ".Val, " +
2776 ChainName + ".ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002777 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002778 emitCode("Result = SDOperand(ResNode, N.ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002779 }
Evan Chengb915f312005-12-09 22:45:35 +00002780 } else {
2781 // If this instruction is the root, and if there is only one use of it,
2782 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002783 emitCode("if (N.Val->hasOneUse()) {");
Evan Cheng34167212006-02-09 00:37:58 +00002784 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002785 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002786 if (N->getTypeNum(0) != MVT::isVoid)
Evan Cheng2618d072006-05-17 20:37:59 +00002787 Code += ", " + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002788 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002789 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002790 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002791 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002792 if (NodeHasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002793 Code += ", InFlag";
2794 emitCode(Code + ");");
2795 emitCode("} else {");
Evan Chengd7805a72006-02-09 07:16:09 +00002796 emitDecl("ResNode", true);
2797 Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002798 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002799 if (N->getTypeNum(0) != MVT::isVoid)
Evan Cheng2618d072006-05-17 20:37:59 +00002800 Code += ", " + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002801 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002802 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002803 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002804 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002805 if (NodeHasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002806 Code += ", InFlag";
2807 emitCode(Code + ");");
Chris Lattner11bcd282006-06-09 23:59:44 +00002808 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo"
2809 ", ResNode, 0);");
Evan Cheng67212a02006-02-09 22:12:27 +00002810 emitCode(" Result = SDOperand(ResNode, 0);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002811 emitCode("}");
Evan Chengb915f312005-12-09 22:45:35 +00002812 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002813
Evan Cheng34167212006-02-09 00:37:58 +00002814 if (isRoot)
2815 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002816 return std::make_pair(1, ResNo);
2817 } else if (Op->isSubClassOf("SDNodeXForm")) {
2818 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00002819 // PatLeaf node - the operand may or may not be a leaf node. But it should
2820 // behave like one.
2821 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
Evan Chengb915f312005-12-09 22:45:35 +00002822 unsigned ResNo = TmpNo++;
Evan Cheng21ad3922006-02-07 00:37:41 +00002823 emitDecl("Tmp" + utostr(ResNo));
2824 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Chris Lattner8a0604b2006-01-28 20:31:24 +00002825 + "(Tmp" + utostr(OpVal) + ".Val);");
Evan Chengb915f312005-12-09 22:45:35 +00002826 if (isRoot) {
Evan Cheng67212a02006-02-09 22:12:27 +00002827 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2828 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2829 utostr(ResNo) + ".ResNo);");
Evan Cheng34167212006-02-09 00:37:58 +00002830 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2831 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002832 }
2833 return std::make_pair(1, ResNo);
2834 } else {
2835 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002836 std::cerr << "\n";
2837 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002838 }
2839 }
2840
Chris Lattner488580c2006-01-28 19:06:51 +00002841 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2842 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002843 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2844 /// for, this returns true otherwise false if Pat has all types.
2845 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2846 const std::string &Prefix) {
2847 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +00002848 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +00002849 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002850 Pat->setTypes(Other->getExtTypes());
Evan Chengd7c2c862006-06-15 00:16:37 +00002851 emitCheck(Prefix + ".Val->getValueType(0) == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002852 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002853 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002854 }
2855
Evan Cheng51fecc82006-01-09 18:27:06 +00002856 unsigned OpNo =
2857 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002858 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2859 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2860 Prefix + utostr(OpNo)))
2861 return true;
2862 return false;
2863 }
2864
2865private:
Evan Cheng54597732006-01-26 00:22:25 +00002866 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002867 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002868 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2869 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002870 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002871 unsigned OpNo =
2872 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002873 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002874 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2875 TreePatternNode *Child = N->getChild(i);
2876 if (!Child->isLeaf()) {
Evan Cheng54597732006-01-26 00:22:25 +00002877 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002878 } else {
2879 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002880 if (!Child->getName().empty()) {
2881 std::string Name = RootName + utostr(OpNo);
2882 if (Duplicates.find(Name) != Duplicates.end())
2883 // A duplicate! Do not emit a copy for this node.
2884 continue;
2885 }
2886
Evan Chengb915f312005-12-09 22:45:35 +00002887 Record *RR = DI->getDef();
2888 if (RR->isSubClassOf("Register")) {
2889 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002890 if (RVT == MVT::Flag) {
Evan Cheng34167212006-02-09 00:37:58 +00002891 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
Evan Chengb2c6d492006-01-11 22:16:13 +00002892 } else {
2893 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002894 emitDecl("Chain");
2895 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002896 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002897 ChainEmitted = true;
2898 }
Evan Cheng34167212006-02-09 00:37:58 +00002899 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2900 RootName + utostr(OpNo) + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002901 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002902 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
Evan Cheng2618d072006-05-17 20:37:59 +00002903 ", " + getEnumName(RVT) + "), " +
Evan Chengd7805a72006-02-09 07:16:09 +00002904 RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng67212a02006-02-09 22:12:27 +00002905 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2906 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00002907 }
2908 }
2909 }
2910 }
2911 }
Evan Cheng54597732006-01-26 00:22:25 +00002912
Evan Chengbc6b86a2006-06-14 19:27:50 +00002913 if (HasInFlag)
2914 emitCode("Select(InFlag, " + RootName +
Evan Cheng34167212006-02-09 00:37:58 +00002915 ".getOperand(" + utostr(OpNo) + "));");
Evan Chengb915f312005-12-09 22:45:35 +00002916 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002917
2918 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002919 /// as specified by the instruction. It returns true if any copy is
2920 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002921 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002922 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002923 Record *Op = N->getOperator();
2924 if (Op->isSubClassOf("Instruction")) {
2925 const DAGInstruction &Inst = ISE.getInstruction(Op);
2926 const CodeGenTarget &CGT = ISE.getTargetInfo();
Evan Cheng4fba2812005-12-20 07:37:41 +00002927 unsigned NumImpResults = Inst.getNumImpResults();
2928 for (unsigned i = 0; i < NumImpResults; i++) {
2929 Record *RR = Inst.getImpResult(i);
2930 if (RR->isSubClassOf("Register")) {
2931 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2932 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002933 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002934 emitDecl("Chain");
2935 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002936 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002937 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002938 }
Evan Chengd7805a72006-02-09 07:16:09 +00002939 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
Evan Cheng2618d072006-05-17 20:37:59 +00002940 ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00002941 ", InFlag).Val;");
2942 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2943 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002944 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002945 }
2946 }
2947 }
2948 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002949 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002950 }
Evan Chengb915f312005-12-09 22:45:35 +00002951};
2952
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002953/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2954/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00002955/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00002956void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Chenge41bf822006-02-05 06:43:12 +00002957 std::vector<std::pair<bool, std::string> > &GeneratedCode,
Evan Chengd7805a72006-02-09 07:16:09 +00002958 std::set<std::pair<bool, std::string> > &GeneratedDecl,
Evan Chenge41bf822006-02-05 06:43:12 +00002959 bool DoReplace) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002960 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2961 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Cheng21ad3922006-02-07 00:37:41 +00002962 GeneratedCode, GeneratedDecl, DoReplace);
Evan Chengb915f312005-12-09 22:45:35 +00002963
Chris Lattner8fc35682005-09-23 23:16:51 +00002964 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002965 bool FoundChain = false;
Evan Chenge41bf822006-02-05 06:43:12 +00002966 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002967
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002968 // TP - Get *SOME* tree pattern, we don't care which.
2969 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002970
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002971 // At this point, we know that we structurally match the pattern, but the
2972 // types of the nodes may not match. Figure out the fewest number of type
2973 // comparisons we need to emit. For example, if there is only one integer
2974 // type supported by a target, there should be no type comparisons at all for
2975 // integer patterns!
2976 //
2977 // To figure out the fewest number of type checks needed, clone the pattern,
2978 // remove the types, then perform type inference on the pattern as a whole.
2979 // If there are unresolved types, emit an explicit check for those types,
2980 // apply the type to the tree, then rerun type inference. Iterate until all
2981 // types are resolved.
2982 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002983 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002984 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002985
2986 do {
2987 // Resolve/propagate as many types as possible.
2988 try {
2989 bool MadeChange = true;
2990 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00002991 MadeChange = Pat->ApplyTypeConstraints(TP,
2992 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00002993 } catch (...) {
2994 assert(0 && "Error: could not find consistent types for something we"
2995 " already decided was ok!");
2996 abort();
2997 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002998
Chris Lattner7e82f132005-10-15 21:34:21 +00002999 // Insert a check for an unresolved type and add it to the tree. If we find
3000 // an unresolved type to add a check for, this returns true and we iterate,
3001 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00003002 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00003003
Evan Cheng863bf5a2006-03-20 22:53:06 +00003004 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003005 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00003006}
3007
Chris Lattner24e00a42006-01-29 04:41:05 +00003008/// EraseCodeLine - Erase one code line from all of the patterns. If removing
3009/// a line causes any of them to be empty, remove them and return true when
3010/// done.
3011static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
3012 std::vector<std::pair<bool, std::string> > > >
3013 &Patterns) {
3014 bool ErasedPatterns = false;
3015 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3016 Patterns[i].second.pop_back();
3017 if (Patterns[i].second.empty()) {
3018 Patterns.erase(Patterns.begin()+i);
3019 --i; --e;
3020 ErasedPatterns = true;
3021 }
3022 }
3023 return ErasedPatterns;
3024}
3025
Chris Lattner8bc74722006-01-29 04:25:26 +00003026/// EmitPatterns - Emit code for at least one pattern, but try to group common
3027/// code together between the patterns.
3028void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
3029 std::vector<std::pair<bool, std::string> > > >
3030 &Patterns, unsigned Indent,
3031 std::ostream &OS) {
3032 typedef std::pair<bool, std::string> CodeLine;
3033 typedef std::vector<CodeLine> CodeList;
3034 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3035
3036 if (Patterns.empty()) return;
3037
Chris Lattner24e00a42006-01-29 04:41:05 +00003038 // Figure out how many patterns share the next code line. Explicitly copy
3039 // FirstCodeLine so that we don't invalidate a reference when changing
3040 // Patterns.
3041 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00003042 unsigned LastMatch = Patterns.size()-1;
3043 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3044 --LastMatch;
3045
3046 // If not all patterns share this line, split the list into two pieces. The
3047 // first chunk will use this line, the second chunk won't.
3048 if (LastMatch != 0) {
3049 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3050 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3051
3052 // FIXME: Emit braces?
3053 if (Shared.size() == 1) {
3054 PatternToMatch &Pattern = *Shared.back().first;
3055 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3056 Pattern.getSrcPattern()->print(OS);
3057 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3058 Pattern.getDstPattern()->print(OS);
3059 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003060 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003061 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003062 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003063 << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00003064 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003065 }
3066 if (!FirstCodeLine.first) {
3067 OS << std::string(Indent, ' ') << "{\n";
3068 Indent += 2;
3069 }
3070 EmitPatterns(Shared, Indent, OS);
3071 if (!FirstCodeLine.first) {
3072 Indent -= 2;
3073 OS << std::string(Indent, ' ') << "}\n";
3074 }
3075
3076 if (Other.size() == 1) {
3077 PatternToMatch &Pattern = *Other.back().first;
3078 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3079 Pattern.getSrcPattern()->print(OS);
3080 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3081 Pattern.getDstPattern()->print(OS);
3082 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003083 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003084 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003085 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003086 << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00003087 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003088 }
3089 EmitPatterns(Other, Indent, OS);
3090 return;
3091 }
3092
Chris Lattner24e00a42006-01-29 04:41:05 +00003093 // Remove this code from all of the patterns that share it.
3094 bool ErasedPatterns = EraseCodeLine(Patterns);
3095
Chris Lattner8bc74722006-01-29 04:25:26 +00003096 bool isPredicate = FirstCodeLine.first;
3097
3098 // Otherwise, every pattern in the list has this line. Emit it.
3099 if (!isPredicate) {
3100 // Normal code.
3101 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3102 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00003103 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3104
3105 // If the next code line is another predicate, and if all of the pattern
3106 // in this group share the same next line, emit it inline now. Do this
3107 // until we run out of common predicates.
3108 while (!ErasedPatterns && Patterns.back().second.back().first) {
3109 // Check that all of fhe patterns in Patterns end with the same predicate.
3110 bool AllEndWithSamePredicate = true;
3111 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3112 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3113 AllEndWithSamePredicate = false;
3114 break;
3115 }
3116 // If all of the predicates aren't the same, we can't share them.
3117 if (!AllEndWithSamePredicate) break;
3118
3119 // Otherwise we can. Emit it shared now.
3120 OS << " &&\n" << std::string(Indent+4, ' ')
3121 << Patterns.back().second.back().second;
3122 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00003123 }
Chris Lattner24e00a42006-01-29 04:41:05 +00003124
3125 OS << ") {\n";
3126 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00003127 }
3128
3129 EmitPatterns(Patterns, Indent, OS);
3130
3131 if (isPredicate)
3132 OS << std::string(Indent-2, ' ') << "}\n";
3133}
3134
3135
Chris Lattner37481472005-09-26 21:59:35 +00003136
3137namespace {
3138 /// CompareByRecordName - An ordering predicate that implements less-than by
3139 /// comparing the names records.
3140 struct CompareByRecordName {
3141 bool operator()(const Record *LHS, const Record *RHS) const {
3142 // Sort by name first.
3143 if (LHS->getName() < RHS->getName()) return true;
3144 // If both names are equal, sort by pointer.
3145 return LHS->getName() == RHS->getName() && LHS < RHS;
3146 }
3147 };
3148}
3149
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003150void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003151 std::string InstNS = Target.inst_begin()->second.Namespace;
3152 if (!InstNS.empty()) InstNS += "::";
3153
Chris Lattner602f6922006-01-04 00:25:00 +00003154 // Group the patterns by their top-level opcodes.
3155 std::map<Record*, std::vector<PatternToMatch*>,
3156 CompareByRecordName> PatternsByOpcode;
3157 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3158 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3159 if (!Node->isLeaf()) {
3160 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3161 } else {
3162 const ComplexPattern *CP;
3163 if (IntInit *II =
3164 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3165 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3166 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3167 std::vector<Record*> OpNodes = CP->getRootNodes();
3168 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00003169 PatternsByOpcode[OpNodes[j]]
3170 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003171 }
3172 } else {
3173 std::cerr << "Unrecognized opcode '";
3174 Node->dump();
3175 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00003176 std::cerr <<
3177 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00003178 std::cerr << "'!\n";
3179 exit(1);
3180 }
3181 }
3182 }
3183
3184 // Emit one Select_* method for each top-level opcode. We do this instead of
3185 // emitting one giant switch statement to support compilers where this will
3186 // result in the recursive functions taking less stack space.
3187 for (std::map<Record*, std::vector<PatternToMatch*>,
3188 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3189 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00003190 const std::string &OpName = PBOI->first->getName();
Evan Cheng34167212006-02-09 00:37:58 +00003191 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003192
3193 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Evan Chenge41bf822006-02-05 06:43:12 +00003194 bool OptSlctOrder =
3195 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3196 OpcodeInfo.getNumResults() > 0);
3197
3198 if (OptSlctOrder) {
Evan Chenge41bf822006-02-05 06:43:12 +00003199 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3200 << " && N.getValue(0).hasOneUse()) {\n"
3201 << " SDOperand Dummy = "
3202 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003203 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3204 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3205 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3206 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003207 << " Result = Dummy;\n"
3208 << " return;\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003209 << " }\n";
3210 }
3211
Chris Lattner602f6922006-01-04 00:25:00 +00003212 std::vector<PatternToMatch*> &Patterns = PBOI->second;
Chris Lattner355408b2006-01-29 02:43:35 +00003213 assert(!Patterns.empty() && "No patterns but map has entry?");
Chris Lattner602f6922006-01-04 00:25:00 +00003214
3215 // We want to emit all of the matching code now. However, we want to emit
3216 // the matches in order of minimal cost. Sort the patterns so the least
3217 // cost one is at the start.
3218 std::stable_sort(Patterns.begin(), Patterns.end(),
3219 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00003220
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003221 typedef std::vector<std::pair<bool, std::string> > CodeList;
Evan Cheng21ad3922006-02-07 00:37:41 +00003222 typedef std::set<std::string> DeclSet;
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003223
3224 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
Evan Chengd7805a72006-02-09 07:16:09 +00003225 std::set<std::pair<bool, std::string> > GeneratedDecl;
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003226 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003227 CodeList GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00003228 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3229 OptSlctOrder);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003230 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3231 }
3232
3233 // Scan the code to see if all of the patterns are reachable and if it is
3234 // possible that the last one might not match.
3235 bool mightNotMatch = true;
3236 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3237 CodeList &GeneratedCode = CodeForPatterns[i].second;
3238 mightNotMatch = false;
Chris Lattner355408b2006-01-29 02:43:35 +00003239
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003240 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3241 if (GeneratedCode[j].first) { // predicate.
3242 mightNotMatch = true;
3243 break;
3244 }
3245 }
Chris Lattner355408b2006-01-29 02:43:35 +00003246
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003247 // If this pattern definitely matches, and if it isn't the last one, the
3248 // patterns after it CANNOT ever match. Error out.
3249 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3250 std::cerr << "Pattern '";
3251 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3252 std::cerr << "' is impossible to select!\n";
3253 exit(1);
3254 }
3255 }
Evan Cheng21ad3922006-02-07 00:37:41 +00003256
3257 // Print all declarations.
Chris Lattner947604b2006-03-24 21:52:20 +00003258 for (std::set<std::pair<bool, std::string> >::iterator
3259 I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
Evan Chengd7805a72006-02-09 07:16:09 +00003260 if (I->first)
3261 OS << " SDNode *" << I->second << ";\n";
3262 else
3263 OS << " SDOperand " << I->second << "(0, 0);\n";
Evan Cheng21ad3922006-02-07 00:37:41 +00003264
Chris Lattner8bc74722006-01-29 04:25:26 +00003265 // Loop through and reverse all of the CodeList vectors, as we will be
3266 // accessing them from their logical front, but accessing the end of a
3267 // vector is more efficient.
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003268 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3269 CodeList &GeneratedCode = CodeForPatterns[i].second;
Chris Lattner8bc74722006-01-29 04:25:26 +00003270 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003271 }
Chris Lattner602f6922006-01-04 00:25:00 +00003272
Chris Lattner8bc74722006-01-29 04:25:26 +00003273 // Next, reverse the list of patterns itself for the same reason.
3274 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3275
3276 // Emit all of the patterns now, grouped together to share code.
3277 EmitPatterns(CodeForPatterns, 2, OS);
3278
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003279 // If the last pattern has predicates (which could fail) emit code to catch
3280 // the case where nothing handles a pattern.
Chris Lattnerb026e702006-03-28 00:41:33 +00003281 if (mightNotMatch) {
3282 OS << " std::cerr << \"Cannot yet select: \";\n";
3283 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3284 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3285 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3286 OS << " N.Val->dump(CurDAG);\n";
3287 } else {
3288 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3289 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3290 << " std::cerr << \"intrinsic %\"<< "
3291 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3292 }
3293 OS << " std::cerr << '\\n';\n"
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003294 << " abort();\n";
Chris Lattnerb026e702006-03-28 00:41:33 +00003295 }
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003296 OS << "}\n\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003297 }
3298
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003299 // Emit boilerplate.
Evan Cheng34167212006-02-09 00:37:58 +00003300 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003301 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng34167212006-02-09 00:37:58 +00003302 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003303 << " // Select the flag operand.\n"
3304 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng34167212006-02-09 00:37:58 +00003305 << " Select(Ops.back(), Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00003306 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003307 << " std::vector<MVT::ValueType> VTs;\n"
3308 << " VTs.push_back(MVT::Other);\n"
3309 << " VTs.push_back(MVT::Flag);\n"
3310 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003311 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3312 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003313 << " Result = New.getValue(N.ResNo);\n"
3314 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003315 << "}\n\n";
3316
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003317 OS << "// The main instruction selector code.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003318 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003319 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003320 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003321 << "INSTRUCTION_LIST_END)) {\n"
3322 << " Result = N;\n"
3323 << " return; // Already selected.\n"
3324 << " }\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003325 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003326 << " if (CGMI != CodeGenMap.end()) {\n"
3327 << " Result = CGMI->second;\n"
3328 << " return;\n"
3329 << " }\n\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003330 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003331 << " default: break;\n"
3332 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003333 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003334 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003335 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003336 << " case ISD::TargetConstant:\n"
3337 << " case ISD::TargetConstantPool:\n"
3338 << " case ISD::TargetFrameIndex:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00003339 << " case ISD::TargetJumpTable:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003340 << " case ISD::TargetGlobalAddress: {\n"
3341 << " Result = N;\n"
3342 << " return;\n"
3343 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003344 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003345 << " case ISD::AssertZext: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003346 << " SDOperand Tmp0;\n"
3347 << " Select(Tmp0, N.getOperand(0));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003348 << " if (!N.Val->hasOneUse())\n"
3349 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3350 << "Tmp0.Val, Tmp0.ResNo);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003351 << " Result = Tmp0;\n"
3352 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003353 << " }\n"
3354 << " case ISD::TokenFactor:\n"
3355 << " if (N.getNumOperands() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003356 << " SDOperand Op0, Op1;\n"
3357 << " Select(Op0, N.getOperand(0));\n"
3358 << " Select(Op1, N.getOperand(1));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003359 << " Result = \n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003360 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003361 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3362 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003363 << " } else {\n"
3364 << " std::vector<SDOperand> Ops;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003365 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3366 << " SDOperand Val;\n"
3367 << " Select(Val, N.getOperand(i));\n"
3368 << " Ops.push_back(Val);\n"
3369 << " }\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003370 << " Result = \n"
3371 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3372 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3373 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003374 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003375 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003376 << " case ISD::CopyFromReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003377 << " SDOperand Chain;\n"
3378 << " Select(Chain, N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003379 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3380 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003381 << " if (N.Val->getNumValues() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003382 << " if (Chain == N.getOperand(0)) {\n"
3383 << " Result = N; // No change\n"
3384 << " return;\n"
3385 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003386 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003387 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3388 << "New.Val, 0);\n"
3389 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3390 << "New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003391 << " Result = New.getValue(N.ResNo);\n"
3392 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003393 << " } else {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003394 << " SDOperand Flag;\n"
3395 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003396 << " if (Chain == N.getOperand(0) &&\n"
Evan Cheng34167212006-02-09 00:37:58 +00003397 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3398 << " Result = N; // No change\n"
3399 << " return;\n"
3400 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003401 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003402 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3403 << "New.Val, 0);\n"
3404 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3405 << "New.Val, 1);\n"
3406 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3407 << "New.Val, 2);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003408 << " Result = New.getValue(N.ResNo);\n"
3409 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003410 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003411 << " }\n"
3412 << " case ISD::CopyToReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003413 << " SDOperand Chain;\n"
3414 << " Select(Chain, N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003415 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Evan Cheng34167212006-02-09 00:37:58 +00003416 << " SDOperand Val;\n"
3417 << " Select(Val, N.getOperand(2));\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003418 << " Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003419 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003420 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003421 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003422 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3423 << "Result.Val, 0);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003424 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003425 << " SDOperand Flag(0, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003426 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003427 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003428 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003429 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003430 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3431 << "Result.Val, 0);\n"
3432 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3433 << "Result.Val, 1);\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003434 << " Result = Result.getValue(N.ResNo);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003435 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003436 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003437 << " }\n"
Chris Lattner947604b2006-03-24 21:52:20 +00003438 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003439
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003440
Chris Lattner602f6922006-01-04 00:25:00 +00003441 // Loop over all of the case statements, emiting a call to each method we
3442 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003443 for (std::map<Record*, std::vector<PatternToMatch*>,
3444 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3445 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003446 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00003447 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00003448 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Evan Cheng34167212006-02-09 00:37:58 +00003449 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
Chris Lattner81303322005-09-23 19:36:15 +00003450 }
Chris Lattner81303322005-09-23 19:36:15 +00003451
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003452 OS << " } // end of big switch.\n\n"
3453 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00003454 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3455 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3456 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003457 << " N.Val->dump(CurDAG);\n"
3458 << " } else {\n"
3459 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3460 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3461 << " std::cerr << \"intrinsic %\"<< "
3462 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3463 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003464 << " std::cerr << '\\n';\n"
3465 << " abort();\n"
3466 << "}\n";
3467}
3468
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003469void DAGISelEmitter::run(std::ostream &OS) {
3470 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3471 " target", OS);
3472
Chris Lattner1f39e292005-09-14 00:09:24 +00003473 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3474 << "// *** instruction selector class. These functions are really "
3475 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003476
Chris Lattner296dfe32005-09-24 00:50:51 +00003477 OS << "// Instance var to keep track of multiply used nodes that have \n"
3478 << "// already been selected.\n"
3479 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003480
3481 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003482 << "// and their place handle nodes.\n";
3483 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3484 OS << "// Instance var to keep track of mapping of place handle nodes\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003485 << "// and their replacement nodes.\n";
3486 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
Evan Cheng61a02092006-04-28 02:08:10 +00003487 OS << "// Keep track of nodes that are currently being selecte and therefore\n"
3488 << "// should not be folded.\n";
3489 OS << "std::set<SDNode*> InFlightSet;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003490
3491 OS << "\n";
3492 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3493 << "std::set<SDNode *> &Visited) {\n";
3494 OS << " if (found || !Visited.insert(Use).second) return;\n";
3495 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3496 OS << " SDNode *N = Use->getOperand(i).Val;\n";
Evan Cheng553ef1b2006-05-25 20:16:55 +00003497 OS << " if (N != Def) {\n";
3498 OS << " findNonImmUse(N, Def, found, Visited);\n";
3499 OS << " } else {\n";
3500 OS << " found = true;\n";
3501 OS << " break;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003502 OS << " }\n";
3503 OS << " }\n";
3504 OS << "}\n";
3505
3506 OS << "\n";
3507 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3508 OS << " std::set<SDNode *> Visited;\n";
3509 OS << " bool found = false;\n";
3510 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3511 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3512 OS << " if (N != Def) {\n";
3513 OS << " findNonImmUse(N, Def, found, Visited);\n";
3514 OS << " if (found) break;\n";
3515 OS << " }\n";
3516 OS << " }\n";
3517 OS << " return found;\n";
3518 OS << "}\n";
3519
3520 OS << "\n";
Evan Cheng024524f2006-02-06 06:03:35 +00003521 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003522 << "// handle node in ReplaceMap.\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003523 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3524 << "unsigned RNum) {\n";
3525 OS << " SDOperand N(H, HNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003526 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3527 OS << " if (HMI != HandleMap.end()) {\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003528 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003529 OS << " HandleMap.erase(N);\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003530 OS << " }\n";
3531 OS << "}\n";
3532
3533 OS << "\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003534 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3535 OS << "// handles.Some handles do not yet have replacements because the\n";
3536 OS << "// nodes they replacements have only dead readers.\n";
3537 OS << "void SelectDanglingHandles() {\n";
3538 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3539 << "HandleMap.begin(),\n"
3540 << " E = HandleMap.end(); I != E; ++I) {\n";
3541 OS << " SDOperand N = I->first;\n";
Evan Cheng34167212006-02-09 00:37:58 +00003542 OS << " SDOperand R;\n";
3543 OS << " Select(R, N.getValue(0));\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003544 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003545 OS << " }\n";
3546 OS << "}\n";
3547 OS << "\n";
3548 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003549 OS << "// specific nodes.\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003550 OS << "void ReplaceHandles() {\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003551 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3552 << "ReplaceMap.begin(),\n"
3553 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3554 OS << " SDOperand From = I->first;\n";
3555 OS << " SDOperand To = I->second;\n";
3556 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3557 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3558 OS << " SDNode *Use = *UI;\n";
3559 OS << " std::vector<SDOperand> Ops;\n";
Chris Lattner11bcd282006-06-09 23:59:44 +00003560 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i){\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003561 OS << " SDOperand O = Use->getOperand(i);\n";
3562 OS << " if (O.Val == From.Val)\n";
3563 OS << " Ops.push_back(To);\n";
3564 OS << " else\n";
3565 OS << " Ops.push_back(O);\n";
3566 OS << " }\n";
3567 OS << " SDOperand U = SDOperand(Use, 0);\n";
3568 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3569 OS << " }\n";
3570 OS << " }\n";
3571 OS << "}\n";
3572
3573 OS << "\n";
Evan Chenged66e852006-03-09 08:19:11 +00003574 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3575 OS << "// if the folding were to happen. This is called when, for example,\n";
3576 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3577 OS << "// then the resulting node's input chain would be the load's input\n";
3578 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3579 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3580 OS << "// with the other operands along with the input chain of the load.\n";
3581 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3582 << "SDNode *Chain, SDNode* &OldTF) {\n";
3583 OS << " OldTF = NULL;\n";
3584 OS << " if (N == Chain) {\n";
3585 OS << " return N->getOperand(0);\n";
3586 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3587 OS << " N->isOperand(Chain)) {\n";
3588 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3589 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3590 << "CodeGenMap.find(Ch);\n";
3591 OS << " if (CGMI != CodeGenMap.end())\n";
3592 OS << " return SDOperand(0, 0);\n";
3593 OS << " OldTF = Chain;\n";
3594 OS << " std::vector<SDOperand> Ops;\n";
3595 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3596 OS << " SDOperand Op = Chain->getOperand(i);\n";
3597 OS << " if (Op.Val == N)\n";
3598 OS << " Ops.push_back(N->getOperand(0));\n";
3599 OS << " else\n";
3600 OS << " Ops.push_back(Op);\n";
3601 OS << " }\n";
3602 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3603 OS << " }\n";
3604 OS << " return SDOperand(0, 0);\n";
3605 OS << "}\n";
3606
3607 OS << "\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003608 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3609 OS << "SDOperand SelectRoot(SDOperand N) {\n";
Evan Cheng34167212006-02-09 00:37:58 +00003610 OS << " SDOperand ResNode;\n";
3611 OS << " Select(ResNode, N);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003612 OS << " SelectDanglingHandles();\n";
3613 OS << " ReplaceHandles();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003614 OS << " ReplaceMap.clear();\n";
Evan Cheng34167212006-02-09 00:37:58 +00003615 OS << " return ResNode;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003616 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003617
Chris Lattner550525e2006-03-24 21:48:51 +00003618 Intrinsics = LoadIntrinsics(Records);
Chris Lattnerca559d02005-09-08 21:03:01 +00003619 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003620 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003621 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003622 ParsePatternFragments(OS);
3623 ParseInstructions();
3624 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003625
Chris Lattnere97603f2005-09-28 19:27:25 +00003626 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003627 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003628 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003629
Chris Lattnere46e17b2005-09-29 19:28:10 +00003630
3631 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3632 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003633 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3634 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003635 std::cerr << "\n";
3636 });
3637
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003638 // At this point, we have full information about the 'Patterns' we need to
3639 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003640 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003641 EmitInstructionSelector(OS);
3642
3643 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3644 E = PatternFragments.end(); I != E; ++I)
3645 delete I->second;
3646 PatternFragments.clear();
3647
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003648 Instructions.clear();
3649}