blob: 9f1913798d823a856478b4401b83f5a687249d34 [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;
Chris Lattner02cdb372006-06-20 00:56:37 +0000439 default: {
440 std::string VTName = llvm::getName(getTypeNum(0));
441 // Strip off MVT:: prefix if present.
442 if (VTName.substr(0,5) == "MVT::")
443 VTName = VTName.substr(5);
444 OS << ":" << VTName;
445 break;
446 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000447 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000448
449 if (!isLeaf()) {
450 if (getNumChildren() != 0) {
451 OS << " ";
452 getChild(0)->print(OS);
453 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
454 OS << ", ";
455 getChild(i)->print(OS);
456 }
457 }
458 OS << ")";
459 }
460
461 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000462 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000463 if (TransformFn)
464 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000465 if (!getName().empty())
466 OS << ":$" << getName();
467
468}
469void TreePatternNode::dump() const {
470 print(std::cerr);
471}
472
Chris Lattnere46e17b2005-09-29 19:28:10 +0000473/// isIsomorphicTo - Return true if this node is recursively isomorphic to
474/// the specified node. For this comparison, all of the state of the node
475/// is considered, except for the assigned name. Nodes with differing names
476/// that are otherwise identical are considered isomorphic.
477bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
478 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000479 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000480 getPredicateFn() != N->getPredicateFn() ||
481 getTransformFn() != N->getTransformFn())
482 return false;
483
484 if (isLeaf()) {
485 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
486 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
487 return DI->getDef() == NDI->getDef();
488 return getLeafValue() == N->getLeafValue();
489 }
490
491 if (N->getOperator() != getOperator() ||
492 N->getNumChildren() != getNumChildren()) return false;
493 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
494 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
495 return false;
496 return true;
497}
498
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000499/// clone - Make a copy of this tree and all of its children.
500///
501TreePatternNode *TreePatternNode::clone() const {
502 TreePatternNode *New;
503 if (isLeaf()) {
504 New = new TreePatternNode(getLeafValue());
505 } else {
506 std::vector<TreePatternNode*> CChildren;
507 CChildren.reserve(Children.size());
508 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
509 CChildren.push_back(getChild(i)->clone());
510 New = new TreePatternNode(getOperator(), CChildren);
511 }
512 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000513 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000514 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000515 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000516 return New;
517}
518
Chris Lattner32707602005-09-08 23:22:48 +0000519/// SubstituteFormalArguments - Replace the formal arguments in this tree
520/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000521void TreePatternNode::
522SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
523 if (isLeaf()) return;
524
525 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
526 TreePatternNode *Child = getChild(i);
527 if (Child->isLeaf()) {
528 Init *Val = Child->getLeafValue();
529 if (dynamic_cast<DefInit*>(Val) &&
530 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
531 // We found a use of a formal argument, replace it with its value.
532 Child = ArgMap[Child->getName()];
533 assert(Child && "Couldn't find formal argument!");
534 setChild(i, Child);
535 }
536 } else {
537 getChild(i)->SubstituteFormalArguments(ArgMap);
538 }
539 }
540}
541
542
543/// InlinePatternFragments - If this pattern refers to any pattern
544/// fragments, inline them into place, giving us a pattern without any
545/// PatFrag references.
546TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
547 if (isLeaf()) return this; // nothing to do.
548 Record *Op = getOperator();
549
550 if (!Op->isSubClassOf("PatFrag")) {
551 // Just recursively inline children nodes.
552 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
553 setChild(i, getChild(i)->InlinePatternFragments(TP));
554 return this;
555 }
556
557 // Otherwise, we found a reference to a fragment. First, look up its
558 // TreePattern record.
559 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
560
561 // Verify that we are passing the right number of operands.
562 if (Frag->getNumArgs() != Children.size())
563 TP.error("'" + Op->getName() + "' fragment requires " +
564 utostr(Frag->getNumArgs()) + " operands!");
565
Chris Lattner37937092005-09-09 01:15:01 +0000566 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000567
568 // Resolve formal arguments to their actual value.
569 if (Frag->getNumArgs()) {
570 // Compute the map of formal to actual arguments.
571 std::map<std::string, TreePatternNode*> ArgMap;
572 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
573 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
574
575 FragTree->SubstituteFormalArguments(ArgMap);
576 }
577
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000578 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000579 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000580
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000581 // Get a new copy of this fragment to stitch into here.
582 //delete this; // FIXME: implement refcounting!
583 return FragTree;
584}
585
Chris Lattner52793e22006-04-06 20:19:52 +0000586/// getImplicitType - Check to see if the specified record has an implicit
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000587/// type which should be applied to it. This infer the type of register
588/// references from the register file information, for example.
589///
Chris Lattner52793e22006-04-06 20:19:52 +0000590static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000591 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000592 // Some common return values
593 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
594 std::vector<unsigned char> Other(1, MVT::Other);
595
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000596 // Check to see if this is a register or a register class...
597 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000598 if (NotRegisters)
599 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000600 const CodeGenRegisterClass &RC =
601 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000602 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000603 } else if (R->isSubClassOf("PatFrag")) {
604 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000605 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000606 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000607 if (NotRegisters)
608 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000609 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
Evan Cheng44a65fa2006-05-16 07:05:30 +0000610 return T.getRegisterVTs(R);
Chris Lattner1531f202005-10-26 16:59:37 +0000611 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
612 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000613 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000614 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000615 if (NotRegisters)
616 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000617 std::vector<unsigned char>
618 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
619 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000620 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000621 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000622 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000623 }
624
625 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000626 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000627}
628
Chris Lattner32707602005-09-08 23:22:48 +0000629/// ApplyTypeConstraints - Apply all of the type constraints relevent to
630/// this node and its children in the tree. This returns true if it makes a
631/// change, false otherwise. If a type contradiction is found, throw an
632/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000633bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000634 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000635 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000636 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000637 // If it's a regclass or something else known, include the type.
Chris Lattner52793e22006-04-06 20:19:52 +0000638 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000639 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
640 // Int inits are always integers. :)
641 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
642
643 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000644 // At some point, it may make sense for this tree pattern to have
645 // multiple types. Assert here that it does not, so we revisit this
646 // code when appropriate.
Evan Cheng2618d072006-05-17 20:37:59 +0000647 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Evan Cheng44a65fa2006-05-16 07:05:30 +0000648 MVT::ValueType VT = getTypeNum(0);
649 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
650 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000651
Evan Cheng2618d072006-05-17 20:37:59 +0000652 VT = getTypeNum(0);
653 if (VT != MVT::iPTR) {
654 unsigned Size = MVT::getSizeInBits(VT);
655 // Make sure that the value is representable for this type.
656 if (Size < 32) {
657 int Val = (II->getValue() << (32-Size)) >> (32-Size);
658 if (Val != II->getValue())
659 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
660 "' is out of range for type '" +
661 getEnumName(getTypeNum(0)) + "'!");
662 }
Chris Lattner465c7372005-11-03 05:46:11 +0000663 }
664 }
665
666 return MadeChange;
667 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000668 return false;
669 }
Chris Lattner32707602005-09-08 23:22:48 +0000670
671 // special handling for set, which isn't really an SDNode.
672 if (getOperator()->getName() == "set") {
673 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000674 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
675 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000676
677 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000678 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
679 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000680 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
681 return MadeChange;
Chris Lattner5a1df382006-03-24 23:10:39 +0000682 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
683 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
684 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
685 unsigned IID =
686 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
687 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
688 bool MadeChange = false;
689
690 // Apply the result type to the node.
691 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
692
693 if (getNumChildren() != Int.ArgVTs.size())
Chris Lattner2c4e65d2006-03-27 22:21:18 +0000694 TP.error("Intrinsic '" + Int.Name + "' expects " +
Chris Lattner5a1df382006-03-24 23:10:39 +0000695 utostr(Int.ArgVTs.size()-1) + " operands, not " +
696 utostr(getNumChildren()-1) + " operands!");
697
698 // Apply type info to the intrinsic ID.
Evan Cheng2618d072006-05-17 20:37:59 +0000699 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5a1df382006-03-24 23:10:39 +0000700
701 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
702 MVT::ValueType OpVT = Int.ArgVTs[i];
703 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
704 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
705 }
706 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000707 } else if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000708 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
Chris Lattnerabbb6052005-09-15 21:42:00 +0000709
710 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
711 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000712 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000713 // Branch, etc. do not produce results and top-level forms in instr pattern
714 // must have void types.
715 if (NI.getNumResults() == 0)
716 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner91ded082006-04-06 20:36:51 +0000717
718 // If this is a vector_shuffle operation, apply types to the build_vector
719 // operation. The types of the integers don't matter, but this ensures they
720 // won't get checked.
721 if (getOperator()->getName() == "vector_shuffle" &&
722 getChild(2)->getOperator()->getName() == "build_vector") {
723 TreePatternNode *BV = getChild(2);
724 const std::vector<MVT::ValueType> &LegalVTs
725 = ISE.getTargetInfo().getLegalValueTypes();
726 MVT::ValueType LegalIntVT = MVT::Other;
727 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
728 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
729 LegalIntVT = LegalVTs[i];
730 break;
731 }
732 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
733
734 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
735 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
736 }
Chris Lattnerabbb6052005-09-15 21:42:00 +0000737 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000738 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000739 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000740 bool MadeChange = false;
741 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000742
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000743 assert(NumResults <= 1 &&
744 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000745 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000746 if (NumResults == 0) {
747 MadeChange = UpdateNodeType(MVT::isVoid, TP);
748 } else {
749 Record *ResultNode = Inst.getResult(0);
750 assert(ResultNode->isSubClassOf("RegisterClass") &&
751 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000752
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000753 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000754 ISE.getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000755 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000756 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000757
758 if (getNumChildren() != Inst.getNumOperands())
759 TP.error("Instruction '" + getOperator()->getName() + " expects " +
760 utostr(Inst.getNumOperands()) + " operands, not " +
761 utostr(getNumChildren()) + " operands!");
762 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000763 Record *OperandNode = Inst.getOperand(i);
764 MVT::ValueType VT;
765 if (OperandNode->isSubClassOf("RegisterClass")) {
766 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000767 ISE.getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000768 //VT = RC.getValueTypeNum(0);
769 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
770 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000771 } else if (OperandNode->isSubClassOf("Operand")) {
772 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000773 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000774 } else {
775 assert(0 && "Unknown operand type!");
776 abort();
777 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000778 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000779 }
780 return MadeChange;
781 } else {
782 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
783
Evan Chengf26ba692006-03-20 08:09:17 +0000784 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000785 if (getNumChildren() != 1)
786 TP.error("Node transform '" + getOperator()->getName() +
787 "' requires one operand!");
Chris Lattner4e2f54d2006-03-21 06:42:58 +0000788
789 // If either the output or input of the xform does not have exact
790 // type info. We assume they must be the same. Otherwise, it is perfectly
791 // legal to transform from one type to a completely different type.
792 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Evan Chengf26ba692006-03-20 08:09:17 +0000793 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
794 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
795 return MadeChange;
796 }
797 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000798 }
Chris Lattner32707602005-09-08 23:22:48 +0000799}
800
Chris Lattnere97603f2005-09-28 19:27:25 +0000801/// canPatternMatch - If it is impossible for this pattern to match on this
802/// target, fill in Reason and return false. Otherwise, return true. This is
803/// used as a santity check for .td files (to prevent people from writing stuff
804/// that can never possibly work), and to prevent the pattern permuter from
805/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000806bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000807 if (isLeaf()) return true;
808
809 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
810 if (!getChild(i)->canPatternMatch(Reason, ISE))
811 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000812
Chris Lattner550525e2006-03-24 21:48:51 +0000813 // If this is an intrinsic, handle cases that would make it not match. For
814 // example, if an operand is required to be an immediate.
815 if (getOperator()->isSubClassOf("Intrinsic")) {
816 // TODO:
817 return true;
818 }
819
Chris Lattnere97603f2005-09-28 19:27:25 +0000820 // If this node is a commutative operator, check that the LHS isn't an
821 // immediate.
822 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
823 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
824 // Scan all of the operands of the node and make sure that only the last one
825 // is a constant node.
826 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
827 if (!getChild(i)->isLeaf() &&
828 getChild(i)->getOperator()->getName() == "imm") {
829 Reason = "Immediate value must be on the RHS of commutative operators!";
830 return false;
831 }
832 }
833
834 return true;
835}
Chris Lattner32707602005-09-08 23:22:48 +0000836
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000837//===----------------------------------------------------------------------===//
838// TreePattern implementation
839//
840
Chris Lattneredbd8712005-10-21 01:19:59 +0000841TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +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 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
845 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000846}
847
Chris Lattneredbd8712005-10-21 01:19:59 +0000848TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000849 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000850 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000851 Trees.push_back(ParseTreePattern(Pat));
852}
853
Chris Lattneredbd8712005-10-21 01:19:59 +0000854TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000855 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000856 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000857 Trees.push_back(Pat);
858}
859
860
861
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000862void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000863 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000864 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000865}
866
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000867TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
Chris Lattner8c063182006-03-30 22:50:40 +0000868 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
869 if (!OpDef) error("Pattern has unexpected operator type!");
870 Record *Operator = OpDef->getDef();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000871
872 if (Operator->isSubClassOf("ValueType")) {
873 // If the operator is a ValueType, then this must be "type cast" of a leaf
874 // node.
875 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000876 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000877
878 Init *Arg = Dag->getArg(0);
879 TreePatternNode *New;
880 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000881 Record *R = DI->getDef();
882 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000883 Dag->setArg(0, new DagInit(DI,
Chris Lattner72fe91c2005-09-24 00:40:24 +0000884 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000885 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000886 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000887 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000888 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
889 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000890 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
891 New = new TreePatternNode(II);
892 if (!Dag->getArgName(0).empty())
893 error("Constant int argument should not have a name!");
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000894 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
895 // Turn this into an IntInit.
896 Init *II = BI->convertInitializerTo(new IntRecTy());
897 if (II == 0 || !dynamic_cast<IntInit*>(II))
898 error("Bits value must be constants!");
899
900 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
901 if (!Dag->getArgName(0).empty())
902 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000903 } else {
904 Arg->dump();
905 error("Unknown leaf value for tree pattern!");
906 return 0;
907 }
908
Chris Lattner32707602005-09-08 23:22:48 +0000909 // Apply the type cast.
910 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000911 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000912 return New;
913 }
914
915 // Verify that this is something that makes sense for an operator.
916 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000917 !Operator->isSubClassOf("Instruction") &&
918 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner550525e2006-03-24 21:48:51 +0000919 !Operator->isSubClassOf("Intrinsic") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000920 Operator->getName() != "set")
921 error("Unrecognized node '" + Operator->getName() + "'!");
922
Chris Lattneredbd8712005-10-21 01:19:59 +0000923 // Check to see if this is something that is illegal in an input pattern.
924 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
Chris Lattner5a1df382006-03-24 23:10:39 +0000925 Operator->isSubClassOf("SDNodeXForm")))
Chris Lattneredbd8712005-10-21 01:19:59 +0000926 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
927
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000928 std::vector<TreePatternNode*> Children;
929
930 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
931 Init *Arg = Dag->getArg(i);
932 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
933 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000934 if (Children.back()->getName().empty())
935 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000936 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
937 Record *R = DefI->getDef();
938 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
939 // TreePatternNode if its own.
940 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000941 Dag->setArg(i, new DagInit(DefI,
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000942 std::vector<std::pair<Init*, std::string> >()));
943 --i; // Revisit this node...
944 } else {
945 TreePatternNode *Node = new TreePatternNode(DefI);
946 Node->setName(Dag->getArgName(i));
947 Children.push_back(Node);
948
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000949 // Input argument?
950 if (R->getName() == "node") {
951 if (Dag->getArgName(i).empty())
952 error("'node' argument requires a name to match with operand list");
953 Args.push_back(Dag->getArgName(i));
954 }
955 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000956 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
957 TreePatternNode *Node = new TreePatternNode(II);
958 if (!Dag->getArgName(i).empty())
959 error("Constant int argument should not have a name!");
960 Children.push_back(Node);
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000961 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
962 // Turn this into an IntInit.
963 Init *II = BI->convertInitializerTo(new IntRecTy());
964 if (II == 0 || !dynamic_cast<IntInit*>(II))
965 error("Bits value must be constants!");
966
967 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
968 if (!Dag->getArgName(i).empty())
969 error("Constant int argument should not have a name!");
970 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000971 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000972 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000973 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000974 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000975 error("Unknown leaf value for tree pattern!");
976 }
977 }
978
Chris Lattner5a1df382006-03-24 23:10:39 +0000979 // If the operator is an intrinsic, then this is just syntactic sugar for for
980 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
981 // convert the intrinsic name to a number.
982 if (Operator->isSubClassOf("Intrinsic")) {
983 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
984 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
985
986 // If this intrinsic returns void, it must have side-effects and thus a
987 // chain.
988 if (Int.ArgVTs[0] == MVT::isVoid) {
989 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
990 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
991 // Has side-effects, requires chain.
992 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
993 } else {
994 // Otherwise, no chain.
995 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
996 }
997
998 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
999 Children.insert(Children.begin(), IIDNode);
1000 }
1001
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001002 return new TreePatternNode(Operator, Children);
1003}
1004
Chris Lattner32707602005-09-08 23:22:48 +00001005/// InferAllTypes - Infer/propagate as many types throughout the expression
1006/// patterns as possible. Return true if all types are infered, false
1007/// otherwise. Throw an exception if a type contradiction is found.
1008bool TreePattern::InferAllTypes() {
1009 bool MadeChange = true;
1010 while (MadeChange) {
1011 MadeChange = false;
1012 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001013 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +00001014 }
1015
1016 bool HasUnresolvedTypes = false;
1017 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1018 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1019 return !HasUnresolvedTypes;
1020}
1021
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001022void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001023 OS << getRecord()->getName();
1024 if (!Args.empty()) {
1025 OS << "(" << Args[0];
1026 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1027 OS << ", " << Args[i];
1028 OS << ")";
1029 }
1030 OS << ": ";
1031
1032 if (Trees.size() > 1)
1033 OS << "[\n";
1034 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1035 OS << "\t";
1036 Trees[i]->print(OS);
1037 OS << "\n";
1038 }
1039
1040 if (Trees.size() > 1)
1041 OS << "]\n";
1042}
1043
1044void TreePattern::dump() const { print(std::cerr); }
1045
1046
1047
1048//===----------------------------------------------------------------------===//
1049// DAGISelEmitter implementation
1050//
1051
Chris Lattnerca559d02005-09-08 21:03:01 +00001052// Parse all of the SDNode definitions for the target, populating SDNodes.
1053void DAGISelEmitter::ParseNodeInfo() {
1054 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1055 while (!Nodes.empty()) {
1056 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1057 Nodes.pop_back();
1058 }
Chris Lattner5a1df382006-03-24 23:10:39 +00001059
1060 // Get the buildin intrinsic nodes.
1061 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1062 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1063 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
Chris Lattnerca559d02005-09-08 21:03:01 +00001064}
1065
Chris Lattner24eeeb82005-09-13 21:51:00 +00001066/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1067/// map, and emit them to the file as functions.
1068void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1069 OS << "\n// Node transformations.\n";
1070 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1071 while (!Xforms.empty()) {
1072 Record *XFormNode = Xforms.back();
1073 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1074 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1075 SDNodeXForms.insert(std::make_pair(XFormNode,
1076 std::make_pair(SDNode, Code)));
1077
Chris Lattner1048b7a2005-09-13 22:03:37 +00001078 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +00001079 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1080 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1081
Chris Lattner1048b7a2005-09-13 22:03:37 +00001082 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +00001083 << "(SDNode *" << C2 << ") {\n";
1084 if (ClassName != "SDNode")
1085 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1086 OS << Code << "\n}\n";
1087 }
1088
1089 Xforms.pop_back();
1090 }
1091}
1092
Evan Cheng0fc71982005-12-08 02:00:36 +00001093void DAGISelEmitter::ParseComplexPatterns() {
1094 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1095 while (!AMs.empty()) {
1096 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1097 AMs.pop_back();
1098 }
1099}
Chris Lattner24eeeb82005-09-13 21:51:00 +00001100
1101
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001102/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1103/// file, building up the PatternFragments map. After we've collected them all,
1104/// inline fragments together as necessary, so that there are no references left
1105/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001106///
1107/// This also emits all of the predicate functions to the output file.
1108///
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001109void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001110 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1111
1112 // First step, parse all of the fragments and emit predicate functions.
1113 OS << "\n// Predicate functions.\n";
1114 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001115 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +00001116 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001117 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +00001118
1119 // Validate the argument list, converting it to map, to discard duplicates.
1120 std::vector<std::string> &Args = P->getArgList();
1121 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1122
1123 if (OperandsMap.count(""))
1124 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1125
1126 // Parse the operands list.
1127 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Chris Lattner8c063182006-03-30 22:50:40 +00001128 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1129 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
Chris Lattneree9f0c32005-09-13 21:20:49 +00001130 P->error("Operands list should start with '(ops ... '!");
1131
1132 // Copy over the arguments.
1133 Args.clear();
1134 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1135 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1136 static_cast<DefInit*>(OpsList->getArg(j))->
1137 getDef()->getName() != "node")
1138 P->error("Operands list should all be 'node' values.");
1139 if (OpsList->getArgName(j).empty())
1140 P->error("Operands list should have names for each operand!");
1141 if (!OperandsMap.count(OpsList->getArgName(j)))
1142 P->error("'" + OpsList->getArgName(j) +
1143 "' does not occur in pattern or was multiply specified!");
1144 OperandsMap.erase(OpsList->getArgName(j));
1145 Args.push_back(OpsList->getArgName(j));
1146 }
1147
1148 if (!OperandsMap.empty())
1149 P->error("Operands list does not contain an entry for operand '" +
1150 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001151
1152 // If there is a code init for this fragment, emit the predicate code and
1153 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001154 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1155 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +00001156 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001157 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +00001158 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001159 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1160
Chris Lattner1048b7a2005-09-13 22:03:37 +00001161 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001162 << "(SDNode *" << C2 << ") {\n";
1163 if (ClassName != "SDNode")
1164 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +00001165 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001166 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001167 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001168
1169 // If there is a node transformation corresponding to this, keep track of
1170 // it.
1171 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1172 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001173 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001174 }
1175
1176 OS << "\n\n";
1177
1178 // Now that we've parsed all of the tree fragments, do a closure on them so
1179 // that there are not references to PatFrags left inside of them.
1180 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1181 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001182 TreePattern *ThePat = I->second;
1183 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001184
Chris Lattner32707602005-09-08 23:22:48 +00001185 // Infer as many types as possible. Don't worry about it if we don't infer
1186 // all of them, some may depend on the inputs of the pattern.
1187 try {
1188 ThePat->InferAllTypes();
1189 } catch (...) {
1190 // If this pattern fragment is not supported by this target (no types can
1191 // satisfy its constraints), just ignore it. If the bogus pattern is
1192 // actually used by instructions, the type consistency error will be
1193 // reported there.
1194 }
1195
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001196 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001197 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001198 }
1199}
1200
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001201/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001202/// instruction input. Return true if this is a real use.
1203static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001204 std::map<std::string, TreePatternNode*> &InstInputs,
1205 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001206 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001207 if (Pat->getName().empty()) {
1208 if (Pat->isLeaf()) {
1209 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1210 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1211 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001212 else if (DI && DI->getDef()->isSubClassOf("Register"))
1213 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001214 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001215 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001216 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001217
1218 Record *Rec;
1219 if (Pat->isLeaf()) {
1220 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1221 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1222 Rec = DI->getDef();
1223 } else {
1224 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1225 Rec = Pat->getOperator();
1226 }
1227
Evan Cheng01f318b2005-12-14 02:21:57 +00001228 // SRCVALUE nodes are ignored.
1229 if (Rec->getName() == "srcvalue")
1230 return false;
1231
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001232 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1233 if (!Slot) {
1234 Slot = Pat;
1235 } else {
1236 Record *SlotRec;
1237 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001238 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001239 } else {
1240 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1241 SlotRec = Slot->getOperator();
1242 }
1243
1244 // Ensure that the inputs agree if we've already seen this input.
1245 if (Rec != SlotRec)
1246 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001247 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001248 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1249 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001250 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001251}
1252
1253/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1254/// part of "I", the instruction), computing the set of inputs and outputs of
1255/// the pattern. Report errors if we see anything naughty.
1256void DAGISelEmitter::
1257FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1258 std::map<std::string, TreePatternNode*> &InstInputs,
Chris Lattner947604b2006-03-24 21:52:20 +00001259 std::map<std::string, TreePatternNode*>&InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001260 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001261 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001262 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001263 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001264 if (!isUse && Pat->getTransformFn())
1265 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001266 return;
1267 } else if (Pat->getOperator()->getName() != "set") {
1268 // If this is not a set, verify that the children nodes are not void typed,
1269 // and recurse.
1270 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001271 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001272 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001273 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001274 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001275 }
1276
1277 // If this is a non-leaf node with no children, treat it basically as if
1278 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001279 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001280 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001281 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001282
Chris Lattnerf1311842005-09-14 23:05:13 +00001283 if (!isUse && Pat->getTransformFn())
1284 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001285 return;
1286 }
1287
1288 // Otherwise, this is a set, validate and collect instruction results.
1289 if (Pat->getNumChildren() == 0)
1290 I->error("set requires operands!");
1291 else if (Pat->getNumChildren() & 1)
1292 I->error("set requires an even number of operands");
1293
Chris Lattnerf1311842005-09-14 23:05:13 +00001294 if (Pat->getTransformFn())
1295 I->error("Cannot specify a transform function on a set node!");
1296
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001297 // Check the set destinations.
1298 unsigned NumValues = Pat->getNumChildren()/2;
1299 for (unsigned i = 0; i != NumValues; ++i) {
1300 TreePatternNode *Dest = Pat->getChild(i);
1301 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001302 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001303
1304 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1305 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001306 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001307
Evan Chengbcecf332005-12-17 01:19:28 +00001308 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1309 if (Dest->getName().empty())
1310 I->error("set destination must have a name!");
1311 if (InstResults.count(Dest->getName()))
1312 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001313 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001314 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001315 InstImpResults.push_back(Val->getDef());
1316 } else {
1317 I->error("set destination should be a register!");
1318 }
1319
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001320 // Verify and collect info from the computation.
1321 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001322 InstInputs, InstResults,
1323 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001324 }
1325}
1326
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001327/// ParseInstructions - Parse all of the instructions, inlining and resolving
1328/// any fragments involved. This populates the Instructions list with fully
1329/// resolved instructions.
1330void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001331 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1332
1333 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001334 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001335
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001336 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1337 LI = Instrs[i]->getValueAsListInit("Pattern");
1338
1339 // If there is no pattern, only collect minimal information about the
1340 // instruction for its operand list. We have to assume that there is one
1341 // result, as we have no detailed info.
1342 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001343 std::vector<Record*> Results;
1344 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001345
1346 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001347
Evan Cheng3a217f32005-12-22 02:35:21 +00001348 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001349 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001350 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001351 // These produce no results
1352 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1353 Operands.push_back(InstInfo.OperandList[j].Rec);
1354 } else {
1355 // Assume the first operand is the result.
1356 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001357
Evan Cheng3a217f32005-12-22 02:35:21 +00001358 // The rest are inputs.
1359 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1360 Operands.push_back(InstInfo.OperandList[j].Rec);
1361 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001362 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001363
1364 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001365 std::vector<Record*> ImpResults;
1366 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001367 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001368 DAGInstruction(0, Results, Operands, ImpResults,
1369 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001370 continue; // no pattern.
1371 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001372
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001373 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001374 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001375 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001376 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001377
Chris Lattner95f6b762005-09-08 23:26:30 +00001378 // Infer as many types as possible. If we cannot infer all of them, we can
1379 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001380 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001381 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001382
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001383 // InstInputs - Keep track of all of the inputs of the instruction, along
1384 // with the record they are declared as.
1385 std::map<std::string, TreePatternNode*> InstInputs;
1386
1387 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001388 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001389 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001390
1391 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001392 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001393
Chris Lattner1f39e292005-09-14 00:09:24 +00001394 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001395 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001396 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1397 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001398 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001399 I->error("Top-level forms in instruction pattern should have"
1400 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001401
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001402 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001403 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001404 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001405 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001406
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001407 // Now that we have inputs and outputs of the pattern, inspect the operands
1408 // list for the instruction. This determines the order that operands are
1409 // added to the machine instruction the node corresponds to.
1410 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001411
1412 // Parse the operands list from the (ops) list, validating it.
1413 std::vector<std::string> &Args = I->getArgList();
1414 assert(Args.empty() && "Args list should still be empty here!");
1415 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1416
1417 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001418 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001419 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001420 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001421 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001422 I->error("'" + InstResults.begin()->first +
1423 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001424 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001425
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001426 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001427 TreePatternNode *RNode = InstResults[OpName];
Chris Lattner5c4c7742006-03-25 22:12:44 +00001428 if (RNode == 0)
1429 I->error("Operand $" + OpName + " does not exist in operand list!");
1430
Evan Cheng420132e2006-03-20 06:04:09 +00001431 if (i == 0)
1432 Res0Node = RNode;
1433 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001434 if (R == 0)
1435 I->error("Operand $" + OpName + " should be a set destination: all "
1436 "outputs must occur before inputs in operand list!");
1437
1438 if (CGI.OperandList[i].Rec != R)
1439 I->error("Operand $" + OpName + " class mismatch!");
1440
Chris Lattnerae6d8282005-09-15 21:51:12 +00001441 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001442 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001443
Chris Lattner39e8af92005-09-14 18:19:25 +00001444 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001445 InstResults.erase(OpName);
1446 }
1447
Chris Lattner0b592252005-09-14 21:59:34 +00001448 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1449 // the copy while we're checking the inputs.
1450 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001451
1452 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001453 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001454 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1455 const std::string &OpName = CGI.OperandList[i].Name;
1456 if (OpName.empty())
1457 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1458
Chris Lattner0b592252005-09-14 21:59:34 +00001459 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001460 I->error("Operand $" + OpName +
1461 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001462 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001463 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001464
1465 if (InVal->isLeaf() &&
1466 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1467 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001468 if (CGI.OperandList[i].Rec != InRec &&
1469 !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001470 I->error("Operand $" + OpName + "'s register class disagrees"
1471 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001472 }
1473 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001474
Chris Lattner2175c182005-09-14 23:01:59 +00001475 // Construct the result for the dest-pattern operand list.
1476 TreePatternNode *OpNode = InVal->clone();
1477
1478 // No predicate is useful on the result.
1479 OpNode->setPredicateFn("");
1480
1481 // Promote the xform function to be an explicit node if set.
1482 if (Record *Xform = OpNode->getTransformFn()) {
1483 OpNode->setTransformFn(0);
1484 std::vector<TreePatternNode*> Children;
1485 Children.push_back(OpNode);
1486 OpNode = new TreePatternNode(Xform, Children);
1487 }
1488
1489 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001490 }
1491
Chris Lattner0b592252005-09-14 21:59:34 +00001492 if (!InstInputsCheck.empty())
1493 I->error("Input operand $" + InstInputsCheck.begin()->first +
1494 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001495
1496 TreePatternNode *ResultPattern =
1497 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001498 // Copy fully inferred output node type to instruction result pattern.
1499 if (NumResults > 0)
1500 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001501
1502 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001503 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001504 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1505
1506 // Use a temporary tree pattern to infer all types and make sure that the
1507 // constructed result is correct. This depends on the instruction already
1508 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001509 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001510 Temp.InferAllTypes();
1511
1512 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1513 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001514
Chris Lattner32707602005-09-08 23:22:48 +00001515 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001516 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001517
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001518 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001519 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1520 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001521 DAGInstruction &TheInst = II->second;
1522 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001523 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001524
Chris Lattner1f39e292005-09-14 00:09:24 +00001525 if (I->getNumTrees() != 1) {
1526 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1527 continue;
1528 }
1529 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001530 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001531 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001532 if (Pattern->getNumChildren() != 2)
1533 continue; // Not a set of a single value (not handled so far)
1534
1535 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001536 } else{
1537 // Not a set (store or something?)
1538 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001539 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001540
1541 std::string Reason;
1542 if (!SrcPattern->canPatternMatch(Reason, *this))
1543 I->error("Instruction can never match: " + Reason);
1544
Evan Cheng58e84a62005-12-14 22:02:59 +00001545 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001546 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001547 PatternsToMatch.
1548 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
Evan Cheng59413202006-04-19 18:07:24 +00001549 SrcPattern, DstPattern,
Evan Chengc81d2a02006-04-19 20:36:09 +00001550 Instr->getValueAsInt("AddedComplexity")));
Chris Lattner1f39e292005-09-14 00:09:24 +00001551 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001552}
1553
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001554void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001555 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001556
Chris Lattnerabbb6052005-09-15 21:42:00 +00001557 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001558 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001559 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001560
Chris Lattnerabbb6052005-09-15 21:42:00 +00001561 // Inline pattern fragments into it.
1562 Pattern->InlinePatternFragments();
1563
Chris Lattnera3548492006-06-20 00:18:02 +00001564 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1565 if (LI->getSize() == 0) continue; // no pattern.
1566
1567 // Parse the instruction.
1568 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1569
1570 // Inline pattern fragments into it.
1571 Result->InlinePatternFragments();
Chris Lattner09c03392005-11-17 17:43:52 +00001572
Chris Lattnera3548492006-06-20 00:18:02 +00001573 if (Result->getNumTrees() != 1)
1574 Result->error("Cannot handle instructions producing instructions "
1575 "with temporaries yet!");
1576
1577 bool IterateInference;
Chris Lattner186fb7d2006-06-20 00:31:27 +00001578 bool InferredAllPatternTypes, InferredAllResultTypes;
Chris Lattnera3548492006-06-20 00:18:02 +00001579 do {
1580 // Infer as many types as possible. If we cannot infer all of them, we
1581 // can never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001582 InferredAllPatternTypes = Pattern->InferAllTypes();
Chris Lattnera3548492006-06-20 00:18:02 +00001583
1584 // Infer as many types as possible. If we cannot infer all of them, we can
1585 // never do anything with this pattern: report it to the user.
Chris Lattner186fb7d2006-06-20 00:31:27 +00001586 InferredAllResultTypes = Result->InferAllTypes();
1587
Chris Lattnera3548492006-06-20 00:18:02 +00001588 // Apply the type of the result to the source pattern. This helps us
1589 // resolve cases where the input type is known to be a pointer type (which
1590 // is considered resolved), but the result knows it needs to be 32- or
1591 // 64-bits. Infer the other way for good measure.
1592 IterateInference = Pattern->getOnlyTree()->
1593 UpdateNodeType(Result->getOnlyTree()->getExtTypes(), *Result);
1594 IterateInference |= Result->getOnlyTree()->
1595 UpdateNodeType(Pattern->getOnlyTree()->getExtTypes(), *Result);
1596 } while (IterateInference);
Chris Lattner186fb7d2006-06-20 00:31:27 +00001597
1598 // Verify that we inferred enough types that we can do something with the
1599 // pattern and result. If these fire the user has to add type casts.
1600 if (!InferredAllPatternTypes)
1601 Pattern->error("Could not infer all types in pattern!");
1602 if (!InferredAllResultTypes)
1603 Result->error("Could not infer all types in pattern result!");
Chris Lattnera3548492006-06-20 00:18:02 +00001604
Chris Lattner09c03392005-11-17 17:43:52 +00001605 // Validate that the input pattern is correct.
1606 {
1607 std::map<std::string, TreePatternNode*> InstInputs;
Evan Cheng420132e2006-03-20 06:04:09 +00001608 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001609 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001610 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001611 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001612 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001613 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001614 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001615
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001616 // Promote the xform function to be an explicit node if set.
1617 std::vector<TreePatternNode*> ResultNodeOperands;
1618 TreePatternNode *DstPattern = Result->getOnlyTree();
1619 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1620 TreePatternNode *OpNode = DstPattern->getChild(ii);
1621 if (Record *Xform = OpNode->getTransformFn()) {
1622 OpNode->setTransformFn(0);
1623 std::vector<TreePatternNode*> Children;
1624 Children.push_back(OpNode);
1625 OpNode = new TreePatternNode(Xform, Children);
1626 }
1627 ResultNodeOperands.push_back(OpNode);
1628 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00001629 DstPattern = Result->getOnlyTree();
1630 if (!DstPattern->isLeaf())
1631 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1632 ResultNodeOperands);
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001633 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1634 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1635 Temp.InferAllTypes();
1636
Chris Lattnere97603f2005-09-28 19:27:25 +00001637 std::string Reason;
1638 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1639 Pattern->error("Pattern can never match: " + Reason);
1640
Evan Cheng58e84a62005-12-14 22:02:59 +00001641 PatternsToMatch.
1642 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1643 Pattern->getOnlyTree(),
Evan Cheng59413202006-04-19 18:07:24 +00001644 Temp.getOnlyTree(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001645 Patterns[i]->getValueAsInt("AddedComplexity")));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001646 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001647}
1648
Chris Lattnere46e17b2005-09-29 19:28:10 +00001649/// CombineChildVariants - Given a bunch of permutations of each child of the
1650/// 'operator' node, put them together in all possible ways.
1651static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001652 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001653 std::vector<TreePatternNode*> &OutVariants,
1654 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001655 // Make sure that each operand has at least one variant to choose from.
1656 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1657 if (ChildVariants[i].empty())
1658 return;
1659
Chris Lattnere46e17b2005-09-29 19:28:10 +00001660 // The end result is an all-pairs construction of the resultant pattern.
1661 std::vector<unsigned> Idxs;
1662 Idxs.resize(ChildVariants.size());
1663 bool NotDone = true;
1664 while (NotDone) {
1665 // Create the variant and add it to the output list.
1666 std::vector<TreePatternNode*> NewChildren;
1667 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1668 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1669 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1670
1671 // Copy over properties.
1672 R->setName(Orig->getName());
1673 R->setPredicateFn(Orig->getPredicateFn());
1674 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001675 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001676
1677 // If this pattern cannot every match, do not include it as a variant.
1678 std::string ErrString;
1679 if (!R->canPatternMatch(ErrString, ISE)) {
1680 delete R;
1681 } else {
1682 bool AlreadyExists = false;
1683
1684 // Scan to see if this pattern has already been emitted. We can get
1685 // duplication due to things like commuting:
1686 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1687 // which are the same pattern. Ignore the dups.
1688 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1689 if (R->isIsomorphicTo(OutVariants[i])) {
1690 AlreadyExists = true;
1691 break;
1692 }
1693
1694 if (AlreadyExists)
1695 delete R;
1696 else
1697 OutVariants.push_back(R);
1698 }
1699
1700 // Increment indices to the next permutation.
1701 NotDone = false;
1702 // Look for something we can increment without causing a wrap-around.
1703 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1704 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1705 NotDone = true; // Found something to increment.
1706 break;
1707 }
1708 Idxs[IdxsIdx] = 0;
1709 }
1710 }
1711}
1712
Chris Lattneraf302912005-09-29 22:36:54 +00001713/// CombineChildVariants - A helper function for binary operators.
1714///
1715static void CombineChildVariants(TreePatternNode *Orig,
1716 const std::vector<TreePatternNode*> &LHS,
1717 const std::vector<TreePatternNode*> &RHS,
1718 std::vector<TreePatternNode*> &OutVariants,
1719 DAGISelEmitter &ISE) {
1720 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1721 ChildVariants.push_back(LHS);
1722 ChildVariants.push_back(RHS);
1723 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1724}
1725
1726
1727static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1728 std::vector<TreePatternNode *> &Children) {
1729 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1730 Record *Operator = N->getOperator();
1731
1732 // Only permit raw nodes.
1733 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1734 N->getTransformFn()) {
1735 Children.push_back(N);
1736 return;
1737 }
1738
1739 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1740 Children.push_back(N->getChild(0));
1741 else
1742 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1743
1744 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1745 Children.push_back(N->getChild(1));
1746 else
1747 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1748}
1749
Chris Lattnere46e17b2005-09-29 19:28:10 +00001750/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1751/// the (potentially recursive) pattern by using algebraic laws.
1752///
1753static void GenerateVariantsOf(TreePatternNode *N,
1754 std::vector<TreePatternNode*> &OutVariants,
1755 DAGISelEmitter &ISE) {
1756 // We cannot permute leaves.
1757 if (N->isLeaf()) {
1758 OutVariants.push_back(N);
1759 return;
1760 }
1761
1762 // Look up interesting info about the node.
Chris Lattner5a1df382006-03-24 23:10:39 +00001763 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001764
1765 // If this node is associative, reassociate.
Chris Lattner5a1df382006-03-24 23:10:39 +00001766 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
Chris Lattneraf302912005-09-29 22:36:54 +00001767 // Reassociate by pulling together all of the linked operators
1768 std::vector<TreePatternNode*> MaximalChildren;
1769 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1770
1771 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1772 // permutations.
1773 if (MaximalChildren.size() == 3) {
1774 // Find the variants of all of our maximal children.
1775 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1776 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1777 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1778 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1779
1780 // There are only two ways we can permute the tree:
1781 // (A op B) op C and A op (B op C)
1782 // Within these forms, we can also permute A/B/C.
1783
1784 // Generate legal pair permutations of A/B/C.
1785 std::vector<TreePatternNode*> ABVariants;
1786 std::vector<TreePatternNode*> BAVariants;
1787 std::vector<TreePatternNode*> ACVariants;
1788 std::vector<TreePatternNode*> CAVariants;
1789 std::vector<TreePatternNode*> BCVariants;
1790 std::vector<TreePatternNode*> CBVariants;
1791 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1792 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1793 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1794 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1795 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1796 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1797
1798 // Combine those into the result: (x op x) op x
1799 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1800 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1801 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1802 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1803 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1804 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1805
1806 // Combine those into the result: x op (x op x)
1807 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1808 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1809 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1810 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1811 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1812 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1813 return;
1814 }
1815 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001816
1817 // Compute permutations of all children.
1818 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1819 ChildVariants.resize(N->getNumChildren());
1820 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1821 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1822
1823 // Build all permutations based on how the children were formed.
1824 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1825
1826 // If this node is commutative, consider the commuted order.
Chris Lattner5a1df382006-03-24 23:10:39 +00001827 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001828 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001829 // Consider the commuted order.
1830 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1831 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001832 }
1833}
1834
1835
Chris Lattnere97603f2005-09-28 19:27:25 +00001836// GenerateVariants - Generate variants. For example, commutative patterns can
1837// match multiple ways. Add them to PatternsToMatch as well.
1838void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001839
1840 DEBUG(std::cerr << "Generating instruction variants.\n");
1841
1842 // Loop over all of the patterns we've collected, checking to see if we can
1843 // generate variants of the instruction, through the exploitation of
1844 // identities. This permits the target to provide agressive matching without
1845 // the .td file having to contain tons of variants of instructions.
1846 //
1847 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1848 // intentionally do not reconsider these. Any variants of added patterns have
1849 // already been added.
1850 //
1851 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1852 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001853 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001854
1855 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001856 Variants.erase(Variants.begin()); // Remove the original pattern.
1857
1858 if (Variants.empty()) // No variants for this pattern.
1859 continue;
1860
1861 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001862 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001863 std::cerr << "\n");
1864
1865 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1866 TreePatternNode *Variant = Variants[v];
1867
1868 DEBUG(std::cerr << " VAR#" << v << ": ";
1869 Variant->dump();
1870 std::cerr << "\n");
1871
1872 // Scan to see if an instruction or explicit pattern already matches this.
1873 bool AlreadyExists = false;
1874 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1875 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001876 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001877 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1878 AlreadyExists = true;
1879 break;
1880 }
1881 }
1882 // If we already have it, ignore the variant.
1883 if (AlreadyExists) continue;
1884
1885 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001886 PatternsToMatch.
1887 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
Evan Cheng59413202006-04-19 18:07:24 +00001888 Variant, PatternsToMatch[i].getDstPattern(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001889 PatternsToMatch[i].getAddedComplexity()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001890 }
1891
1892 DEBUG(std::cerr << "\n");
1893 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001894}
1895
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001896
Evan Cheng0fc71982005-12-08 02:00:36 +00001897// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1898// ComplexPattern.
1899static bool NodeIsComplexPattern(TreePatternNode *N)
1900{
1901 return (N->isLeaf() &&
1902 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1903 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1904 isSubClassOf("ComplexPattern"));
1905}
1906
1907// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1908// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1909static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1910 DAGISelEmitter &ISE)
1911{
1912 if (N->isLeaf() &&
1913 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1914 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1915 isSubClassOf("ComplexPattern")) {
1916 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1917 ->getDef());
1918 }
1919 return NULL;
1920}
1921
Chris Lattner05814af2005-09-28 17:57:56 +00001922/// getPatternSize - Return the 'size' of this pattern. We want to match large
1923/// patterns before small ones. This is used to determine the size of a
1924/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001925static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng2618d072006-05-17 20:37:59 +00001926 assert((isExtIntegerInVTs(P->getExtTypes()) ||
1927 isExtFloatingPointInVTs(P->getExtTypes()) ||
1928 P->getExtTypeNum(0) == MVT::isVoid ||
1929 P->getExtTypeNum(0) == MVT::Flag ||
1930 P->getExtTypeNum(0) == MVT::iPTR) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +00001931 "Not a valid pattern node to size!");
Evan Chenge1050d62006-01-06 02:30:23 +00001932 unsigned Size = 2; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00001933 // If the root node is a ConstantSDNode, increases its size.
1934 // e.g. (set R32:$dst, 0).
1935 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1936 Size++;
Evan Cheng0fc71982005-12-08 02:00:36 +00001937
1938 // FIXME: This is a hack to statically increase the priority of patterns
1939 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1940 // Later we can allow complexity / cost for each pattern to be (optionally)
1941 // specified. To get best possible pattern match we'll need to dynamically
1942 // calculate the complexity of all patterns a dag can potentially map to.
1943 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1944 if (AM)
Evan Cheng4a7c2842006-01-06 22:19:44 +00001945 Size += AM->getNumOperands() * 2;
Chris Lattner3e179802006-02-03 18:06:02 +00001946
1947 // If this node has some predicate function that must match, it adds to the
1948 // complexity of this node.
1949 if (!P->getPredicateFn().empty())
1950 ++Size;
1951
Chris Lattner05814af2005-09-28 17:57:56 +00001952 // Count children in the count if they are also nodes.
1953 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1954 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001955 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001956 Size += getPatternSize(Child, ISE);
1957 else if (Child->isLeaf()) {
1958 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner3e179802006-02-03 18:06:02 +00001959 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
Evan Cheng4a7c2842006-01-06 22:19:44 +00001960 else if (NodeIsComplexPattern(Child))
1961 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00001962 else if (!Child->getPredicateFn().empty())
1963 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001964 }
Chris Lattner05814af2005-09-28 17:57:56 +00001965 }
1966
1967 return Size;
1968}
1969
1970/// getResultPatternCost - Compute the number of instructions for this pattern.
1971/// This is a temporary hack. We should really include the instruction
1972/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00001973static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00001974 if (P->isLeaf()) return 0;
1975
Evan Chengfbad7082006-02-18 02:33:09 +00001976 unsigned Cost = 0;
1977 Record *Op = P->getOperator();
1978 if (Op->isSubClassOf("Instruction")) {
1979 Cost++;
1980 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1981 if (II.usesCustomDAGSchedInserter)
1982 Cost += 10;
1983 }
Chris Lattner05814af2005-09-28 17:57:56 +00001984 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00001985 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001986 return Cost;
1987}
1988
Evan Chenge6f32032006-07-19 00:24:41 +00001989/// getResultPatternCodeSize - Compute the code size of instructions for this
1990/// pattern.
1991static unsigned getResultPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1992 if (P->isLeaf()) return 0;
1993
1994 unsigned Cost = 0;
1995 Record *Op = P->getOperator();
1996 if (Op->isSubClassOf("Instruction")) {
1997 Cost += Op->getValueAsInt("CodeSize");
1998 }
1999 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2000 Cost += getResultPatternSize(P->getChild(i), ISE);
2001 return Cost;
2002}
2003
Chris Lattner05814af2005-09-28 17:57:56 +00002004// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
2005// In particular, we want to match maximal patterns first and lowest cost within
2006// a particular complexity first.
2007struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00002008 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
2009 DAGISelEmitter &ISE;
2010
Evan Cheng58e84a62005-12-14 22:02:59 +00002011 bool operator()(PatternToMatch *LHS,
2012 PatternToMatch *RHS) {
2013 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
2014 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Evan Chengc81d2a02006-04-19 20:36:09 +00002015 LHSSize += LHS->getAddedComplexity();
2016 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +00002017 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
2018 if (LHSSize < RHSSize) return false;
2019
2020 // If the patterns have equal complexity, compare generated instruction cost
Evan Chenge6f32032006-07-19 00:24:41 +00002021 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), ISE);
2022 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), ISE);
2023 if (LHSCost < RHSCost) return true;
2024 if (LHSCost > RHSCost) return false;
2025
2026 return getResultPatternSize(LHS->getDstPattern(), ISE) <
2027 getResultPatternSize(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00002028 }
2029};
2030
Nate Begeman6510b222005-12-01 04:51:06 +00002031/// getRegisterValueType - Look up and return the first ValueType of specified
2032/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00002033static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00002034 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
2035 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00002036 return MVT::Other;
2037}
2038
Chris Lattner72fe91c2005-09-24 00:40:24 +00002039
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002040/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
2041/// type information from it.
2042static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00002043 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002044 if (!N->isLeaf())
2045 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2046 RemoveAllTypes(N->getChild(i));
2047}
Chris Lattner72fe91c2005-09-24 00:40:24 +00002048
Chris Lattner0614b622005-11-02 06:49:14 +00002049Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
2050 Record *N = Records.getDef(Name);
Chris Lattner5a1df382006-03-24 23:10:39 +00002051 if (!N || !N->isSubClassOf("SDNode")) {
2052 std::cerr << "Error getting SDNode '" << Name << "'!\n";
2053 exit(1);
2054 }
Chris Lattner0614b622005-11-02 06:49:14 +00002055 return N;
2056}
2057
Evan Cheng51fecc82006-01-09 18:27:06 +00002058/// NodeHasProperty - return true if TreePatternNode has the specified
2059/// property.
2060static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2061 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002062{
2063 if (N->isLeaf()) return false;
2064 Record *Operator = N->getOperator();
2065 if (!Operator->isSubClassOf("SDNode")) return false;
2066
2067 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00002068 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002069}
2070
Evan Cheng51fecc82006-01-09 18:27:06 +00002071static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2072 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002073{
Evan Cheng51fecc82006-01-09 18:27:06 +00002074 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00002075 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00002076
2077 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2078 TreePatternNode *Child = N->getChild(i);
2079 if (PatternHasProperty(Child, Property, ISE))
2080 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002081 }
2082
2083 return false;
2084}
2085
Evan Chengb915f312005-12-09 22:45:35 +00002086class PatternCodeEmitter {
2087private:
2088 DAGISelEmitter &ISE;
2089
Evan Cheng58e84a62005-12-14 22:02:59 +00002090 // Predicates.
2091 ListInit *Predicates;
Evan Cheng59413202006-04-19 18:07:24 +00002092 // Pattern cost.
2093 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +00002094 // Instruction selector pattern.
2095 TreePatternNode *Pattern;
2096 // Matched instruction.
2097 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002098
Evan Chengb915f312005-12-09 22:45:35 +00002099 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00002100 std::map<std::string, std::string> VariableMap;
2101 // Node to operator mapping
2102 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00002103 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002104 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00002105 std::set<std::string> Duplicates;
Evan Cheng61a02092006-04-28 02:08:10 +00002106 /// These nodes are being marked "in-flight" so they cannot be folded.
2107 std::vector<std::string> InflightNodes;
Evan Chengb915f312005-12-09 22:45:35 +00002108
Chris Lattner8a0604b2006-01-28 20:31:24 +00002109 /// GeneratedCode - This is the buffer that we emit code to. The first bool
2110 /// indicates whether this is an exit predicate (something that should be
2111 /// tested, and if true, the match fails) [when true] or normal code to emit
2112 /// [when false].
2113 std::vector<std::pair<bool, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002114 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2115 /// the set of patterns for each top-level opcode.
Evan Chengf8729402006-07-16 06:12:52 +00002116 std::set<std::pair<unsigned, std::string> > &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +00002117 /// TargetOpcodes - The target specific opcodes used by the resulting
2118 /// instructions.
2119 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +00002120 std::vector<std::string> &TargetVTs;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002121
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002122 std::string ChainName;
Evan Chenged66e852006-03-09 08:19:11 +00002123 bool NewTF;
Evan Chenge41bf822006-02-05 06:43:12 +00002124 bool DoReplace;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002125 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +00002126 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +00002127 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002128
2129 void emitCheck(const std::string &S) {
2130 if (!S.empty())
2131 GeneratedCode.push_back(std::make_pair(true, S));
2132 }
2133 void emitCode(const std::string &S) {
2134 if (!S.empty())
2135 GeneratedCode.push_back(std::make_pair(false, S));
2136 }
Evan Chengf8729402006-07-16 06:12:52 +00002137 void emitDecl(const std::string &S, unsigned T=0) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002138 assert(!S.empty() && "Invalid declaration");
Evan Chengf8729402006-07-16 06:12:52 +00002139 GeneratedDecl.insert(std::make_pair(T, S));
Evan Cheng21ad3922006-02-07 00:37:41 +00002140 }
Evan Chengfceb57a2006-07-15 08:45:20 +00002141 void emitOpcode(const std::string &Opc) {
2142 TargetOpcodes.push_back(Opc);
2143 OpcNo++;
2144 }
Evan Chengf8729402006-07-16 06:12:52 +00002145 void emitVT(const std::string &VT) {
2146 TargetVTs.push_back(VT);
2147 VTNo++;
2148 }
Evan Chengb915f312005-12-09 22:45:35 +00002149public:
Evan Cheng58e84a62005-12-14 22:02:59 +00002150 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2151 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng21ad3922006-02-07 00:37:41 +00002152 std::vector<std::pair<bool, std::string> > &gc,
Evan Chengf8729402006-07-16 06:12:52 +00002153 std::set<std::pair<unsigned, std::string> > &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +00002154 std::vector<std::string> &to,
Evan Chengf8729402006-07-16 06:12:52 +00002155 std::vector<std::string> &tv,
Evan Cheng21ad3922006-02-07 00:37:41 +00002156 bool dorep)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002157 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Chengf8729402006-07-16 06:12:52 +00002158 GeneratedCode(gc), GeneratedDecl(gd), TargetOpcodes(to), TargetVTs(tv),
2159 NewTF(false), DoReplace(dorep), TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00002160
2161 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2162 /// if the match fails. At this point, we already know that the opcode for N
2163 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00002164 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2165 const std::string &RootName, const std::string &ParentName,
2166 const std::string &ChainSuffix, bool &FoundChain) {
2167 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00002168 // Emit instruction predicates. Each predicate is just a string for now.
2169 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002170 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00002171 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2172 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2173 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002174 if (!Def->isSubClassOf("Predicate")) {
Jim Laskey16d42c62006-07-11 18:25:13 +00002175#ifndef NDEBUG
2176 Def->dump();
2177#endif
Evan Cheng58e84a62005-12-14 22:02:59 +00002178 assert(0 && "Unknown predicate type!");
2179 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002180 if (!PredicateCheck.empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002181 PredicateCheck += " || ";
2182 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00002183 }
2184 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002185
2186 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00002187 }
2188
Evan Chengb915f312005-12-09 22:45:35 +00002189 if (N->isLeaf()) {
2190 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002191 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00002192 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002193 return;
2194 } else if (!NodeIsComplexPattern(N)) {
2195 assert(0 && "Cannot match this as a leaf value!");
2196 abort();
2197 }
2198 }
2199
Chris Lattner488580c2006-01-28 19:06:51 +00002200 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002201 // we already saw this in the pattern, emit code to verify dagness.
2202 if (!N->getName().empty()) {
2203 std::string &VarMapEntry = VariableMap[N->getName()];
2204 if (VarMapEntry.empty()) {
2205 VarMapEntry = RootName;
2206 } else {
2207 // If we get here, this is a second reference to a specific name. Since
2208 // we already have checked that the first reference is valid, we don't
2209 // have to recursively match it, just check that it's the same as the
2210 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002211 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00002212 return;
2213 }
Evan Chengf805c2e2006-01-12 19:35:54 +00002214
2215 if (!N->isLeaf())
2216 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00002217 }
2218
2219
2220 // Emit code to load the child nodes and match their contents recursively.
2221 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00002222 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2223 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2224 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00002225 bool EmittedUseCheck = false;
2226 bool EmittedSlctedCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00002227 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00002228 if (NodeHasChain)
2229 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00002230 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00002231 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Evan Cheng61a02092006-04-28 02:08:10 +00002232 // Not in flight?
Evan Cheng55d0fa12006-04-28 18:54:11 +00002233 emitCheck("InFlightSet.count(" + RootName + ".Val) == 0");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002234 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002235 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002236 EmittedUseCheck = true;
2237 // hasOneUse() check is not strong enough. If the original node has
2238 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002239 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002240 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002241 "))");
2242
Evan Cheng1feeeec2006-01-26 19:13:45 +00002243 EmittedSlctedCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002244 if (NodeHasChain) {
2245 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2246 // has a chain use.
2247 // This a workaround for this problem:
2248 //
2249 // [ch, r : ld]
2250 // ^ ^
2251 // | |
2252 // [XX]--/ \- [flag : cmp]
2253 // ^ ^
2254 // | |
2255 // \---[br flag]-
2256 //
2257 // cmp + br should be considered as a single node as they are flagged
2258 // together. So, if the ld is folded into the cmp, the XX node in the
2259 // graph is now both an operand and a use of the ld/cmp/br node.
2260 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2261 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2262
2263 // If the immediate use can somehow reach this node through another
2264 // path, then can't fold it either or it will create a cycle.
2265 // e.g. In the following diagram, XX can reach ld through YY. If
2266 // ld is folded into XX, then YY is both a predecessor and a successor
2267 // of XX.
2268 //
2269 // [ld]
2270 // ^ ^
2271 // | |
2272 // / \---
2273 // / [YY]
2274 // | ^
2275 // [XX]-------|
2276 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2277 if (PInfo.getNumOperands() > 1 ||
2278 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2279 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2280 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
Evan Cheng6f8aaf22006-03-07 08:31:27 +00002281 if (PInfo.getNumOperands() > 1) {
2282 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2283 ".Val)");
2284 } else {
2285 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2286 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2287 ".Val))");
2288 }
Evan Chenge41bf822006-02-05 06:43:12 +00002289 }
Evan Chengb915f312005-12-09 22:45:35 +00002290 }
Evan Chenge41bf822006-02-05 06:43:12 +00002291
Evan Chengc15d18c2006-01-27 22:13:45 +00002292 if (NodeHasChain) {
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002293 ChainName = "Chain" + ChainSuffix;
Evan Cheng21ad3922006-02-07 00:37:41 +00002294 emitDecl(ChainName);
Evan Chenged66e852006-03-09 08:19:11 +00002295 if (FoundChain) {
2296 // FIXME: temporary workaround for a common case where chain
2297 // is a TokenFactor and the previous "inner" chain is an operand.
2298 NewTF = true;
Evan Chengf8729402006-07-16 06:12:52 +00002299 emitDecl("OldTF", 1);
Evan Chenged66e852006-03-09 08:19:11 +00002300 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2301 RootName + ".Val, Chain.Val, OldTF)).Val");
2302 } else {
2303 FoundChain = true;
2304 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2305 }
Evan Cheng1cf6db22006-01-06 00:41:12 +00002306 }
Evan Chengb915f312005-12-09 22:45:35 +00002307 }
2308
Evan Cheng54597732006-01-26 00:22:25 +00002309 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002310 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002311 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002312 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2313 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002314 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002315 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2316 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2317 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002318 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2319 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002320 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002321 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002322 }
Evan Cheng1feeeec2006-01-26 19:13:45 +00002323 if (!EmittedSlctedCheck)
2324 // hasOneUse() check is not strong enough. If the original node has
2325 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002326 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002327 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002328 "))");
Evan Cheng54597732006-01-26 00:22:25 +00002329 }
2330
Evan Chengb915f312005-12-09 22:45:35 +00002331 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002332 emitDecl(RootName + utostr(OpNo));
2333 emitCode(RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002334 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002335 TreePatternNode *Child = N->getChild(i);
2336
2337 if (!Child->isLeaf()) {
2338 // If it's not a leaf, recursively match.
2339 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002340 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002341 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002342 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2343 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002344 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002345 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2346 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002347 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002348 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002349 // we already saw this in the pattern, emit code to verify dagness.
2350 if (!Child->getName().empty()) {
2351 std::string &VarMapEntry = VariableMap[Child->getName()];
2352 if (VarMapEntry.empty()) {
2353 VarMapEntry = RootName + utostr(OpNo);
2354 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002355 // If we get here, this is a second reference to a specific name.
2356 // Since we already have checked that the first reference is valid,
2357 // we don't have to recursively match it, just check that it's the
2358 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002359 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002360 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002361 continue;
2362 }
2363 }
2364
2365 // Handle leaves of various types.
2366 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2367 Record *LeafRec = DI->getDef();
2368 if (LeafRec->isSubClassOf("RegisterClass")) {
2369 // Handle register references. Nothing to do here.
2370 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002371 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002372 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2373 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00002374 } else if (LeafRec->getName() == "srcvalue") {
2375 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002376 } else if (LeafRec->isSubClassOf("ValueType")) {
2377 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002378 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002379 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002380 } else if (LeafRec->isSubClassOf("CondCode")) {
2381 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002382 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002383 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002384 } else {
Jim Laskey16d42c62006-07-11 18:25:13 +00002385#ifndef NDEBUG
2386 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002387 std::cerr << " ";
Jim Laskey16d42c62006-07-11 18:25:13 +00002388#endif
Evan Chengb915f312005-12-09 22:45:35 +00002389 assert(0 && "Unknown leaf type!");
2390 }
Chris Lattner488580c2006-01-28 19:06:51 +00002391 } else if (IntInit *II =
2392 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002393 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2394 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002395 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002396 RootName + utostr(OpNo) + ")->getSignExtended();");
2397
2398 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002399 } else {
Jim Laskey16d42c62006-07-11 18:25:13 +00002400#ifndef NDEBUG
2401 Child->dump();
2402#endif
Evan Chengb915f312005-12-09 22:45:35 +00002403 assert(0 && "Unknown leaf type!");
2404 }
2405 }
2406 }
2407
2408 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002409 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002410 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002411 }
2412
2413 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2414 /// we actually have to build a DAG!
2415 std::pair<unsigned, unsigned>
Chris Lattner947604b2006-03-24 21:52:20 +00002416 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2417 bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002418 // This is something selected from the pattern we matched.
2419 if (!N->getName().empty()) {
Evan Chengb915f312005-12-09 22:45:35 +00002420 std::string &Val = VariableMap[N->getName()];
2421 assert(!Val.empty() &&
2422 "Variable referenced but not defined and not caught earlier!");
2423 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2424 // Already selected this operand, just return the tmpval.
2425 return std::make_pair(1, atoi(Val.c_str()+3));
2426 }
2427
2428 const ComplexPattern *CP;
2429 unsigned ResNo = TmpNo++;
2430 unsigned NumRes = 1;
2431 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002432 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002433 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002434 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002435 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002436 case MVT::i1: CastType = "bool"; break;
2437 case MVT::i8: CastType = "unsigned char"; break;
2438 case MVT::i16: CastType = "unsigned short"; break;
2439 case MVT::i32: CastType = "unsigned"; break;
2440 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002441 }
Evan Cheng21ad3922006-02-07 00:37:41 +00002442 emitDecl("Tmp" + utostr(ResNo));
2443 emitCode("Tmp" + utostr(ResNo) +
Evan Chengfceb57a2006-07-15 08:45:20 +00002444 " = CurDAG->getTargetConstant(((" + CastType +
2445 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
2446 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengbb48e332006-01-12 07:54:57 +00002447 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002448 Record *Op = OperatorMap[N->getName()];
2449 // Transform ExternalSymbol to TargetExternalSymbol
2450 if (Op && Op->getName() == "externalsym") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002451 emitDecl("Tmp" + utostr(ResNo));
2452 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002453 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002454 Val + ")->getSymbol(), " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002455 getEnumName(N->getTypeNum(0)) + ");");
2456 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002457 emitDecl("Tmp" + utostr(ResNo));
2458 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002459 }
Evan Chengb915f312005-12-09 22:45:35 +00002460 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002461 Record *Op = OperatorMap[N->getName()];
2462 // Transform GlobalAddress to TargetGlobalAddress
2463 if (Op && Op->getName() == "globaladdr") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002464 emitDecl("Tmp" + utostr(ResNo));
2465 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002466 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
Evan Cheng2618d072006-05-17 20:37:59 +00002467 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002468 ");");
2469 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002470 emitDecl("Tmp" + utostr(ResNo));
2471 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002472 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002473 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng21ad3922006-02-07 00:37:41 +00002474 emitDecl("Tmp" + utostr(ResNo));
2475 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengbb48e332006-01-12 07:54:57 +00002476 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002477 emitDecl("Tmp" + utostr(ResNo));
2478 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002479 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2480 std::string Fn = CP->getSelectFunc();
2481 NumRes = CP->getNumOperands();
Evan Cheng21ad3922006-02-07 00:37:41 +00002482 for (unsigned i = 0; i < NumRes; ++i)
Evan Chengb0793f92006-05-25 00:21:44 +00002483 emitDecl("CPTmp" + utostr(i+ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002484
Evan Chengb0793f92006-05-25 00:21:44 +00002485 std::string Code = "bool Match = " + Fn + "(" + Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002486 for (unsigned i = 0; i < NumRes; i++)
Evan Chengb0793f92006-05-25 00:21:44 +00002487 Code += ", CPTmp" + utostr(i + ResNo);
2488 emitCode(Code + ");");
2489 if (InflightNodes.size()) {
2490 // Remove the in-flight nodes if the ComplexPattern does not match!
2491 emitCode("if (!Match) {");
2492 for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2493 AE = InflightNodes.end(); AI != AE; ++AI)
Evan Cheng322812e2006-06-29 23:57:05 +00002494 emitCode(" SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " +
2495 *AI + ".Val);");
Evan Chengb0793f92006-05-25 00:21:44 +00002496 emitCode("}");
2497 }
2498
2499 emitCheck("Match");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002500
Evan Cheng61a02092006-04-28 02:08:10 +00002501 for (unsigned i = 0; i < NumRes; ++i) {
Evan Cheng322812e2006-06-29 23:57:05 +00002502 emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, CPTmp" +
2503 utostr(i+ResNo) + ".Val);");
Evan Chengb0793f92006-05-25 00:21:44 +00002504 InflightNodes.push_back("CPTmp" + utostr(i+ResNo));
Evan Cheng61a02092006-04-28 02:08:10 +00002505 }
Evan Chengb0793f92006-05-25 00:21:44 +00002506 for (unsigned i = 0; i < NumRes; ++i) {
2507 emitDecl("Tmp" + utostr(i+ResNo));
2508 emitCode("Select(Tmp" + utostr(i+ResNo) + ", CPTmp" +
Evan Cheng2216d8a2006-02-05 05:22:18 +00002509 utostr(i+ResNo) + ");");
Evan Chengb0793f92006-05-25 00:21:44 +00002510 }
Evan Cheng9c4815a2006-02-04 08:50:49 +00002511
Evan Chengb915f312005-12-09 22:45:35 +00002512 TmpNo = ResNo + NumRes;
2513 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002514 emitDecl("Tmp" + utostr(ResNo));
Evan Cheng863bf5a2006-03-20 22:53:06 +00002515 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2516 // node even if it isn't one. Don't select it.
2517 if (LikeLeaf)
2518 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Cheng61a02092006-04-28 02:08:10 +00002519 else {
Evan Cheng863bf5a2006-03-20 22:53:06 +00002520 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
Evan Cheng61a02092006-04-28 02:08:10 +00002521 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00002522
2523 if (isRoot && N->isLeaf()) {
2524 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2525 emitCode("return;");
2526 }
Evan Chengb915f312005-12-09 22:45:35 +00002527 }
2528 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2529 // value if used multiple times by this pattern result.
2530 Val = "Tmp"+utostr(ResNo);
2531 return std::make_pair(NumRes, ResNo);
2532 }
Evan Chengb915f312005-12-09 22:45:35 +00002533 if (N->isLeaf()) {
2534 // If this is an explicit register reference, handle it.
2535 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2536 unsigned ResNo = TmpNo++;
2537 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002538 emitDecl("Tmp" + utostr(ResNo));
2539 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002540 ISE.getQualifiedName(DI->getDef()) + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002541 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002542 return std::make_pair(1, ResNo);
2543 }
2544 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2545 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002546 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng21ad3922006-02-07 00:37:41 +00002547 emitDecl("Tmp" + utostr(ResNo));
2548 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002549 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
Evan Cheng2618d072006-05-17 20:37:59 +00002550 ", " + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002551 return std::make_pair(1, ResNo);
2552 }
2553
Jim Laskey16d42c62006-07-11 18:25:13 +00002554#ifndef NDEBUG
2555 N->dump();
2556#endif
Evan Chengb915f312005-12-09 22:45:35 +00002557 assert(0 && "Unknown leaf type!");
2558 return std::make_pair(1, ~0U);
2559 }
2560
2561 Record *Op = N->getOperator();
2562 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002563 const CodeGenTarget &CGT = ISE.getTargetInfo();
2564 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002565 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng045953c2006-05-10 00:05:46 +00002566 TreePattern *InstPat = Inst.getPattern();
2567 TreePatternNode *InstPatNode =
2568 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2569 : (InstPat ? InstPat->getOnlyTree() : NULL);
2570 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2571 InstPatNode = InstPatNode->getChild(1);
2572 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002573 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
Evan Cheng045953c2006-05-10 00:05:46 +00002574 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2575 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2576 bool NodeHasOptInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002577 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002578 bool NodeHasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002579 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002580 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2581 PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2582 bool NodeHasChain = InstPatNode &&
2583 PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002584 bool InputHasChain = isRoot &&
2585 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng4fba2812005-12-20 07:37:41 +00002586
Evan Cheng045953c2006-05-10 00:05:46 +00002587 if (NodeHasInFlag || NodeHasOutFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng21ad3922006-02-07 00:37:41 +00002588 emitDecl("InFlag");
Evan Chengfceb57a2006-07-15 08:45:20 +00002589 if (NodeHasOptInFlag) {
Evan Chengf8729402006-07-16 06:12:52 +00002590 emitDecl("HasInFlag", 2);
Evan Chengfceb57a2006-07-15 08:45:20 +00002591 emitCode("HasInFlag = "
Evan Chengf8729402006-07-16 06:12:52 +00002592 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
Evan Chengfceb57a2006-07-15 08:45:20 +00002593 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002594 if (HasVarOps)
2595 emitCode("std::vector<SDOperand> Ops;");
Evan Cheng4fba2812005-12-20 07:37:41 +00002596
Evan Cheng823b7522006-01-19 21:57:10 +00002597 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002598 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002599 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2600 MVT::ValueType VT = Pattern->getTypeNum(i);
2601 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002602 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002603 }
2604
Evan Chengb915f312005-12-09 22:45:35 +00002605 // Determine operand emission order. Complex pattern first.
2606 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2607 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2608 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2609 TreePatternNode *Child = N->getChild(i);
2610 if (i == 0) {
2611 EmitOrder.push_back(std::make_pair(i, Child));
2612 OI = EmitOrder.begin();
2613 } else if (NodeIsComplexPattern(Child)) {
2614 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2615 } else {
2616 EmitOrder.push_back(std::make_pair(i, Child));
2617 }
2618 }
2619
Evan Cheng61a02092006-04-28 02:08:10 +00002620 // Make sure these operands which would be selected won't be folded while
2621 // the isel traverses the DAG upward.
Evan Chengb915f312005-12-09 22:45:35 +00002622 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
Evan Cheng61a02092006-04-28 02:08:10 +00002623 TreePatternNode *Child = EmitOrder[i].second;
2624 if (!Child->getName().empty()) {
2625 std::string &Val = VariableMap[Child->getName()];
2626 assert(!Val.empty() &&
2627 "Variable referenced but not defined and not caught earlier!");
2628 if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) {
Evan Cheng322812e2006-06-29 23:57:05 +00002629 emitCode("SelectionDAG::InsertInFlightSetEntry(InFlightSet, " +
2630 Val + ".Val);");
Evan Cheng61a02092006-04-28 02:08:10 +00002631 InflightNodes.push_back(Val);
2632 }
2633 }
2634 }
2635
2636 // Emit all of the operands.
Evan Chengb0793f92006-05-25 00:21:44 +00002637 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
Evan Cheng61a02092006-04-28 02:08:10 +00002638 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
Evan Chengb915f312005-12-09 22:45:35 +00002639 unsigned OpOrder = EmitOrder[i].first;
2640 TreePatternNode *Child = EmitOrder[i].second;
2641 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2642 NumTemps[OpOrder] = NumTemp;
2643 }
2644
2645 // List all the operands in the right order.
2646 std::vector<unsigned> Ops;
2647 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2648 for (unsigned j = 0; j < NumTemps[i].first; j++)
2649 Ops.push_back(NumTemps[i].second + j);
2650 }
2651
Evan Chengb915f312005-12-09 22:45:35 +00002652 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +00002653 bool ChainEmitted = NodeHasChain;
2654 if (NodeHasChain)
Evan Cheng34167212006-02-09 00:37:58 +00002655 emitCode("Select(" + ChainName + ", " + ChainName + ");");
Evan Chengbc6b86a2006-06-14 19:27:50 +00002656 if (NodeHasInFlag || HasImpInputs)
Evan Cheng54597732006-01-26 00:22:25 +00002657 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
Evan Chengbc6b86a2006-06-14 19:27:50 +00002658 if (NodeHasOptInFlag) {
Evan Chenge945f4d2006-06-14 22:22:20 +00002659 emitCode("if (HasInFlag)");
Evan Chengbc6b86a2006-06-14 19:27:50 +00002660 emitCode(" Select(InFlag, N.getOperand(N.getNumOperands()-1));");
2661 }
Evan Chengb915f312005-12-09 22:45:35 +00002662
Evan Cheng045953c2006-05-10 00:05:46 +00002663 if (isRoot) {
2664 // The operands have been selected. Remove them from InFlightSet.
2665 for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2666 AE = InflightNodes.end(); AI != AE; ++AI)
Evan Cheng322812e2006-06-29 23:57:05 +00002667 emitCode("SelectionDAG::RemoveInFlightSetEntry(InFlightSet, " +
2668 *AI + ".Val);");
Evan Cheng045953c2006-05-10 00:05:46 +00002669 }
2670
Evan Chengb915f312005-12-09 22:45:35 +00002671 unsigned NumResults = Inst.getNumResults();
2672 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002673 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2674 NodeHasOptInFlag) {
Evan Chenge945f4d2006-06-14 22:22:20 +00002675 std::string Code;
2676 std::string Code2;
2677 std::string NodeName;
2678 if (!isRoot) {
2679 NodeName = "Tmp" + utostr(ResNo);
2680 emitDecl(NodeName);
2681 Code2 = NodeName + " = SDOperand(";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002682 } else {
Evan Chenge945f4d2006-06-14 22:22:20 +00002683 NodeName = "ResNode";
2684 emitDecl(NodeName, true);
2685 Code2 = NodeName + " = ";
Evan Chengbcecf332005-12-17 01:19:28 +00002686 }
Evan Chengfceb57a2006-07-15 08:45:20 +00002687 Code = "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2688 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
Evan Chenge945f4d2006-06-14 22:22:20 +00002689
2690 // Output order: results, chain, flags
2691 // Result types.
Evan Chengf8729402006-07-16 06:12:52 +00002692 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
2693 Code += ", VT" + utostr(VTNo);
2694 emitVT(getEnumName(N->getTypeNum(0)));
2695 }
Evan Chenge945f4d2006-06-14 22:22:20 +00002696 if (NodeHasChain)
2697 Code += ", MVT::Other";
2698 if (NodeHasOutFlag)
2699 Code += ", MVT::Flag";
2700
2701 // Inputs.
2702 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2703 if (HasVarOps)
2704 emitCode("Ops.push_back(Tmp" + utostr(Ops[i]) + ");");
2705 else
2706 Code += ", Tmp" + utostr(Ops[i]);
2707 }
2708
2709 if (HasVarOps) {
2710 if (NodeHasInFlag || HasImpInputs)
2711 emitCode("for (unsigned i = 2, e = N.getNumOperands()-1; "
2712 "i != e; ++i) {");
2713 else if (NodeHasOptInFlag)
Evan Chengfceb57a2006-07-15 08:45:20 +00002714 emitCode("for (unsigned i = 2, e = N.getNumOperands()-"
2715 "(HasInFlag?1:0); i != e; ++i) {");
Evan Chenge945f4d2006-06-14 22:22:20 +00002716 else
2717 emitCode("for (unsigned i = 2, e = N.getNumOperands(); "
2718 "i != e; ++i) {");
2719 emitCode(" SDOperand VarOp(0, 0);");
2720 emitCode(" Select(VarOp, N.getOperand(i));");
2721 emitCode(" Ops.push_back(VarOp);");
2722 emitCode("}");
2723 }
2724
2725 if (NodeHasChain) {
2726 if (HasVarOps)
2727 emitCode("Ops.push_back(" + ChainName + ");");
2728 else
2729 Code += ", " + ChainName;
2730 }
2731 if (NodeHasInFlag || HasImpInputs) {
2732 if (HasVarOps)
2733 emitCode("Ops.push_back(InFlag);");
2734 else
2735 Code += ", InFlag";
2736 } else if (NodeHasOptInFlag && HasVarOps) {
2737 emitCode("if (HasInFlag)");
2738 emitCode(" Ops.push_back(InFlag);");
2739 }
2740
2741 if (HasVarOps)
2742 Code += ", Ops";
2743 else if (NodeHasOptInFlag)
2744 Code = "HasInFlag ? " + Code + ", InFlag) : " + Code;
2745
2746 if (!isRoot)
2747 Code += "), 0";
2748 emitCode(Code2 + Code + ");");
2749
2750 if (NodeHasChain)
2751 // Remember which op produces the chain.
2752 if (!isRoot)
2753 emitCode(ChainName + " = SDOperand(" + NodeName +
2754 ".Val, " + utostr(PatResults) + ");");
2755 else
2756 emitCode(ChainName + " = SDOperand(" + NodeName +
2757 ", " + utostr(PatResults) + ");");
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002758
Evan Cheng045953c2006-05-10 00:05:46 +00002759 if (!isRoot)
2760 return std::make_pair(1, ResNo);
2761
Evan Chenged66e852006-03-09 08:19:11 +00002762 if (NewTF)
2763 emitCode("if (OldTF) "
2764 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2765 ChainName + ".Val, 0);");
2766
2767 for (unsigned i = 0; i < NumResults; i++)
Evan Cheng67212a02006-02-09 22:12:27 +00002768 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002769 utostr(i) + ", ResNode, " + utostr(i) + ");");
Evan Chengf9fc25d2005-12-19 22:40:04 +00002770
Evan Cheng54597732006-01-26 00:22:25 +00002771 if (NodeHasOutFlag)
Evan Chengd7805a72006-02-09 07:16:09 +00002772 emitCode("InFlag = SDOperand(ResNode, " +
Evan Cheng045953c2006-05-10 00:05:46 +00002773 utostr(NumResults + (unsigned)NodeHasChain) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002774
Chris Lattner8a0604b2006-01-28 20:31:24 +00002775 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
Evan Chenged66e852006-03-09 08:19:11 +00002776 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2777 "0, ResNode, 0);");
2778 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00002779 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002780
Evan Cheng045953c2006-05-10 00:05:46 +00002781 if (InputHasChain) {
Evan Cheng67212a02006-02-09 22:12:27 +00002782 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Cheng3eff89b2006-05-10 02:47:57 +00002783 utostr(PatResults) + ", " + ChainName + ".Val, " +
2784 ChainName + ".ResNo" + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002785 if (DoReplace)
Evan Chenged66e852006-03-09 08:19:11 +00002786 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
Evan Cheng3eff89b2006-05-10 02:47:57 +00002787 utostr(PatResults) + ", " + ChainName + ".Val, " +
2788 ChainName + ".ResNo" + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002789 }
2790
Evan Cheng97938882005-12-22 02:24:50 +00002791 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002792 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002793 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng67212a02006-02-09 22:12:27 +00002794 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2795 FoldedChains[j].first + ".Val, " +
2796 utostr(FoldedChains[j].second) + ", ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002797 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002798
2799 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2800 std::string Code =
Evan Cheng67212a02006-02-09 22:12:27 +00002801 FoldedChains[j].first + ".Val, " +
2802 utostr(FoldedChains[j].second) + ", ";
2803 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002804 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002805 }
Evan Chengb915f312005-12-09 22:45:35 +00002806 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002807
Evan Cheng54597732006-01-26 00:22:25 +00002808 if (NodeHasOutFlag)
Evan Cheng67212a02006-02-09 22:12:27 +00002809 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Cheng045953c2006-05-10 00:05:46 +00002810 utostr(PatResults + (unsigned)InputHasChain) +
Evan Chenged66e852006-03-09 08:19:11 +00002811 ", InFlag.Val, InFlag.ResNo);");
Evan Cheng97938882005-12-22 02:24:50 +00002812
Evan Chenged66e852006-03-09 08:19:11 +00002813 // User does not expect the instruction would produce a chain!
Evan Cheng045953c2006-05-10 00:05:46 +00002814 bool AddedChain = NodeHasChain && !InputHasChain;
Evan Cheng54597732006-01-26 00:22:25 +00002815 if (AddedChain && NodeHasOutFlag) {
Evan Chenged66e852006-03-09 08:19:11 +00002816 if (PatResults == 0) {
Evan Chengd7805a72006-02-09 07:16:09 +00002817 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002818 } else {
Evan Chenged66e852006-03-09 08:19:11 +00002819 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
Evan Chengd7805a72006-02-09 07:16:09 +00002820 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002821 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002822 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002823 }
Evan Cheng3eff89b2006-05-10 02:47:57 +00002824 } else if (InputHasChain && !NodeHasChain) {
2825 // One of the inner node produces a chain.
2826 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2827 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2828 if (NodeHasOutFlag) {
2829 emitCode("else if (N.ResNo > " + utostr(PatResults) + ")");
2830 emitCode(" Result = SDOperand(ResNode, N.ResNo-1);");
2831 }
2832 emitCode("else");
Chris Lattner11bcd282006-06-09 23:59:44 +00002833 emitCode(" Result = SDOperand(" + ChainName + ".Val, " +
2834 ChainName + ".ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002835 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002836 emitCode("Result = SDOperand(ResNode, N.ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002837 }
Evan Chengb915f312005-12-09 22:45:35 +00002838 } else {
2839 // If this instruction is the root, and if there is only one use of it,
2840 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002841 emitCode("if (N.Val->hasOneUse()) {");
Evan Chengfceb57a2006-07-15 08:45:20 +00002842 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, Opc" +
2843 utostr(OpcNo);
Nate Begemanb73628b2005-12-30 00:12:56 +00002844 if (N->getTypeNum(0) != MVT::isVoid)
Evan Chengf8729402006-07-16 06:12:52 +00002845 Code += ", VT" + utostr(VTNo);
Evan Cheng54597732006-01-26 00:22:25 +00002846 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002847 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002848 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002849 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002850 if (NodeHasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002851 Code += ", InFlag";
2852 emitCode(Code + ");");
2853 emitCode("} else {");
Evan Chengf8729402006-07-16 06:12:52 +00002854 emitDecl("ResNode", 1);
Evan Chengfceb57a2006-07-15 08:45:20 +00002855 Code = " ResNode = CurDAG->getTargetNode(Opc" + utostr(OpcNo);
2856 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
Evan Chengf8729402006-07-16 06:12:52 +00002857 if (N->getTypeNum(0) != MVT::isVoid) {
2858 Code += ", VT" + utostr(VTNo);
2859 emitVT(getEnumName(N->getTypeNum(0)));
2860 }
Evan Cheng54597732006-01-26 00:22:25 +00002861 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002862 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002863 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002864 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002865 if (NodeHasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002866 Code += ", InFlag";
2867 emitCode(Code + ");");
Chris Lattner11bcd282006-06-09 23:59:44 +00002868 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo"
2869 ", ResNode, 0);");
Evan Cheng67212a02006-02-09 22:12:27 +00002870 emitCode(" Result = SDOperand(ResNode, 0);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002871 emitCode("}");
Evan Chengb915f312005-12-09 22:45:35 +00002872 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002873
Evan Cheng34167212006-02-09 00:37:58 +00002874 if (isRoot)
2875 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002876 return std::make_pair(1, ResNo);
2877 } else if (Op->isSubClassOf("SDNodeXForm")) {
2878 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00002879 // PatLeaf node - the operand may or may not be a leaf node. But it should
2880 // behave like one.
2881 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
Evan Chengb915f312005-12-09 22:45:35 +00002882 unsigned ResNo = TmpNo++;
Evan Cheng21ad3922006-02-07 00:37:41 +00002883 emitDecl("Tmp" + utostr(ResNo));
2884 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Chris Lattner8a0604b2006-01-28 20:31:24 +00002885 + "(Tmp" + utostr(OpVal) + ".Val);");
Evan Chengb915f312005-12-09 22:45:35 +00002886 if (isRoot) {
Evan Cheng67212a02006-02-09 22:12:27 +00002887 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2888 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2889 utostr(ResNo) + ".ResNo);");
Evan Cheng34167212006-02-09 00:37:58 +00002890 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2891 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002892 }
2893 return std::make_pair(1, ResNo);
2894 } else {
2895 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002896 std::cerr << "\n";
2897 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002898 }
2899 }
2900
Chris Lattner488580c2006-01-28 19:06:51 +00002901 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2902 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002903 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2904 /// for, this returns true otherwise false if Pat has all types.
2905 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2906 const std::string &Prefix) {
2907 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +00002908 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +00002909 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002910 Pat->setTypes(Other->getExtTypes());
Evan Chengd7c2c862006-06-15 00:16:37 +00002911 emitCheck(Prefix + ".Val->getValueType(0) == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002912 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002913 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002914 }
2915
Evan Cheng51fecc82006-01-09 18:27:06 +00002916 unsigned OpNo =
2917 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002918 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2919 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2920 Prefix + utostr(OpNo)))
2921 return true;
2922 return false;
2923 }
2924
2925private:
Evan Cheng54597732006-01-26 00:22:25 +00002926 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002927 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002928 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2929 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002930 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002931 unsigned OpNo =
2932 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002933 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002934 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2935 TreePatternNode *Child = N->getChild(i);
2936 if (!Child->isLeaf()) {
Evan Cheng54597732006-01-26 00:22:25 +00002937 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002938 } else {
2939 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002940 if (!Child->getName().empty()) {
2941 std::string Name = RootName + utostr(OpNo);
2942 if (Duplicates.find(Name) != Duplicates.end())
2943 // A duplicate! Do not emit a copy for this node.
2944 continue;
2945 }
2946
Evan Chengb915f312005-12-09 22:45:35 +00002947 Record *RR = DI->getDef();
2948 if (RR->isSubClassOf("Register")) {
2949 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002950 if (RVT == MVT::Flag) {
Evan Cheng34167212006-02-09 00:37:58 +00002951 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
Evan Chengb2c6d492006-01-11 22:16:13 +00002952 } else {
2953 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002954 emitDecl("Chain");
2955 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002956 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002957 ChainEmitted = true;
2958 }
Evan Cheng34167212006-02-09 00:37:58 +00002959 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2960 RootName + utostr(OpNo) + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002961 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002962 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
Evan Cheng2618d072006-05-17 20:37:59 +00002963 ", " + getEnumName(RVT) + "), " +
Evan Chengd7805a72006-02-09 07:16:09 +00002964 RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng67212a02006-02-09 22:12:27 +00002965 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2966 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00002967 }
2968 }
2969 }
2970 }
2971 }
Evan Cheng54597732006-01-26 00:22:25 +00002972
Evan Chengbc6b86a2006-06-14 19:27:50 +00002973 if (HasInFlag)
2974 emitCode("Select(InFlag, " + RootName +
Evan Cheng34167212006-02-09 00:37:58 +00002975 ".getOperand(" + utostr(OpNo) + "));");
Evan Chengb915f312005-12-09 22:45:35 +00002976 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002977
2978 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002979 /// as specified by the instruction. It returns true if any copy is
2980 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002981 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002982 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002983 Record *Op = N->getOperator();
2984 if (Op->isSubClassOf("Instruction")) {
2985 const DAGInstruction &Inst = ISE.getInstruction(Op);
2986 const CodeGenTarget &CGT = ISE.getTargetInfo();
Evan Cheng4fba2812005-12-20 07:37:41 +00002987 unsigned NumImpResults = Inst.getNumImpResults();
2988 for (unsigned i = 0; i < NumImpResults; i++) {
2989 Record *RR = Inst.getImpResult(i);
2990 if (RR->isSubClassOf("Register")) {
2991 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2992 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002993 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002994 emitDecl("Chain");
2995 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002996 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002997 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002998 }
Evan Chengfceb57a2006-07-15 08:45:20 +00002999 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName +
3000 ", " + ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00003001 ", InFlag).Val;");
3002 emitCode(ChainName + " = SDOperand(ResNode, 1);");
3003 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00003004 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00003005 }
3006 }
3007 }
3008 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00003009 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00003010 }
Evan Chengb915f312005-12-09 22:45:35 +00003011};
3012
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00003013/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
3014/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00003015/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00003016void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Chenge41bf822006-02-05 06:43:12 +00003017 std::vector<std::pair<bool, std::string> > &GeneratedCode,
Evan Chengf8729402006-07-16 06:12:52 +00003018 std::set<std::pair<unsigned, std::string> > &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00003019 std::vector<std::string> &TargetOpcodes,
Evan Chengf8729402006-07-16 06:12:52 +00003020 std::vector<std::string> &TargetVTs,
Evan Chenge41bf822006-02-05 06:43:12 +00003021 bool DoReplace) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003022 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
3023 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00003024 GeneratedCode, GeneratedDecl,
3025 TargetOpcodes, TargetVTs,
Evan Chengfceb57a2006-07-15 08:45:20 +00003026 DoReplace);
Evan Chengb915f312005-12-09 22:45:35 +00003027
Chris Lattner8fc35682005-09-23 23:16:51 +00003028 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00003029 bool FoundChain = false;
Evan Chenge41bf822006-02-05 06:43:12 +00003030 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00003031
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003032 // TP - Get *SOME* tree pattern, we don't care which.
3033 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00003034
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003035 // At this point, we know that we structurally match the pattern, but the
3036 // types of the nodes may not match. Figure out the fewest number of type
3037 // comparisons we need to emit. For example, if there is only one integer
3038 // type supported by a target, there should be no type comparisons at all for
3039 // integer patterns!
3040 //
3041 // To figure out the fewest number of type checks needed, clone the pattern,
3042 // remove the types, then perform type inference on the pattern as a whole.
3043 // If there are unresolved types, emit an explicit check for those types,
3044 // apply the type to the tree, then rerun type inference. Iterate until all
3045 // types are resolved.
3046 //
Evan Cheng58e84a62005-12-14 22:02:59 +00003047 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003048 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00003049
3050 do {
3051 // Resolve/propagate as many types as possible.
3052 try {
3053 bool MadeChange = true;
3054 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00003055 MadeChange = Pat->ApplyTypeConstraints(TP,
3056 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00003057 } catch (...) {
3058 assert(0 && "Error: could not find consistent types for something we"
3059 " already decided was ok!");
3060 abort();
3061 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003062
Chris Lattner7e82f132005-10-15 21:34:21 +00003063 // Insert a check for an unresolved type and add it to the tree. If we find
3064 // an unresolved type to add a check for, this returns true and we iterate,
3065 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00003066 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00003067
Evan Cheng863bf5a2006-03-20 22:53:06 +00003068 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00003069 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00003070}
3071
Chris Lattner24e00a42006-01-29 04:41:05 +00003072/// EraseCodeLine - Erase one code line from all of the patterns. If removing
3073/// a line causes any of them to be empty, remove them and return true when
3074/// done.
3075static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
3076 std::vector<std::pair<bool, std::string> > > >
3077 &Patterns) {
3078 bool ErasedPatterns = false;
3079 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3080 Patterns[i].second.pop_back();
3081 if (Patterns[i].second.empty()) {
3082 Patterns.erase(Patterns.begin()+i);
3083 --i; --e;
3084 ErasedPatterns = true;
3085 }
3086 }
3087 return ErasedPatterns;
3088}
3089
Chris Lattner8bc74722006-01-29 04:25:26 +00003090/// EmitPatterns - Emit code for at least one pattern, but try to group common
3091/// code together between the patterns.
3092void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
3093 std::vector<std::pair<bool, std::string> > > >
3094 &Patterns, unsigned Indent,
3095 std::ostream &OS) {
3096 typedef std::pair<bool, std::string> CodeLine;
3097 typedef std::vector<CodeLine> CodeList;
3098 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3099
3100 if (Patterns.empty()) return;
3101
Chris Lattner24e00a42006-01-29 04:41:05 +00003102 // Figure out how many patterns share the next code line. Explicitly copy
3103 // FirstCodeLine so that we don't invalidate a reference when changing
3104 // Patterns.
3105 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00003106 unsigned LastMatch = Patterns.size()-1;
3107 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3108 --LastMatch;
3109
3110 // If not all patterns share this line, split the list into two pieces. The
3111 // first chunk will use this line, the second chunk won't.
3112 if (LastMatch != 0) {
3113 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3114 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3115
3116 // FIXME: Emit braces?
3117 if (Shared.size() == 1) {
3118 PatternToMatch &Pattern = *Shared.back().first;
3119 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3120 Pattern.getSrcPattern()->print(OS);
3121 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3122 Pattern.getDstPattern()->print(OS);
3123 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003124 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003125 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003126 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003127 << " cost = "
Evan Chenge6f32032006-07-19 00:24:41 +00003128 << getResultPatternCost(Pattern.getDstPattern(), *this)
3129 << " size = "
3130 << getResultPatternSize(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003131 }
3132 if (!FirstCodeLine.first) {
3133 OS << std::string(Indent, ' ') << "{\n";
3134 Indent += 2;
3135 }
3136 EmitPatterns(Shared, Indent, OS);
3137 if (!FirstCodeLine.first) {
3138 Indent -= 2;
3139 OS << std::string(Indent, ' ') << "}\n";
3140 }
3141
3142 if (Other.size() == 1) {
3143 PatternToMatch &Pattern = *Other.back().first;
3144 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3145 Pattern.getSrcPattern()->print(OS);
3146 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3147 Pattern.getDstPattern()->print(OS);
3148 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003149 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003150 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003151 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003152 << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00003153 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003154 }
3155 EmitPatterns(Other, Indent, OS);
3156 return;
3157 }
3158
Chris Lattner24e00a42006-01-29 04:41:05 +00003159 // Remove this code from all of the patterns that share it.
3160 bool ErasedPatterns = EraseCodeLine(Patterns);
3161
Chris Lattner8bc74722006-01-29 04:25:26 +00003162 bool isPredicate = FirstCodeLine.first;
3163
3164 // Otherwise, every pattern in the list has this line. Emit it.
3165 if (!isPredicate) {
3166 // Normal code.
3167 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3168 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00003169 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3170
3171 // If the next code line is another predicate, and if all of the pattern
3172 // in this group share the same next line, emit it inline now. Do this
3173 // until we run out of common predicates.
3174 while (!ErasedPatterns && Patterns.back().second.back().first) {
3175 // Check that all of fhe patterns in Patterns end with the same predicate.
3176 bool AllEndWithSamePredicate = true;
3177 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3178 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3179 AllEndWithSamePredicate = false;
3180 break;
3181 }
3182 // If all of the predicates aren't the same, we can't share them.
3183 if (!AllEndWithSamePredicate) break;
3184
3185 // Otherwise we can. Emit it shared now.
3186 OS << " &&\n" << std::string(Indent+4, ' ')
3187 << Patterns.back().second.back().second;
3188 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00003189 }
Chris Lattner24e00a42006-01-29 04:41:05 +00003190
3191 OS << ") {\n";
3192 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00003193 }
3194
3195 EmitPatterns(Patterns, Indent, OS);
3196
3197 if (isPredicate)
3198 OS << std::string(Indent-2, ' ') << "}\n";
3199}
3200
3201
Chris Lattner37481472005-09-26 21:59:35 +00003202
3203namespace {
3204 /// CompareByRecordName - An ordering predicate that implements less-than by
3205 /// comparing the names records.
3206 struct CompareByRecordName {
3207 bool operator()(const Record *LHS, const Record *RHS) const {
3208 // Sort by name first.
3209 if (LHS->getName() < RHS->getName()) return true;
3210 // If both names are equal, sort by pointer.
3211 return LHS->getName() == RHS->getName() && LHS < RHS;
3212 }
3213 };
3214}
3215
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003216void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003217 std::string InstNS = Target.inst_begin()->second.Namespace;
3218 if (!InstNS.empty()) InstNS += "::";
3219
Chris Lattner602f6922006-01-04 00:25:00 +00003220 // Group the patterns by their top-level opcodes.
3221 std::map<Record*, std::vector<PatternToMatch*>,
3222 CompareByRecordName> PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00003223 // All unique target node emission functions.
3224 std::map<std::string, unsigned> EmitFunctions;
Chris Lattner602f6922006-01-04 00:25:00 +00003225 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3226 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3227 if (!Node->isLeaf()) {
3228 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3229 } else {
3230 const ComplexPattern *CP;
3231 if (IntInit *II =
3232 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3233 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3234 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3235 std::vector<Record*> OpNodes = CP->getRootNodes();
3236 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00003237 PatternsByOpcode[OpNodes[j]]
3238 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003239 }
3240 } else {
3241 std::cerr << "Unrecognized opcode '";
3242 Node->dump();
3243 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00003244 std::cerr <<
3245 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00003246 std::cerr << "'!\n";
3247 exit(1);
3248 }
3249 }
3250 }
3251
3252 // Emit one Select_* method for each top-level opcode. We do this instead of
3253 // emitting one giant switch statement to support compilers where this will
3254 // result in the recursive functions taking less stack space.
3255 for (std::map<Record*, std::vector<PatternToMatch*>,
3256 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3257 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00003258 const std::string &OpName = PBOI->first->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00003259 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Evan Chenge41bf822006-02-05 06:43:12 +00003260 bool OptSlctOrder =
3261 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3262 OpcodeInfo.getNumResults() > 0);
Chris Lattner602f6922006-01-04 00:25:00 +00003263 std::vector<PatternToMatch*> &Patterns = PBOI->second;
Chris Lattner355408b2006-01-29 02:43:35 +00003264 assert(!Patterns.empty() && "No patterns but map has entry?");
Chris Lattner602f6922006-01-04 00:25:00 +00003265
3266 // We want to emit all of the matching code now. However, we want to emit
3267 // the matches in order of minimal cost. Sort the patterns so the least
3268 // cost one is at the start.
3269 std::stable_sort(Patterns.begin(), Patterns.end(),
3270 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00003271
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003272 typedef std::vector<std::pair<bool, std::string> > CodeList;
Evan Chengfceb57a2006-07-15 08:45:20 +00003273 typedef std::vector<std::pair<bool, std::string> >::iterator CodeListI;
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003274
3275 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
Evan Chengfceb57a2006-07-15 08:45:20 +00003276 std::vector<std::vector<std::string> > PatternOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +00003277 std::vector<std::vector<std::string> > PatternVTs;
3278 std::vector<std::set<std::pair<unsigned, std::string> > > PatternDecls;
3279 std::set<std::pair<unsigned, std::string> > AllGenDecls;
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003280 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003281 CodeList GeneratedCode;
Evan Chengf8729402006-07-16 06:12:52 +00003282 std::set<std::pair<unsigned, std::string> > GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +00003283 std::vector<std::string> TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +00003284 std::vector<std::string> TargetVTs;
Evan Cheng21ad3922006-02-07 00:37:41 +00003285 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Evan Chengf8729402006-07-16 06:12:52 +00003286 TargetOpcodes, TargetVTs, OptSlctOrder);
3287 for (std::set<std::pair<unsigned, std::string> >::iterator
Evan Chengfceb57a2006-07-15 08:45:20 +00003288 si = GeneratedDecl.begin(), se = GeneratedDecl.end(); si!=se; ++si)
3289 AllGenDecls.insert(*si);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003290 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
Evan Chengfceb57a2006-07-15 08:45:20 +00003291 PatternDecls.push_back(GeneratedDecl);
3292 PatternOpcodes.push_back(TargetOpcodes);
Evan Chengf8729402006-07-16 06:12:52 +00003293 PatternVTs.push_back(TargetVTs);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003294 }
3295
3296 // Scan the code to see if all of the patterns are reachable and if it is
3297 // possible that the last one might not match.
3298 bool mightNotMatch = true;
3299 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3300 CodeList &GeneratedCode = CodeForPatterns[i].second;
3301 mightNotMatch = false;
Chris Lattner355408b2006-01-29 02:43:35 +00003302
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003303 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3304 if (GeneratedCode[j].first) { // predicate.
3305 mightNotMatch = true;
3306 break;
3307 }
3308 }
Chris Lattner355408b2006-01-29 02:43:35 +00003309
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003310 // If this pattern definitely matches, and if it isn't the last one, the
3311 // patterns after it CANNOT ever match. Error out.
3312 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3313 std::cerr << "Pattern '";
3314 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3315 std::cerr << "' is impossible to select!\n";
3316 exit(1);
3317 }
3318 }
Evan Cheng21ad3922006-02-07 00:37:41 +00003319
Evan Chengfceb57a2006-07-15 08:45:20 +00003320 // Factor target node emission code (emitted by EmitResultCode) into
3321 // separate functions. Uniquing and share them among all instruction
3322 // selection routines.
3323 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3324 CodeList &GeneratedCode = CodeForPatterns[i].second;
3325 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
Evan Chengf8729402006-07-16 06:12:52 +00003326 std::vector<std::string> &TargetVTs = PatternVTs[i];
3327 std::set<std::pair<unsigned, std::string> > Decls = PatternDecls[i];
Evan Chengfceb57a2006-07-15 08:45:20 +00003328 int CodeSize = (int)GeneratedCode.size();
3329 int LastPred = -1;
3330 for (int j = CodeSize-1; j >= 0; --j) {
3331 if (GeneratedCode[j].first) {
3332 LastPred = j;
3333 break;
3334 }
3335 }
3336
3337 std::string CalleeDecls;
3338 std::string CalleeCode = "(SDOperand &Result, SDOperand &N";
3339 std::string CallerCode = "(Result, N";
3340 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
3341 CalleeCode += ", unsigned Opc" + utostr(j);
3342 CallerCode += ", " + TargetOpcodes[j];
3343 }
Evan Chengf8729402006-07-16 06:12:52 +00003344 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
3345 CalleeCode += ", MVT::ValueType VT" + utostr(j);
3346 CallerCode += ", " + TargetVTs[j];
3347 }
3348 for (std::set<std::pair<unsigned, std::string> >::iterator
Evan Chengfceb57a2006-07-15 08:45:20 +00003349 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
3350 std::string Name = I->second;
Evan Chengf8729402006-07-16 06:12:52 +00003351 if (I->first == 0) {
3352 if (Name == "InFlag" ||
3353 (Name.size() > 3 &&
3354 Name[0] == 'T' && Name[1] == 'm' && Name[2] == 'p')) {
3355 CalleeDecls += " SDOperand " + Name + "(0, 0);\n";
3356 continue;
3357 }
3358 CalleeCode += ", SDOperand &" + Name;
3359 CallerCode += ", " + Name;
3360 } else if (I->first == 1) {
3361 if (Name == "ResNode") {
3362 CalleeDecls += " SDNode *" + Name + " = NULL;\n";
3363 continue;
3364 }
Evan Chengfceb57a2006-07-15 08:45:20 +00003365 CalleeCode += ", SDNode *" + Name;
3366 CallerCode += ", " + Name;
3367 } else {
Evan Chengf8729402006-07-16 06:12:52 +00003368 CalleeCode += ", bool " + Name;
Evan Chengfceb57a2006-07-15 08:45:20 +00003369 CallerCode += ", " + Name;
3370 }
3371 }
3372 CallerCode += ");";
3373 CalleeCode += ") ";
Evan Chengfb878a32006-07-16 06:14:37 +00003374#ifdef __GNUC__
Evan Chengfceb57a2006-07-15 08:45:20 +00003375 // Prevent emission routines from being inlined to reduce selection
3376 // routines stack frame sizes.
3377 CalleeCode += "__attribute__((noinline)) ";
3378#endif
3379 CalleeCode += "{\n" + CalleeDecls;
3380 for (int j = LastPred+1; j < CodeSize; ++j)
3381 CalleeCode += " " + GeneratedCode[j].second + '\n';
3382 for (int j = LastPred+1; j < CodeSize; ++j)
3383 GeneratedCode.pop_back();
3384 CalleeCode += "}\n";
3385
3386 // Uniquing the emission routines.
3387 unsigned EmitFuncNum;
3388 std::map<std::string, unsigned>::iterator EFI =
3389 EmitFunctions.find(CalleeCode);
3390 if (EFI != EmitFunctions.end()) {
3391 EmitFuncNum = EFI->second;
3392 } else {
3393 EmitFuncNum = EmitFunctions.size();
3394 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
3395 OS << "void " << "Emit_" << utostr(EmitFuncNum) << CalleeCode;
3396 }
3397
3398 // Replace the emission code within selection routines with calls to the
3399 // emission functions.
3400 CallerCode = "Emit_" + utostr(EmitFuncNum) + CallerCode;
3401 GeneratedCode.push_back(std::make_pair(false, CallerCode));
3402 GeneratedCode.push_back(std::make_pair(false, "return;"));
3403 }
3404
3405 // Print function.
3406 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
3407 if (OptSlctOrder) {
3408 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3409 << " && N.getValue(0).hasOneUse()) {\n"
3410 << " SDOperand Dummy = "
3411 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3412 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3413 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3414 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3415 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3416 << " Result = Dummy;\n"
3417 << " return;\n"
3418 << " }\n";
3419 }
3420
Evan Cheng21ad3922006-02-07 00:37:41 +00003421 // Print all declarations.
Evan Chengf8729402006-07-16 06:12:52 +00003422 for (std::set<std::pair<unsigned, std::string> >::iterator
Evan Chengfceb57a2006-07-15 08:45:20 +00003423 I = AllGenDecls.begin(), E = AllGenDecls.end(); I != E; ++I)
Evan Chengf8729402006-07-16 06:12:52 +00003424 if (I->first == 0)
3425 OS << " SDOperand " << I->second << "(0, 0);\n";
3426 else if (I->first == 1)
Evan Chengfceb57a2006-07-15 08:45:20 +00003427 OS << " SDNode *" << I->second << " = NULL;\n";
Evan Chengd7805a72006-02-09 07:16:09 +00003428 else
Evan Chengf8729402006-07-16 06:12:52 +00003429 OS << " bool " << I->second << " = false;\n";
Evan Cheng21ad3922006-02-07 00:37:41 +00003430
Chris Lattner8bc74722006-01-29 04:25:26 +00003431 // Loop through and reverse all of the CodeList vectors, as we will be
3432 // accessing them from their logical front, but accessing the end of a
3433 // vector is more efficient.
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003434 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3435 CodeList &GeneratedCode = CodeForPatterns[i].second;
Chris Lattner8bc74722006-01-29 04:25:26 +00003436 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003437 }
Chris Lattner602f6922006-01-04 00:25:00 +00003438
Chris Lattner8bc74722006-01-29 04:25:26 +00003439 // Next, reverse the list of patterns itself for the same reason.
3440 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3441
3442 // Emit all of the patterns now, grouped together to share code.
3443 EmitPatterns(CodeForPatterns, 2, OS);
3444
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003445 // If the last pattern has predicates (which could fail) emit code to catch
3446 // the case where nothing handles a pattern.
Chris Lattnerb026e702006-03-28 00:41:33 +00003447 if (mightNotMatch) {
3448 OS << " std::cerr << \"Cannot yet select: \";\n";
3449 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3450 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3451 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3452 OS << " N.Val->dump(CurDAG);\n";
3453 } else {
3454 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3455 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3456 << " std::cerr << \"intrinsic %\"<< "
3457 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3458 }
3459 OS << " std::cerr << '\\n';\n"
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003460 << " abort();\n";
Chris Lattnerb026e702006-03-28 00:41:33 +00003461 }
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003462 OS << "}\n\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003463 }
3464
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003465 // Emit boilerplate.
Evan Cheng34167212006-02-09 00:37:58 +00003466 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003467 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng34167212006-02-09 00:37:58 +00003468 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003469 << " // Select the flag operand.\n"
3470 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng34167212006-02-09 00:37:58 +00003471 << " Select(Ops.back(), Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00003472 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003473 << " std::vector<MVT::ValueType> VTs;\n"
3474 << " VTs.push_back(MVT::Other);\n"
3475 << " VTs.push_back(MVT::Flag);\n"
3476 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003477 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3478 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003479 << " Result = New.getValue(N.ResNo);\n"
3480 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003481 << "}\n\n";
3482
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003483 OS << "// The main instruction selector code.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003484 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003485 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003486 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003487 << "INSTRUCTION_LIST_END)) {\n"
3488 << " Result = N;\n"
3489 << " return; // Already selected.\n"
3490 << " }\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003491 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003492 << " if (CGMI != CodeGenMap.end()) {\n"
3493 << " Result = CGMI->second;\n"
3494 << " return;\n"
3495 << " }\n\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003496 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003497 << " default: break;\n"
3498 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003499 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003500 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003501 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003502 << " case ISD::TargetConstant:\n"
3503 << " case ISD::TargetConstantPool:\n"
3504 << " case ISD::TargetFrameIndex:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00003505 << " case ISD::TargetJumpTable:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003506 << " case ISD::TargetGlobalAddress: {\n"
3507 << " Result = N;\n"
3508 << " return;\n"
3509 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003510 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003511 << " case ISD::AssertZext: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003512 << " SDOperand Tmp0;\n"
3513 << " Select(Tmp0, N.getOperand(0));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003514 << " if (!N.Val->hasOneUse())\n"
3515 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3516 << "Tmp0.Val, Tmp0.ResNo);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003517 << " Result = Tmp0;\n"
3518 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003519 << " }\n"
3520 << " case ISD::TokenFactor:\n"
3521 << " if (N.getNumOperands() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003522 << " SDOperand Op0, Op1;\n"
3523 << " Select(Op0, N.getOperand(0));\n"
3524 << " Select(Op1, N.getOperand(1));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003525 << " Result = \n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003526 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003527 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3528 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003529 << " } else {\n"
3530 << " std::vector<SDOperand> Ops;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003531 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3532 << " SDOperand Val;\n"
3533 << " Select(Val, N.getOperand(i));\n"
3534 << " Ops.push_back(Val);\n"
3535 << " }\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003536 << " Result = \n"
3537 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3538 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3539 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003540 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003541 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003542 << " case ISD::CopyFromReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003543 << " SDOperand Chain;\n"
3544 << " Select(Chain, N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003545 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3546 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003547 << " if (N.Val->getNumValues() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003548 << " if (Chain == N.getOperand(0)) {\n"
3549 << " Result = N; // No change\n"
3550 << " return;\n"
3551 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003552 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003553 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3554 << "New.Val, 0);\n"
3555 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3556 << "New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003557 << " Result = New.getValue(N.ResNo);\n"
3558 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003559 << " } else {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003560 << " SDOperand Flag;\n"
3561 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003562 << " if (Chain == N.getOperand(0) &&\n"
Evan Cheng34167212006-02-09 00:37:58 +00003563 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3564 << " Result = N; // No change\n"
3565 << " return;\n"
3566 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003567 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003568 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3569 << "New.Val, 0);\n"
3570 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3571 << "New.Val, 1);\n"
3572 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3573 << "New.Val, 2);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003574 << " Result = New.getValue(N.ResNo);\n"
3575 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003576 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003577 << " }\n"
3578 << " case ISD::CopyToReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003579 << " SDOperand Chain;\n"
3580 << " Select(Chain, N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003581 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Evan Cheng34167212006-02-09 00:37:58 +00003582 << " SDOperand Val;\n"
3583 << " Select(Val, N.getOperand(2));\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003584 << " Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003585 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003586 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003587 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003588 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3589 << "Result.Val, 0);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003590 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003591 << " SDOperand Flag(0, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003592 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003593 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003594 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003595 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003596 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3597 << "Result.Val, 0);\n"
3598 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3599 << "Result.Val, 1);\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003600 << " Result = Result.getValue(N.ResNo);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003601 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003602 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003603 << " }\n"
Chris Lattner947604b2006-03-24 21:52:20 +00003604 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003605
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003606
Chris Lattner602f6922006-01-04 00:25:00 +00003607 // Loop over all of the case statements, emiting a call to each method we
3608 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003609 for (std::map<Record*, std::vector<PatternToMatch*>,
3610 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3611 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003612 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00003613 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00003614 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Evan Cheng34167212006-02-09 00:37:58 +00003615 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
Chris Lattner81303322005-09-23 19:36:15 +00003616 }
Chris Lattner81303322005-09-23 19:36:15 +00003617
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003618 OS << " } // end of big switch.\n\n"
3619 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00003620 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3621 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3622 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003623 << " N.Val->dump(CurDAG);\n"
3624 << " } else {\n"
3625 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3626 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3627 << " std::cerr << \"intrinsic %\"<< "
3628 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3629 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003630 << " std::cerr << '\\n';\n"
3631 << " abort();\n"
3632 << "}\n";
3633}
3634
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003635void DAGISelEmitter::run(std::ostream &OS) {
3636 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3637 " target", OS);
3638
Chris Lattner1f39e292005-09-14 00:09:24 +00003639 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3640 << "// *** instruction selector class. These functions are really "
3641 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003642
Chris Lattner296dfe32005-09-24 00:50:51 +00003643 OS << "// Instance var to keep track of multiply used nodes that have \n"
3644 << "// already been selected.\n"
3645 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003646
3647 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003648 << "// and their place handle nodes.\n";
3649 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3650 OS << "// Instance var to keep track of mapping of place handle nodes\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003651 << "// and their replacement nodes.\n";
3652 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
Evan Cheng61a02092006-04-28 02:08:10 +00003653 OS << "// Keep track of nodes that are currently being selecte and therefore\n"
3654 << "// should not be folded.\n";
3655 OS << "std::set<SDNode*> InFlightSet;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003656
3657 OS << "\n";
3658 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3659 << "std::set<SDNode *> &Visited) {\n";
3660 OS << " if (found || !Visited.insert(Use).second) return;\n";
3661 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3662 OS << " SDNode *N = Use->getOperand(i).Val;\n";
Evan Cheng553ef1b2006-05-25 20:16:55 +00003663 OS << " if (N != Def) {\n";
3664 OS << " findNonImmUse(N, Def, found, Visited);\n";
3665 OS << " } else {\n";
3666 OS << " found = true;\n";
3667 OS << " break;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003668 OS << " }\n";
3669 OS << " }\n";
3670 OS << "}\n";
3671
3672 OS << "\n";
3673 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3674 OS << " std::set<SDNode *> Visited;\n";
3675 OS << " bool found = false;\n";
3676 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3677 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3678 OS << " if (N != Def) {\n";
3679 OS << " findNonImmUse(N, Def, found, Visited);\n";
3680 OS << " if (found) break;\n";
3681 OS << " }\n";
3682 OS << " }\n";
3683 OS << " return found;\n";
3684 OS << "}\n";
3685
3686 OS << "\n";
Evan Cheng024524f2006-02-06 06:03:35 +00003687 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003688 << "// handle node in ReplaceMap.\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003689 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3690 << "unsigned RNum) {\n";
3691 OS << " SDOperand N(H, HNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003692 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3693 OS << " if (HMI != HandleMap.end()) {\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003694 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003695 OS << " HandleMap.erase(N);\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003696 OS << " }\n";
3697 OS << "}\n";
3698
3699 OS << "\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003700 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3701 OS << "// handles.Some handles do not yet have replacements because the\n";
3702 OS << "// nodes they replacements have only dead readers.\n";
3703 OS << "void SelectDanglingHandles() {\n";
3704 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3705 << "HandleMap.begin(),\n"
3706 << " E = HandleMap.end(); I != E; ++I) {\n";
3707 OS << " SDOperand N = I->first;\n";
Evan Cheng34167212006-02-09 00:37:58 +00003708 OS << " SDOperand R;\n";
3709 OS << " Select(R, N.getValue(0));\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003710 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003711 OS << " }\n";
3712 OS << "}\n";
3713 OS << "\n";
3714 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003715 OS << "// specific nodes.\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003716 OS << "void ReplaceHandles() {\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003717 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3718 << "ReplaceMap.begin(),\n"
3719 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3720 OS << " SDOperand From = I->first;\n";
3721 OS << " SDOperand To = I->second;\n";
3722 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3723 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3724 OS << " SDNode *Use = *UI;\n";
3725 OS << " std::vector<SDOperand> Ops;\n";
Chris Lattner11bcd282006-06-09 23:59:44 +00003726 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i){\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003727 OS << " SDOperand O = Use->getOperand(i);\n";
3728 OS << " if (O.Val == From.Val)\n";
3729 OS << " Ops.push_back(To);\n";
3730 OS << " else\n";
3731 OS << " Ops.push_back(O);\n";
3732 OS << " }\n";
3733 OS << " SDOperand U = SDOperand(Use, 0);\n";
3734 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3735 OS << " }\n";
3736 OS << " }\n";
3737 OS << "}\n";
3738
3739 OS << "\n";
Evan Chenged66e852006-03-09 08:19:11 +00003740 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3741 OS << "// if the folding were to happen. This is called when, for example,\n";
3742 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3743 OS << "// then the resulting node's input chain would be the load's input\n";
3744 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3745 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3746 OS << "// with the other operands along with the input chain of the load.\n";
3747 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3748 << "SDNode *Chain, SDNode* &OldTF) {\n";
3749 OS << " OldTF = NULL;\n";
3750 OS << " if (N == Chain) {\n";
3751 OS << " return N->getOperand(0);\n";
3752 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3753 OS << " N->isOperand(Chain)) {\n";
3754 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3755 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3756 << "CodeGenMap.find(Ch);\n";
3757 OS << " if (CGMI != CodeGenMap.end())\n";
3758 OS << " return SDOperand(0, 0);\n";
3759 OS << " OldTF = Chain;\n";
3760 OS << " std::vector<SDOperand> Ops;\n";
3761 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3762 OS << " SDOperand Op = Chain->getOperand(i);\n";
3763 OS << " if (Op.Val == N)\n";
3764 OS << " Ops.push_back(N->getOperand(0));\n";
3765 OS << " else\n";
3766 OS << " Ops.push_back(Op);\n";
3767 OS << " }\n";
3768 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3769 OS << " }\n";
3770 OS << " return SDOperand(0, 0);\n";
3771 OS << "}\n";
3772
3773 OS << "\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003774 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3775 OS << "SDOperand SelectRoot(SDOperand N) {\n";
Evan Cheng34167212006-02-09 00:37:58 +00003776 OS << " SDOperand ResNode;\n";
3777 OS << " Select(ResNode, N);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003778 OS << " SelectDanglingHandles();\n";
3779 OS << " ReplaceHandles();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003780 OS << " ReplaceMap.clear();\n";
Evan Cheng34167212006-02-09 00:37:58 +00003781 OS << " return ResNode;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003782 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003783
Chris Lattner550525e2006-03-24 21:48:51 +00003784 Intrinsics = LoadIntrinsics(Records);
Chris Lattnerca559d02005-09-08 21:03:01 +00003785 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003786 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003787 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003788 ParsePatternFragments(OS);
3789 ParseInstructions();
3790 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003791
Chris Lattnere97603f2005-09-28 19:27:25 +00003792 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003793 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003794 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003795
Chris Lattnere46e17b2005-09-29 19:28:10 +00003796
3797 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3798 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003799 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3800 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003801 std::cerr << "\n";
3802 });
3803
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003804 // At this point, we have full information about the 'Patterns' we need to
3805 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003806 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003807 EmitInstructionSelector(OS);
3808
3809 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3810 E = PatternFragments.end(); I != E; ++I)
3811 delete I->second;
3812 PatternFragments.clear();
3813
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003814 Instructions.clear();
3815}