blob: 564e194f72f504c932da22f49fc1a2d4167ded39 [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
124 if (OpNo < NumResults)
125 return N; // FIXME: need value #
126 else
127 return N->getChild(OpNo-NumResults);
128}
129
130/// ApplyTypeConstraint - Given a node in a pattern, apply this type
131/// constraint to the nodes operands. This returns true if it makes a
132/// change, false otherwise. If a type contradiction is found, throw an
133/// exception.
134bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
135 const SDNodeInfo &NodeInfo,
136 TreePattern &TP) const {
137 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000138 assert(NumResults <= 1 &&
139 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000140
141 // Check that the number of operands is sane.
142 if (NodeInfo.getNumOperands() >= 0) {
143 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
144 TP.error(N->getOperator()->getName() + " node requires exactly " +
145 itostr(NodeInfo.getNumOperands()) + " operands!");
146 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000147
148 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000149
150 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
151
152 switch (ConstraintType) {
153 default: assert(0 && "Unknown constraint type!");
154 case SDTCisVT:
155 // Operand must be a particular type.
156 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000157 case SDTCisPtrTy: {
158 // Operand must be same as target pointer type.
Evan Cheng2618d072006-05-17 20:37:59 +0000159 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000160 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000161 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000162 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000163 std::vector<MVT::ValueType> IntVTs =
164 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000165
166 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000167 if (IntVTs.size() == 1)
168 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000169 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000170 }
171 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000172 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000173 std::vector<MVT::ValueType> FPVTs =
174 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000175
176 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000177 if (FPVTs.size() == 1)
178 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000179 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000180 }
Chris Lattner32707602005-09-08 23:22:48 +0000181 case SDTCisSameAs: {
182 TreePatternNode *OtherNode =
183 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000184 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
185 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000186 }
187 case SDTCisVTSmallerThanOp: {
188 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
189 // have an integer type that is smaller than the VT.
190 if (!NodeToApply->isLeaf() ||
191 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
192 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
193 ->isSubClassOf("ValueType"))
194 TP.error(N->getOperator()->getName() + " expects a VT operand!");
195 MVT::ValueType VT =
196 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
197 if (!MVT::isInteger(VT))
198 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
199
200 TreePatternNode *OtherNode =
201 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000202
203 // It must be integer.
204 bool MadeChange = false;
205 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
206
Nate Begemanb73628b2005-12-30 00:12:56 +0000207 // This code only handles nodes that have one type set. Assert here so
208 // that we can change this if we ever need to deal with multiple value
209 // types at this point.
210 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
211 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000212 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
213 return false;
214 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000215 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000216 TreePatternNode *BigOperand =
217 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
218
219 // Both operands must be integer or FP, but we don't care which.
220 bool MadeChange = false;
221
Nate Begemanb73628b2005-12-30 00:12:56 +0000222 // This code does not currently handle nodes which have multiple types,
223 // where some types are integer, and some are fp. Assert that this is not
224 // the case.
225 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
226 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
227 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
228 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
229 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
230 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000231 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000232 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000233 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000234 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000235 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000236 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000237 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
238
239 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
240
Nate Begemanb73628b2005-12-30 00:12:56 +0000241 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000242 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000243 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000244 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
245 } else {
246 VTs.clear();
247 }
248
249 switch (VTs.size()) {
250 default: // Too many VT's to pick from.
251 case 0: break; // No info yet.
252 case 1:
253 // Only one VT of this flavor. Cannot ever satisify the constraints.
254 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
255 case 2:
256 // If we have exactly two possible types, the little operand must be the
257 // small one, the big operand should be the big one. Common with
258 // float/double for example.
259 assert(VTs[0] < VTs[1] && "Should be sorted!");
260 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
261 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
262 break;
263 }
264 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000265 }
Chris Lattner697f8842006-03-20 05:39:48 +0000266 case SDTCisIntVectorOfSameSize: {
267 TreePatternNode *OtherOperand =
268 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
269 N, NumResults);
270 if (OtherOperand->hasTypeSet()) {
271 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
272 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
273 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
274 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
275 return NodeToApply->UpdateNodeType(IVT, TP);
276 }
277 return false;
278 }
Chris Lattner32707602005-09-08 23:22:48 +0000279 }
280 return false;
281}
282
283
Chris Lattner33c92e92005-09-08 21:27:15 +0000284//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000285// SDNodeInfo implementation
286//
287SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
288 EnumName = R->getValueAsString("Opcode");
289 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000290 Record *TypeProfile = R->getValueAsDef("TypeProfile");
291 NumResults = TypeProfile->getValueAsInt("NumResults");
292 NumOperands = TypeProfile->getValueAsInt("NumOperands");
293
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000294 // Parse the properties.
295 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000296 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000297 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
298 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000299 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000300 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000301 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000302 } else if (PropList[i]->getName() == "SDNPHasChain") {
303 Properties |= 1 << SDNPHasChain;
Evan Cheng51fecc82006-01-09 18:27:06 +0000304 } else if (PropList[i]->getName() == "SDNPOutFlag") {
305 Properties |= 1 << SDNPOutFlag;
306 } else if (PropList[i]->getName() == "SDNPInFlag") {
307 Properties |= 1 << SDNPInFlag;
308 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
309 Properties |= 1 << SDNPOptInFlag;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000310 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000311 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000312 << "' on node '" << R->getName() << "'!\n";
313 exit(1);
314 }
315 }
316
317
Chris Lattner33c92e92005-09-08 21:27:15 +0000318 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000319 std::vector<Record*> ConstraintList =
320 TypeProfile->getValueAsListOfDefs("Constraints");
321 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000322}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000323
324//===----------------------------------------------------------------------===//
325// TreePatternNode implementation
326//
327
328TreePatternNode::~TreePatternNode() {
329#if 0 // FIXME: implement refcounted tree nodes!
330 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
331 delete getChild(i);
332#endif
333}
334
Chris Lattner32707602005-09-08 23:22:48 +0000335/// UpdateNodeType - Set the node type of N to VT if VT contains
336/// information. If N already contains a conflicting type, then throw an
337/// exception. This returns true if any information was updated.
338///
Nate Begemanb73628b2005-12-30 00:12:56 +0000339bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
340 TreePattern &TP) {
341 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
342
343 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
344 return false;
345 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
346 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000347 return true;
348 }
Evan Cheng2618d072006-05-17 20:37:59 +0000349
350 if (getExtTypeNum(0) == MVT::iPTR) {
351 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
352 return false;
353 if (isExtIntegerInVTs(ExtVTs)) {
354 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
355 if (FVTs.size()) {
356 setTypes(ExtVTs);
357 return true;
358 }
359 }
360 }
Chris Lattner32707602005-09-08 23:22:48 +0000361
Nate Begemanb73628b2005-12-30 00:12:56 +0000362 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
363 assert(hasTypeSet() && "should be handled above!");
364 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
365 if (getExtTypes() == FVTs)
366 return false;
367 setTypes(FVTs);
368 return true;
369 }
Evan Cheng2618d072006-05-17 20:37:59 +0000370 if (ExtVTs[0] == MVT::iPTR && isExtIntegerInVTs(getExtTypes())) {
371 //assert(hasTypeSet() && "should be handled above!");
372 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
373 if (getExtTypes() == FVTs)
374 return false;
375 if (FVTs.size()) {
376 setTypes(FVTs);
377 return true;
378 }
379 }
Nate Begemanb73628b2005-12-30 00:12:56 +0000380 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
381 assert(hasTypeSet() && "should be handled above!");
Chris Lattner488580c2006-01-28 19:06:51 +0000382 std::vector<unsigned char> FVTs =
383 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
Nate Begemanb73628b2005-12-30 00:12:56 +0000384 if (getExtTypes() == FVTs)
385 return false;
386 setTypes(FVTs);
387 return true;
388 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000389
390 // If we know this is an int or fp type, and we are told it is a specific one,
391 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000392 //
393 // Similarly, we should probably set the type here to the intersection of
394 // {isInt|isFP} and ExtVTs
395 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
396 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
397 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000398 return true;
Evan Cheng2618d072006-05-17 20:37:59 +0000399 }
400 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
401 setTypes(ExtVTs);
402 return true;
403 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000404
Chris Lattner1531f202005-10-26 16:59:37 +0000405 if (isLeaf()) {
406 dump();
Evan Chengbcecf332005-12-17 01:19:28 +0000407 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000408 TP.error("Type inference contradiction found in node!");
409 } else {
410 TP.error("Type inference contradiction found in node " +
411 getOperator()->getName() + "!");
412 }
Chris Lattner32707602005-09-08 23:22:48 +0000413 return true; // unreachable
414}
415
416
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000417void TreePatternNode::print(std::ostream &OS) const {
418 if (isLeaf()) {
419 OS << *getLeafValue();
420 } else {
421 OS << "(" << getOperator()->getName();
422 }
423
Nate Begemanb73628b2005-12-30 00:12:56 +0000424 // FIXME: At some point we should handle printing all the value types for
425 // nodes that are multiply typed.
426 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000427 case MVT::Other: OS << ":Other"; break;
428 case MVT::isInt: OS << ":isInt"; break;
429 case MVT::isFP : OS << ":isFP"; break;
430 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Evan Cheng2618d072006-05-17 20:37:59 +0000431 case MVT::iPTR: OS << ":iPTR"; break;
Nate Begemanb73628b2005-12-30 00:12:56 +0000432 default: OS << ":" << getTypeNum(0); break;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000433 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000434
435 if (!isLeaf()) {
436 if (getNumChildren() != 0) {
437 OS << " ";
438 getChild(0)->print(OS);
439 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
440 OS << ", ";
441 getChild(i)->print(OS);
442 }
443 }
444 OS << ")";
445 }
446
447 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000448 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000449 if (TransformFn)
450 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000451 if (!getName().empty())
452 OS << ":$" << getName();
453
454}
455void TreePatternNode::dump() const {
456 print(std::cerr);
457}
458
Chris Lattnere46e17b2005-09-29 19:28:10 +0000459/// isIsomorphicTo - Return true if this node is recursively isomorphic to
460/// the specified node. For this comparison, all of the state of the node
461/// is considered, except for the assigned name. Nodes with differing names
462/// that are otherwise identical are considered isomorphic.
463bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
464 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000465 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000466 getPredicateFn() != N->getPredicateFn() ||
467 getTransformFn() != N->getTransformFn())
468 return false;
469
470 if (isLeaf()) {
471 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
472 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
473 return DI->getDef() == NDI->getDef();
474 return getLeafValue() == N->getLeafValue();
475 }
476
477 if (N->getOperator() != getOperator() ||
478 N->getNumChildren() != getNumChildren()) return false;
479 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
480 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
481 return false;
482 return true;
483}
484
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000485/// clone - Make a copy of this tree and all of its children.
486///
487TreePatternNode *TreePatternNode::clone() const {
488 TreePatternNode *New;
489 if (isLeaf()) {
490 New = new TreePatternNode(getLeafValue());
491 } else {
492 std::vector<TreePatternNode*> CChildren;
493 CChildren.reserve(Children.size());
494 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
495 CChildren.push_back(getChild(i)->clone());
496 New = new TreePatternNode(getOperator(), CChildren);
497 }
498 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000499 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000500 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000501 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000502 return New;
503}
504
Chris Lattner32707602005-09-08 23:22:48 +0000505/// SubstituteFormalArguments - Replace the formal arguments in this tree
506/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000507void TreePatternNode::
508SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
509 if (isLeaf()) return;
510
511 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
512 TreePatternNode *Child = getChild(i);
513 if (Child->isLeaf()) {
514 Init *Val = Child->getLeafValue();
515 if (dynamic_cast<DefInit*>(Val) &&
516 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
517 // We found a use of a formal argument, replace it with its value.
518 Child = ArgMap[Child->getName()];
519 assert(Child && "Couldn't find formal argument!");
520 setChild(i, Child);
521 }
522 } else {
523 getChild(i)->SubstituteFormalArguments(ArgMap);
524 }
525 }
526}
527
528
529/// InlinePatternFragments - If this pattern refers to any pattern
530/// fragments, inline them into place, giving us a pattern without any
531/// PatFrag references.
532TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
533 if (isLeaf()) return this; // nothing to do.
534 Record *Op = getOperator();
535
536 if (!Op->isSubClassOf("PatFrag")) {
537 // Just recursively inline children nodes.
538 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
539 setChild(i, getChild(i)->InlinePatternFragments(TP));
540 return this;
541 }
542
543 // Otherwise, we found a reference to a fragment. First, look up its
544 // TreePattern record.
545 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
546
547 // Verify that we are passing the right number of operands.
548 if (Frag->getNumArgs() != Children.size())
549 TP.error("'" + Op->getName() + "' fragment requires " +
550 utostr(Frag->getNumArgs()) + " operands!");
551
Chris Lattner37937092005-09-09 01:15:01 +0000552 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000553
554 // Resolve formal arguments to their actual value.
555 if (Frag->getNumArgs()) {
556 // Compute the map of formal to actual arguments.
557 std::map<std::string, TreePatternNode*> ArgMap;
558 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
559 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
560
561 FragTree->SubstituteFormalArguments(ArgMap);
562 }
563
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000564 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000565 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000566
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000567 // Get a new copy of this fragment to stitch into here.
568 //delete this; // FIXME: implement refcounting!
569 return FragTree;
570}
571
Chris Lattner52793e22006-04-06 20:19:52 +0000572/// getImplicitType - Check to see if the specified record has an implicit
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000573/// type which should be applied to it. This infer the type of register
574/// references from the register file information, for example.
575///
Chris Lattner52793e22006-04-06 20:19:52 +0000576static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000577 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000578 // Some common return values
579 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
580 std::vector<unsigned char> Other(1, MVT::Other);
581
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000582 // Check to see if this is a register or a register class...
583 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000584 if (NotRegisters)
585 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000586 const CodeGenRegisterClass &RC =
587 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000588 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000589 } else if (R->isSubClassOf("PatFrag")) {
590 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000591 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000592 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000593 if (NotRegisters)
594 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000595 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
Evan Cheng44a65fa2006-05-16 07:05:30 +0000596 return T.getRegisterVTs(R);
Chris Lattner1531f202005-10-26 16:59:37 +0000597 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
598 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000599 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000600 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000601 if (NotRegisters)
602 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000603 std::vector<unsigned char>
604 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
605 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000606 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000607 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000608 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000609 }
610
611 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000612 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000613}
614
Chris Lattner32707602005-09-08 23:22:48 +0000615/// ApplyTypeConstraints - Apply all of the type constraints relevent to
616/// this node and its children in the tree. This returns true if it makes a
617/// change, false otherwise. If a type contradiction is found, throw an
618/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000619bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000620 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000621 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000622 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000623 // If it's a regclass or something else known, include the type.
Chris Lattner52793e22006-04-06 20:19:52 +0000624 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000625 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
626 // Int inits are always integers. :)
627 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
628
629 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000630 // At some point, it may make sense for this tree pattern to have
631 // multiple types. Assert here that it does not, so we revisit this
632 // code when appropriate.
Evan Cheng2618d072006-05-17 20:37:59 +0000633 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Evan Cheng44a65fa2006-05-16 07:05:30 +0000634 MVT::ValueType VT = getTypeNum(0);
635 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
636 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000637
Evan Cheng2618d072006-05-17 20:37:59 +0000638 VT = getTypeNum(0);
639 if (VT != MVT::iPTR) {
640 unsigned Size = MVT::getSizeInBits(VT);
641 // Make sure that the value is representable for this type.
642 if (Size < 32) {
643 int Val = (II->getValue() << (32-Size)) >> (32-Size);
644 if (Val != II->getValue())
645 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
646 "' is out of range for type '" +
647 getEnumName(getTypeNum(0)) + "'!");
648 }
Chris Lattner465c7372005-11-03 05:46:11 +0000649 }
650 }
651
652 return MadeChange;
653 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000654 return false;
655 }
Chris Lattner32707602005-09-08 23:22:48 +0000656
657 // special handling for set, which isn't really an SDNode.
658 if (getOperator()->getName() == "set") {
659 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000660 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
661 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000662
663 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000664 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
665 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000666 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
667 return MadeChange;
Chris Lattner5a1df382006-03-24 23:10:39 +0000668 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
669 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
670 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
671 unsigned IID =
672 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
673 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
674 bool MadeChange = false;
675
676 // Apply the result type to the node.
677 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
678
679 if (getNumChildren() != Int.ArgVTs.size())
Chris Lattner2c4e65d2006-03-27 22:21:18 +0000680 TP.error("Intrinsic '" + Int.Name + "' expects " +
Chris Lattner5a1df382006-03-24 23:10:39 +0000681 utostr(Int.ArgVTs.size()-1) + " operands, not " +
682 utostr(getNumChildren()-1) + " operands!");
683
684 // Apply type info to the intrinsic ID.
Evan Cheng2618d072006-05-17 20:37:59 +0000685 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner5a1df382006-03-24 23:10:39 +0000686
687 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
688 MVT::ValueType OpVT = Int.ArgVTs[i];
689 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
690 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
691 }
692 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000693 } else if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000694 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
Chris Lattnerabbb6052005-09-15 21:42:00 +0000695
696 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
697 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000698 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000699 // Branch, etc. do not produce results and top-level forms in instr pattern
700 // must have void types.
701 if (NI.getNumResults() == 0)
702 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner91ded082006-04-06 20:36:51 +0000703
704 // If this is a vector_shuffle operation, apply types to the build_vector
705 // operation. The types of the integers don't matter, but this ensures they
706 // won't get checked.
707 if (getOperator()->getName() == "vector_shuffle" &&
708 getChild(2)->getOperator()->getName() == "build_vector") {
709 TreePatternNode *BV = getChild(2);
710 const std::vector<MVT::ValueType> &LegalVTs
711 = ISE.getTargetInfo().getLegalValueTypes();
712 MVT::ValueType LegalIntVT = MVT::Other;
713 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
714 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
715 LegalIntVT = LegalVTs[i];
716 break;
717 }
718 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
719
720 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
721 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
722 }
Chris Lattnerabbb6052005-09-15 21:42:00 +0000723 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000724 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000725 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000726 bool MadeChange = false;
727 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000728
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000729 assert(NumResults <= 1 &&
730 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000731 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000732 if (NumResults == 0) {
733 MadeChange = UpdateNodeType(MVT::isVoid, TP);
734 } else {
735 Record *ResultNode = Inst.getResult(0);
736 assert(ResultNode->isSubClassOf("RegisterClass") &&
737 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000738
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000739 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000740 ISE.getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000741 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000742 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000743
744 if (getNumChildren() != Inst.getNumOperands())
745 TP.error("Instruction '" + getOperator()->getName() + " expects " +
746 utostr(Inst.getNumOperands()) + " operands, not " +
747 utostr(getNumChildren()) + " operands!");
748 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000749 Record *OperandNode = Inst.getOperand(i);
750 MVT::ValueType VT;
751 if (OperandNode->isSubClassOf("RegisterClass")) {
752 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000753 ISE.getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000754 //VT = RC.getValueTypeNum(0);
755 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
756 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000757 } else if (OperandNode->isSubClassOf("Operand")) {
758 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000759 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000760 } else {
761 assert(0 && "Unknown operand type!");
762 abort();
763 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000764 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000765 }
766 return MadeChange;
767 } else {
768 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
769
Evan Chengf26ba692006-03-20 08:09:17 +0000770 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000771 if (getNumChildren() != 1)
772 TP.error("Node transform '" + getOperator()->getName() +
773 "' requires one operand!");
Chris Lattner4e2f54d2006-03-21 06:42:58 +0000774
775 // If either the output or input of the xform does not have exact
776 // type info. We assume they must be the same. Otherwise, it is perfectly
777 // legal to transform from one type to a completely different type.
778 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Evan Chengf26ba692006-03-20 08:09:17 +0000779 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
780 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
781 return MadeChange;
782 }
783 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000784 }
Chris Lattner32707602005-09-08 23:22:48 +0000785}
786
Chris Lattnere97603f2005-09-28 19:27:25 +0000787/// canPatternMatch - If it is impossible for this pattern to match on this
788/// target, fill in Reason and return false. Otherwise, return true. This is
789/// used as a santity check for .td files (to prevent people from writing stuff
790/// that can never possibly work), and to prevent the pattern permuter from
791/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000792bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000793 if (isLeaf()) return true;
794
795 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
796 if (!getChild(i)->canPatternMatch(Reason, ISE))
797 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000798
Chris Lattner550525e2006-03-24 21:48:51 +0000799 // If this is an intrinsic, handle cases that would make it not match. For
800 // example, if an operand is required to be an immediate.
801 if (getOperator()->isSubClassOf("Intrinsic")) {
802 // TODO:
803 return true;
804 }
805
Chris Lattnere97603f2005-09-28 19:27:25 +0000806 // If this node is a commutative operator, check that the LHS isn't an
807 // immediate.
808 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
809 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
810 // Scan all of the operands of the node and make sure that only the last one
811 // is a constant node.
812 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
813 if (!getChild(i)->isLeaf() &&
814 getChild(i)->getOperator()->getName() == "imm") {
815 Reason = "Immediate value must be on the RHS of commutative operators!";
816 return false;
817 }
818 }
819
820 return true;
821}
Chris Lattner32707602005-09-08 23:22:48 +0000822
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000823//===----------------------------------------------------------------------===//
824// TreePattern implementation
825//
826
Chris Lattneredbd8712005-10-21 01:19:59 +0000827TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000828 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000829 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000830 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
831 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000832}
833
Chris Lattneredbd8712005-10-21 01:19:59 +0000834TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000835 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000836 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000837 Trees.push_back(ParseTreePattern(Pat));
838}
839
Chris Lattneredbd8712005-10-21 01:19:59 +0000840TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000841 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000842 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000843 Trees.push_back(Pat);
844}
845
846
847
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000848void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000849 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000850 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000851}
852
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000853TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
Chris Lattner8c063182006-03-30 22:50:40 +0000854 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
855 if (!OpDef) error("Pattern has unexpected operator type!");
856 Record *Operator = OpDef->getDef();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000857
858 if (Operator->isSubClassOf("ValueType")) {
859 // If the operator is a ValueType, then this must be "type cast" of a leaf
860 // node.
861 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000862 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000863
864 Init *Arg = Dag->getArg(0);
865 TreePatternNode *New;
866 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000867 Record *R = DI->getDef();
868 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000869 Dag->setArg(0, new DagInit(DI,
Chris Lattner72fe91c2005-09-24 00:40:24 +0000870 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000871 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000872 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000873 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000874 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
875 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000876 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
877 New = new TreePatternNode(II);
878 if (!Dag->getArgName(0).empty())
879 error("Constant int argument should not have a name!");
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000880 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
881 // Turn this into an IntInit.
882 Init *II = BI->convertInitializerTo(new IntRecTy());
883 if (II == 0 || !dynamic_cast<IntInit*>(II))
884 error("Bits value must be constants!");
885
886 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
887 if (!Dag->getArgName(0).empty())
888 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000889 } else {
890 Arg->dump();
891 error("Unknown leaf value for tree pattern!");
892 return 0;
893 }
894
Chris Lattner32707602005-09-08 23:22:48 +0000895 // Apply the type cast.
896 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000897 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000898 return New;
899 }
900
901 // Verify that this is something that makes sense for an operator.
902 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000903 !Operator->isSubClassOf("Instruction") &&
904 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner550525e2006-03-24 21:48:51 +0000905 !Operator->isSubClassOf("Intrinsic") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000906 Operator->getName() != "set")
907 error("Unrecognized node '" + Operator->getName() + "'!");
908
Chris Lattneredbd8712005-10-21 01:19:59 +0000909 // Check to see if this is something that is illegal in an input pattern.
910 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
Chris Lattner5a1df382006-03-24 23:10:39 +0000911 Operator->isSubClassOf("SDNodeXForm")))
Chris Lattneredbd8712005-10-21 01:19:59 +0000912 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
913
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000914 std::vector<TreePatternNode*> Children;
915
916 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
917 Init *Arg = Dag->getArg(i);
918 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
919 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000920 if (Children.back()->getName().empty())
921 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000922 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
923 Record *R = DefI->getDef();
924 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
925 // TreePatternNode if its own.
926 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000927 Dag->setArg(i, new DagInit(DefI,
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000928 std::vector<std::pair<Init*, std::string> >()));
929 --i; // Revisit this node...
930 } else {
931 TreePatternNode *Node = new TreePatternNode(DefI);
932 Node->setName(Dag->getArgName(i));
933 Children.push_back(Node);
934
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000935 // Input argument?
936 if (R->getName() == "node") {
937 if (Dag->getArgName(i).empty())
938 error("'node' argument requires a name to match with operand list");
939 Args.push_back(Dag->getArgName(i));
940 }
941 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000942 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
943 TreePatternNode *Node = new TreePatternNode(II);
944 if (!Dag->getArgName(i).empty())
945 error("Constant int argument should not have a name!");
946 Children.push_back(Node);
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000947 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
948 // Turn this into an IntInit.
949 Init *II = BI->convertInitializerTo(new IntRecTy());
950 if (II == 0 || !dynamic_cast<IntInit*>(II))
951 error("Bits value must be constants!");
952
953 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
954 if (!Dag->getArgName(i).empty())
955 error("Constant int argument should not have a name!");
956 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000957 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000958 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000959 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000960 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000961 error("Unknown leaf value for tree pattern!");
962 }
963 }
964
Chris Lattner5a1df382006-03-24 23:10:39 +0000965 // If the operator is an intrinsic, then this is just syntactic sugar for for
966 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
967 // convert the intrinsic name to a number.
968 if (Operator->isSubClassOf("Intrinsic")) {
969 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
970 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
971
972 // If this intrinsic returns void, it must have side-effects and thus a
973 // chain.
974 if (Int.ArgVTs[0] == MVT::isVoid) {
975 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
976 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
977 // Has side-effects, requires chain.
978 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
979 } else {
980 // Otherwise, no chain.
981 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
982 }
983
984 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
985 Children.insert(Children.begin(), IIDNode);
986 }
987
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000988 return new TreePatternNode(Operator, Children);
989}
990
Chris Lattner32707602005-09-08 23:22:48 +0000991/// InferAllTypes - Infer/propagate as many types throughout the expression
992/// patterns as possible. Return true if all types are infered, false
993/// otherwise. Throw an exception if a type contradiction is found.
994bool TreePattern::InferAllTypes() {
995 bool MadeChange = true;
996 while (MadeChange) {
997 MadeChange = false;
998 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000999 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +00001000 }
1001
1002 bool HasUnresolvedTypes = false;
1003 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1004 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1005 return !HasUnresolvedTypes;
1006}
1007
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001008void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001009 OS << getRecord()->getName();
1010 if (!Args.empty()) {
1011 OS << "(" << Args[0];
1012 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1013 OS << ", " << Args[i];
1014 OS << ")";
1015 }
1016 OS << ": ";
1017
1018 if (Trees.size() > 1)
1019 OS << "[\n";
1020 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1021 OS << "\t";
1022 Trees[i]->print(OS);
1023 OS << "\n";
1024 }
1025
1026 if (Trees.size() > 1)
1027 OS << "]\n";
1028}
1029
1030void TreePattern::dump() const { print(std::cerr); }
1031
1032
1033
1034//===----------------------------------------------------------------------===//
1035// DAGISelEmitter implementation
1036//
1037
Chris Lattnerca559d02005-09-08 21:03:01 +00001038// Parse all of the SDNode definitions for the target, populating SDNodes.
1039void DAGISelEmitter::ParseNodeInfo() {
1040 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1041 while (!Nodes.empty()) {
1042 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1043 Nodes.pop_back();
1044 }
Chris Lattner5a1df382006-03-24 23:10:39 +00001045
1046 // Get the buildin intrinsic nodes.
1047 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1048 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1049 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
Chris Lattnerca559d02005-09-08 21:03:01 +00001050}
1051
Chris Lattner24eeeb82005-09-13 21:51:00 +00001052/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1053/// map, and emit them to the file as functions.
1054void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1055 OS << "\n// Node transformations.\n";
1056 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1057 while (!Xforms.empty()) {
1058 Record *XFormNode = Xforms.back();
1059 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1060 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1061 SDNodeXForms.insert(std::make_pair(XFormNode,
1062 std::make_pair(SDNode, Code)));
1063
Chris Lattner1048b7a2005-09-13 22:03:37 +00001064 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +00001065 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1066 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1067
Chris Lattner1048b7a2005-09-13 22:03:37 +00001068 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +00001069 << "(SDNode *" << C2 << ") {\n";
1070 if (ClassName != "SDNode")
1071 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1072 OS << Code << "\n}\n";
1073 }
1074
1075 Xforms.pop_back();
1076 }
1077}
1078
Evan Cheng0fc71982005-12-08 02:00:36 +00001079void DAGISelEmitter::ParseComplexPatterns() {
1080 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1081 while (!AMs.empty()) {
1082 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1083 AMs.pop_back();
1084 }
1085}
Chris Lattner24eeeb82005-09-13 21:51:00 +00001086
1087
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001088/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1089/// file, building up the PatternFragments map. After we've collected them all,
1090/// inline fragments together as necessary, so that there are no references left
1091/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001092///
1093/// This also emits all of the predicate functions to the output file.
1094///
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001095void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001096 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1097
1098 // First step, parse all of the fragments and emit predicate functions.
1099 OS << "\n// Predicate functions.\n";
1100 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001101 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +00001102 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001103 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +00001104
1105 // Validate the argument list, converting it to map, to discard duplicates.
1106 std::vector<std::string> &Args = P->getArgList();
1107 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1108
1109 if (OperandsMap.count(""))
1110 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1111
1112 // Parse the operands list.
1113 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Chris Lattner8c063182006-03-30 22:50:40 +00001114 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1115 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
Chris Lattneree9f0c32005-09-13 21:20:49 +00001116 P->error("Operands list should start with '(ops ... '!");
1117
1118 // Copy over the arguments.
1119 Args.clear();
1120 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1121 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1122 static_cast<DefInit*>(OpsList->getArg(j))->
1123 getDef()->getName() != "node")
1124 P->error("Operands list should all be 'node' values.");
1125 if (OpsList->getArgName(j).empty())
1126 P->error("Operands list should have names for each operand!");
1127 if (!OperandsMap.count(OpsList->getArgName(j)))
1128 P->error("'" + OpsList->getArgName(j) +
1129 "' does not occur in pattern or was multiply specified!");
1130 OperandsMap.erase(OpsList->getArgName(j));
1131 Args.push_back(OpsList->getArgName(j));
1132 }
1133
1134 if (!OperandsMap.empty())
1135 P->error("Operands list does not contain an entry for operand '" +
1136 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001137
1138 // If there is a code init for this fragment, emit the predicate code and
1139 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001140 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1141 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +00001142 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001143 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +00001144 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001145 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1146
Chris Lattner1048b7a2005-09-13 22:03:37 +00001147 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001148 << "(SDNode *" << C2 << ") {\n";
1149 if (ClassName != "SDNode")
1150 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +00001151 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001152 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001153 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001154
1155 // If there is a node transformation corresponding to this, keep track of
1156 // it.
1157 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1158 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001159 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001160 }
1161
1162 OS << "\n\n";
1163
1164 // Now that we've parsed all of the tree fragments, do a closure on them so
1165 // that there are not references to PatFrags left inside of them.
1166 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1167 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001168 TreePattern *ThePat = I->second;
1169 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001170
Chris Lattner32707602005-09-08 23:22:48 +00001171 // Infer as many types as possible. Don't worry about it if we don't infer
1172 // all of them, some may depend on the inputs of the pattern.
1173 try {
1174 ThePat->InferAllTypes();
1175 } catch (...) {
1176 // If this pattern fragment is not supported by this target (no types can
1177 // satisfy its constraints), just ignore it. If the bogus pattern is
1178 // actually used by instructions, the type consistency error will be
1179 // reported there.
1180 }
1181
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001182 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001183 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001184 }
1185}
1186
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001187/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001188/// instruction input. Return true if this is a real use.
1189static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001190 std::map<std::string, TreePatternNode*> &InstInputs,
1191 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001192 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001193 if (Pat->getName().empty()) {
1194 if (Pat->isLeaf()) {
1195 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1196 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1197 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001198 else if (DI && DI->getDef()->isSubClassOf("Register"))
1199 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001200 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001201 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001202 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001203
1204 Record *Rec;
1205 if (Pat->isLeaf()) {
1206 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1207 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1208 Rec = DI->getDef();
1209 } else {
1210 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1211 Rec = Pat->getOperator();
1212 }
1213
Evan Cheng01f318b2005-12-14 02:21:57 +00001214 // SRCVALUE nodes are ignored.
1215 if (Rec->getName() == "srcvalue")
1216 return false;
1217
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001218 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1219 if (!Slot) {
1220 Slot = Pat;
1221 } else {
1222 Record *SlotRec;
1223 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001224 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001225 } else {
1226 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1227 SlotRec = Slot->getOperator();
1228 }
1229
1230 // Ensure that the inputs agree if we've already seen this input.
1231 if (Rec != SlotRec)
1232 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001233 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001234 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1235 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001236 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001237}
1238
1239/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1240/// part of "I", the instruction), computing the set of inputs and outputs of
1241/// the pattern. Report errors if we see anything naughty.
1242void DAGISelEmitter::
1243FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1244 std::map<std::string, TreePatternNode*> &InstInputs,
Chris Lattner947604b2006-03-24 21:52:20 +00001245 std::map<std::string, TreePatternNode*>&InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001246 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001247 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001248 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001249 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001250 if (!isUse && Pat->getTransformFn())
1251 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001252 return;
1253 } else if (Pat->getOperator()->getName() != "set") {
1254 // If this is not a set, verify that the children nodes are not void typed,
1255 // and recurse.
1256 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001257 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001258 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001259 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001260 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001261 }
1262
1263 // If this is a non-leaf node with no children, treat it basically as if
1264 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001265 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001266 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001267 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001268
Chris Lattnerf1311842005-09-14 23:05:13 +00001269 if (!isUse && Pat->getTransformFn())
1270 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001271 return;
1272 }
1273
1274 // Otherwise, this is a set, validate and collect instruction results.
1275 if (Pat->getNumChildren() == 0)
1276 I->error("set requires operands!");
1277 else if (Pat->getNumChildren() & 1)
1278 I->error("set requires an even number of operands");
1279
Chris Lattnerf1311842005-09-14 23:05:13 +00001280 if (Pat->getTransformFn())
1281 I->error("Cannot specify a transform function on a set node!");
1282
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001283 // Check the set destinations.
1284 unsigned NumValues = Pat->getNumChildren()/2;
1285 for (unsigned i = 0; i != NumValues; ++i) {
1286 TreePatternNode *Dest = Pat->getChild(i);
1287 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001288 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001289
1290 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1291 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001292 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001293
Evan Chengbcecf332005-12-17 01:19:28 +00001294 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1295 if (Dest->getName().empty())
1296 I->error("set destination must have a name!");
1297 if (InstResults.count(Dest->getName()))
1298 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001299 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001300 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001301 InstImpResults.push_back(Val->getDef());
1302 } else {
1303 I->error("set destination should be a register!");
1304 }
1305
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001306 // Verify and collect info from the computation.
1307 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001308 InstInputs, InstResults,
1309 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001310 }
1311}
1312
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001313/// ParseInstructions - Parse all of the instructions, inlining and resolving
1314/// any fragments involved. This populates the Instructions list with fully
1315/// resolved instructions.
1316void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001317 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1318
1319 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001320 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001321
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001322 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1323 LI = Instrs[i]->getValueAsListInit("Pattern");
1324
1325 // If there is no pattern, only collect minimal information about the
1326 // instruction for its operand list. We have to assume that there is one
1327 // result, as we have no detailed info.
1328 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001329 std::vector<Record*> Results;
1330 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001331
1332 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001333
Evan Cheng3a217f32005-12-22 02:35:21 +00001334 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001335 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001336 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001337 // These produce no results
1338 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1339 Operands.push_back(InstInfo.OperandList[j].Rec);
1340 } else {
1341 // Assume the first operand is the result.
1342 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001343
Evan Cheng3a217f32005-12-22 02:35:21 +00001344 // The rest are inputs.
1345 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1346 Operands.push_back(InstInfo.OperandList[j].Rec);
1347 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001348 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001349
1350 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001351 std::vector<Record*> ImpResults;
1352 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001353 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001354 DAGInstruction(0, Results, Operands, ImpResults,
1355 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001356 continue; // no pattern.
1357 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001358
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001359 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001360 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001361 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001362 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001363
Chris Lattner95f6b762005-09-08 23:26:30 +00001364 // Infer as many types as possible. If we cannot infer all of them, we can
1365 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001366 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001367 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001368
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001369 // InstInputs - Keep track of all of the inputs of the instruction, along
1370 // with the record they are declared as.
1371 std::map<std::string, TreePatternNode*> InstInputs;
1372
1373 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001374 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001375 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001376
1377 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001378 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001379
Chris Lattner1f39e292005-09-14 00:09:24 +00001380 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001381 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001382 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1383 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001384 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001385 I->error("Top-level forms in instruction pattern should have"
1386 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001387
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001388 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001389 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001390 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001391 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001392
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001393 // Now that we have inputs and outputs of the pattern, inspect the operands
1394 // list for the instruction. This determines the order that operands are
1395 // added to the machine instruction the node corresponds to.
1396 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001397
1398 // Parse the operands list from the (ops) list, validating it.
1399 std::vector<std::string> &Args = I->getArgList();
1400 assert(Args.empty() && "Args list should still be empty here!");
1401 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1402
1403 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001404 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001405 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001406 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001407 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001408 I->error("'" + InstResults.begin()->first +
1409 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001410 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001411
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001412 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001413 TreePatternNode *RNode = InstResults[OpName];
Chris Lattner5c4c7742006-03-25 22:12:44 +00001414 if (RNode == 0)
1415 I->error("Operand $" + OpName + " does not exist in operand list!");
1416
Evan Cheng420132e2006-03-20 06:04:09 +00001417 if (i == 0)
1418 Res0Node = RNode;
1419 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001420 if (R == 0)
1421 I->error("Operand $" + OpName + " should be a set destination: all "
1422 "outputs must occur before inputs in operand list!");
1423
1424 if (CGI.OperandList[i].Rec != R)
1425 I->error("Operand $" + OpName + " class mismatch!");
1426
Chris Lattnerae6d8282005-09-15 21:51:12 +00001427 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001428 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001429
Chris Lattner39e8af92005-09-14 18:19:25 +00001430 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001431 InstResults.erase(OpName);
1432 }
1433
Chris Lattner0b592252005-09-14 21:59:34 +00001434 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1435 // the copy while we're checking the inputs.
1436 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001437
1438 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001439 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001440 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1441 const std::string &OpName = CGI.OperandList[i].Name;
1442 if (OpName.empty())
1443 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1444
Chris Lattner0b592252005-09-14 21:59:34 +00001445 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001446 I->error("Operand $" + OpName +
1447 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001448 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001449 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001450
1451 if (InVal->isLeaf() &&
1452 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1453 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001454 if (CGI.OperandList[i].Rec != InRec &&
1455 !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001456 I->error("Operand $" + OpName + "'s register class disagrees"
1457 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001458 }
1459 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001460
Chris Lattner2175c182005-09-14 23:01:59 +00001461 // Construct the result for the dest-pattern operand list.
1462 TreePatternNode *OpNode = InVal->clone();
1463
1464 // No predicate is useful on the result.
1465 OpNode->setPredicateFn("");
1466
1467 // Promote the xform function to be an explicit node if set.
1468 if (Record *Xform = OpNode->getTransformFn()) {
1469 OpNode->setTransformFn(0);
1470 std::vector<TreePatternNode*> Children;
1471 Children.push_back(OpNode);
1472 OpNode = new TreePatternNode(Xform, Children);
1473 }
1474
1475 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001476 }
1477
Chris Lattner0b592252005-09-14 21:59:34 +00001478 if (!InstInputsCheck.empty())
1479 I->error("Input operand $" + InstInputsCheck.begin()->first +
1480 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001481
1482 TreePatternNode *ResultPattern =
1483 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001484 // Copy fully inferred output node type to instruction result pattern.
1485 if (NumResults > 0)
1486 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001487
1488 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001489 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001490 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1491
1492 // Use a temporary tree pattern to infer all types and make sure that the
1493 // constructed result is correct. This depends on the instruction already
1494 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001495 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001496 Temp.InferAllTypes();
1497
1498 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1499 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001500
Chris Lattner32707602005-09-08 23:22:48 +00001501 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001502 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001503
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001504 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001505 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1506 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001507 DAGInstruction &TheInst = II->second;
1508 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001509 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001510
Chris Lattner1f39e292005-09-14 00:09:24 +00001511 if (I->getNumTrees() != 1) {
1512 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1513 continue;
1514 }
1515 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001516 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001517 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001518 if (Pattern->getNumChildren() != 2)
1519 continue; // Not a set of a single value (not handled so far)
1520
1521 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001522 } else{
1523 // Not a set (store or something?)
1524 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001525 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001526
1527 std::string Reason;
1528 if (!SrcPattern->canPatternMatch(Reason, *this))
1529 I->error("Instruction can never match: " + Reason);
1530
Evan Cheng58e84a62005-12-14 22:02:59 +00001531 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001532 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001533 PatternsToMatch.
1534 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
Evan Cheng59413202006-04-19 18:07:24 +00001535 SrcPattern, DstPattern,
Evan Chengc81d2a02006-04-19 20:36:09 +00001536 Instr->getValueAsInt("AddedComplexity")));
Chris Lattner1f39e292005-09-14 00:09:24 +00001537 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001538}
1539
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001540void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001541 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001542
Chris Lattnerabbb6052005-09-15 21:42:00 +00001543 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001544 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001545 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001546
Chris Lattnerabbb6052005-09-15 21:42:00 +00001547 // Inline pattern fragments into it.
1548 Pattern->InlinePatternFragments();
1549
1550 // Infer as many types as possible. If we cannot infer all of them, we can
1551 // never do anything with this pattern: report it to the user.
1552 if (!Pattern->InferAllTypes())
1553 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001554
1555 // Validate that the input pattern is correct.
1556 {
1557 std::map<std::string, TreePatternNode*> InstInputs;
Evan Cheng420132e2006-03-20 06:04:09 +00001558 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001559 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001560 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001561 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001562 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001563 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001564 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001565
1566 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1567 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001568
1569 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001570 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001571
1572 // Inline pattern fragments into it.
1573 Result->InlinePatternFragments();
1574
1575 // Infer as many types as possible. If we cannot infer all of them, we can
1576 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001577 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001578 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001579
1580 if (Result->getNumTrees() != 1)
1581 Result->error("Cannot handle instructions producing instructions "
1582 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001583
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001584 // Promote the xform function to be an explicit node if set.
1585 std::vector<TreePatternNode*> ResultNodeOperands;
1586 TreePatternNode *DstPattern = Result->getOnlyTree();
1587 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1588 TreePatternNode *OpNode = DstPattern->getChild(ii);
1589 if (Record *Xform = OpNode->getTransformFn()) {
1590 OpNode->setTransformFn(0);
1591 std::vector<TreePatternNode*> Children;
1592 Children.push_back(OpNode);
1593 OpNode = new TreePatternNode(Xform, Children);
1594 }
1595 ResultNodeOperands.push_back(OpNode);
1596 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00001597 DstPattern = Result->getOnlyTree();
1598 if (!DstPattern->isLeaf())
1599 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1600 ResultNodeOperands);
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001601 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1602 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1603 Temp.InferAllTypes();
1604
Chris Lattnere97603f2005-09-28 19:27:25 +00001605 std::string Reason;
1606 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1607 Pattern->error("Pattern can never match: " + Reason);
1608
Evan Cheng58e84a62005-12-14 22:02:59 +00001609 PatternsToMatch.
1610 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1611 Pattern->getOnlyTree(),
Evan Cheng59413202006-04-19 18:07:24 +00001612 Temp.getOnlyTree(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001613 Patterns[i]->getValueAsInt("AddedComplexity")));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001614 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001615}
1616
Chris Lattnere46e17b2005-09-29 19:28:10 +00001617/// CombineChildVariants - Given a bunch of permutations of each child of the
1618/// 'operator' node, put them together in all possible ways.
1619static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001620 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001621 std::vector<TreePatternNode*> &OutVariants,
1622 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001623 // Make sure that each operand has at least one variant to choose from.
1624 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1625 if (ChildVariants[i].empty())
1626 return;
1627
Chris Lattnere46e17b2005-09-29 19:28:10 +00001628 // The end result is an all-pairs construction of the resultant pattern.
1629 std::vector<unsigned> Idxs;
1630 Idxs.resize(ChildVariants.size());
1631 bool NotDone = true;
1632 while (NotDone) {
1633 // Create the variant and add it to the output list.
1634 std::vector<TreePatternNode*> NewChildren;
1635 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1636 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1637 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1638
1639 // Copy over properties.
1640 R->setName(Orig->getName());
1641 R->setPredicateFn(Orig->getPredicateFn());
1642 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001643 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001644
1645 // If this pattern cannot every match, do not include it as a variant.
1646 std::string ErrString;
1647 if (!R->canPatternMatch(ErrString, ISE)) {
1648 delete R;
1649 } else {
1650 bool AlreadyExists = false;
1651
1652 // Scan to see if this pattern has already been emitted. We can get
1653 // duplication due to things like commuting:
1654 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1655 // which are the same pattern. Ignore the dups.
1656 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1657 if (R->isIsomorphicTo(OutVariants[i])) {
1658 AlreadyExists = true;
1659 break;
1660 }
1661
1662 if (AlreadyExists)
1663 delete R;
1664 else
1665 OutVariants.push_back(R);
1666 }
1667
1668 // Increment indices to the next permutation.
1669 NotDone = false;
1670 // Look for something we can increment without causing a wrap-around.
1671 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1672 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1673 NotDone = true; // Found something to increment.
1674 break;
1675 }
1676 Idxs[IdxsIdx] = 0;
1677 }
1678 }
1679}
1680
Chris Lattneraf302912005-09-29 22:36:54 +00001681/// CombineChildVariants - A helper function for binary operators.
1682///
1683static void CombineChildVariants(TreePatternNode *Orig,
1684 const std::vector<TreePatternNode*> &LHS,
1685 const std::vector<TreePatternNode*> &RHS,
1686 std::vector<TreePatternNode*> &OutVariants,
1687 DAGISelEmitter &ISE) {
1688 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1689 ChildVariants.push_back(LHS);
1690 ChildVariants.push_back(RHS);
1691 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1692}
1693
1694
1695static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1696 std::vector<TreePatternNode *> &Children) {
1697 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1698 Record *Operator = N->getOperator();
1699
1700 // Only permit raw nodes.
1701 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1702 N->getTransformFn()) {
1703 Children.push_back(N);
1704 return;
1705 }
1706
1707 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1708 Children.push_back(N->getChild(0));
1709 else
1710 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1711
1712 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1713 Children.push_back(N->getChild(1));
1714 else
1715 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1716}
1717
Chris Lattnere46e17b2005-09-29 19:28:10 +00001718/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1719/// the (potentially recursive) pattern by using algebraic laws.
1720///
1721static void GenerateVariantsOf(TreePatternNode *N,
1722 std::vector<TreePatternNode*> &OutVariants,
1723 DAGISelEmitter &ISE) {
1724 // We cannot permute leaves.
1725 if (N->isLeaf()) {
1726 OutVariants.push_back(N);
1727 return;
1728 }
1729
1730 // Look up interesting info about the node.
Chris Lattner5a1df382006-03-24 23:10:39 +00001731 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001732
1733 // If this node is associative, reassociate.
Chris Lattner5a1df382006-03-24 23:10:39 +00001734 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
Chris Lattneraf302912005-09-29 22:36:54 +00001735 // Reassociate by pulling together all of the linked operators
1736 std::vector<TreePatternNode*> MaximalChildren;
1737 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1738
1739 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1740 // permutations.
1741 if (MaximalChildren.size() == 3) {
1742 // Find the variants of all of our maximal children.
1743 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1744 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1745 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1746 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1747
1748 // There are only two ways we can permute the tree:
1749 // (A op B) op C and A op (B op C)
1750 // Within these forms, we can also permute A/B/C.
1751
1752 // Generate legal pair permutations of A/B/C.
1753 std::vector<TreePatternNode*> ABVariants;
1754 std::vector<TreePatternNode*> BAVariants;
1755 std::vector<TreePatternNode*> ACVariants;
1756 std::vector<TreePatternNode*> CAVariants;
1757 std::vector<TreePatternNode*> BCVariants;
1758 std::vector<TreePatternNode*> CBVariants;
1759 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1760 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1761 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1762 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1763 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1764 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1765
1766 // Combine those into the result: (x op x) op x
1767 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1768 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1769 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1770 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1771 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1772 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1773
1774 // Combine those into the result: x op (x op x)
1775 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1776 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1777 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1778 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1779 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1780 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1781 return;
1782 }
1783 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001784
1785 // Compute permutations of all children.
1786 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1787 ChildVariants.resize(N->getNumChildren());
1788 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1789 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1790
1791 // Build all permutations based on how the children were formed.
1792 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1793
1794 // If this node is commutative, consider the commuted order.
Chris Lattner5a1df382006-03-24 23:10:39 +00001795 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001796 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001797 // Consider the commuted order.
1798 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1799 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001800 }
1801}
1802
1803
Chris Lattnere97603f2005-09-28 19:27:25 +00001804// GenerateVariants - Generate variants. For example, commutative patterns can
1805// match multiple ways. Add them to PatternsToMatch as well.
1806void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001807
1808 DEBUG(std::cerr << "Generating instruction variants.\n");
1809
1810 // Loop over all of the patterns we've collected, checking to see if we can
1811 // generate variants of the instruction, through the exploitation of
1812 // identities. This permits the target to provide agressive matching without
1813 // the .td file having to contain tons of variants of instructions.
1814 //
1815 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1816 // intentionally do not reconsider these. Any variants of added patterns have
1817 // already been added.
1818 //
1819 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1820 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001821 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001822
1823 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001824 Variants.erase(Variants.begin()); // Remove the original pattern.
1825
1826 if (Variants.empty()) // No variants for this pattern.
1827 continue;
1828
1829 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001830 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001831 std::cerr << "\n");
1832
1833 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1834 TreePatternNode *Variant = Variants[v];
1835
1836 DEBUG(std::cerr << " VAR#" << v << ": ";
1837 Variant->dump();
1838 std::cerr << "\n");
1839
1840 // Scan to see if an instruction or explicit pattern already matches this.
1841 bool AlreadyExists = false;
1842 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1843 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001844 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001845 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1846 AlreadyExists = true;
1847 break;
1848 }
1849 }
1850 // If we already have it, ignore the variant.
1851 if (AlreadyExists) continue;
1852
1853 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001854 PatternsToMatch.
1855 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
Evan Cheng59413202006-04-19 18:07:24 +00001856 Variant, PatternsToMatch[i].getDstPattern(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001857 PatternsToMatch[i].getAddedComplexity()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001858 }
1859
1860 DEBUG(std::cerr << "\n");
1861 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001862}
1863
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001864
Evan Cheng0fc71982005-12-08 02:00:36 +00001865// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1866// ComplexPattern.
1867static bool NodeIsComplexPattern(TreePatternNode *N)
1868{
1869 return (N->isLeaf() &&
1870 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1871 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1872 isSubClassOf("ComplexPattern"));
1873}
1874
1875// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1876// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1877static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1878 DAGISelEmitter &ISE)
1879{
1880 if (N->isLeaf() &&
1881 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1882 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1883 isSubClassOf("ComplexPattern")) {
1884 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1885 ->getDef());
1886 }
1887 return NULL;
1888}
1889
Chris Lattner05814af2005-09-28 17:57:56 +00001890/// getPatternSize - Return the 'size' of this pattern. We want to match large
1891/// patterns before small ones. This is used to determine the size of a
1892/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001893static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng2618d072006-05-17 20:37:59 +00001894 assert((isExtIntegerInVTs(P->getExtTypes()) ||
1895 isExtFloatingPointInVTs(P->getExtTypes()) ||
1896 P->getExtTypeNum(0) == MVT::isVoid ||
1897 P->getExtTypeNum(0) == MVT::Flag ||
1898 P->getExtTypeNum(0) == MVT::iPTR) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +00001899 "Not a valid pattern node to size!");
Evan Chenge1050d62006-01-06 02:30:23 +00001900 unsigned Size = 2; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00001901 // If the root node is a ConstantSDNode, increases its size.
1902 // e.g. (set R32:$dst, 0).
1903 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1904 Size++;
Evan Cheng0fc71982005-12-08 02:00:36 +00001905
1906 // FIXME: This is a hack to statically increase the priority of patterns
1907 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1908 // Later we can allow complexity / cost for each pattern to be (optionally)
1909 // specified. To get best possible pattern match we'll need to dynamically
1910 // calculate the complexity of all patterns a dag can potentially map to.
1911 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1912 if (AM)
Evan Cheng4a7c2842006-01-06 22:19:44 +00001913 Size += AM->getNumOperands() * 2;
Chris Lattner3e179802006-02-03 18:06:02 +00001914
1915 // If this node has some predicate function that must match, it adds to the
1916 // complexity of this node.
1917 if (!P->getPredicateFn().empty())
1918 ++Size;
1919
Chris Lattner05814af2005-09-28 17:57:56 +00001920 // Count children in the count if they are also nodes.
1921 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1922 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001923 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001924 Size += getPatternSize(Child, ISE);
1925 else if (Child->isLeaf()) {
1926 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner3e179802006-02-03 18:06:02 +00001927 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
Evan Cheng4a7c2842006-01-06 22:19:44 +00001928 else if (NodeIsComplexPattern(Child))
1929 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00001930 else if (!Child->getPredicateFn().empty())
1931 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001932 }
Chris Lattner05814af2005-09-28 17:57:56 +00001933 }
1934
1935 return Size;
1936}
1937
1938/// getResultPatternCost - Compute the number of instructions for this pattern.
1939/// This is a temporary hack. We should really include the instruction
1940/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00001941static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00001942 if (P->isLeaf()) return 0;
1943
Evan Chengfbad7082006-02-18 02:33:09 +00001944 unsigned Cost = 0;
1945 Record *Op = P->getOperator();
1946 if (Op->isSubClassOf("Instruction")) {
1947 Cost++;
1948 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1949 if (II.usesCustomDAGSchedInserter)
1950 Cost += 10;
1951 }
Chris Lattner05814af2005-09-28 17:57:56 +00001952 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00001953 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001954 return Cost;
1955}
1956
1957// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1958// In particular, we want to match maximal patterns first and lowest cost within
1959// a particular complexity first.
1960struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001961 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1962 DAGISelEmitter &ISE;
1963
Evan Cheng58e84a62005-12-14 22:02:59 +00001964 bool operator()(PatternToMatch *LHS,
1965 PatternToMatch *RHS) {
1966 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1967 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Evan Chengc81d2a02006-04-19 20:36:09 +00001968 LHSSize += LHS->getAddedComplexity();
1969 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +00001970 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1971 if (LHSSize < RHSSize) return false;
1972
1973 // If the patterns have equal complexity, compare generated instruction cost
Evan Chengfbad7082006-02-18 02:33:09 +00001974 return getResultPatternCost(LHS->getDstPattern(), ISE) <
1975 getResultPatternCost(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001976 }
1977};
1978
Nate Begeman6510b222005-12-01 04:51:06 +00001979/// getRegisterValueType - Look up and return the first ValueType of specified
1980/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001981static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001982 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1983 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001984 return MVT::Other;
1985}
1986
Chris Lattner72fe91c2005-09-24 00:40:24 +00001987
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001988/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1989/// type information from it.
1990static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001991 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001992 if (!N->isLeaf())
1993 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1994 RemoveAllTypes(N->getChild(i));
1995}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001996
Chris Lattner0614b622005-11-02 06:49:14 +00001997Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1998 Record *N = Records.getDef(Name);
Chris Lattner5a1df382006-03-24 23:10:39 +00001999 if (!N || !N->isSubClassOf("SDNode")) {
2000 std::cerr << "Error getting SDNode '" << Name << "'!\n";
2001 exit(1);
2002 }
Chris Lattner0614b622005-11-02 06:49:14 +00002003 return N;
2004}
2005
Evan Cheng51fecc82006-01-09 18:27:06 +00002006/// NodeHasProperty - return true if TreePatternNode has the specified
2007/// property.
2008static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2009 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002010{
2011 if (N->isLeaf()) return false;
2012 Record *Operator = N->getOperator();
2013 if (!Operator->isSubClassOf("SDNode")) return false;
2014
2015 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00002016 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002017}
2018
Evan Cheng51fecc82006-01-09 18:27:06 +00002019static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
2020 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00002021{
Evan Cheng51fecc82006-01-09 18:27:06 +00002022 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00002023 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00002024
2025 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2026 TreePatternNode *Child = N->getChild(i);
2027 if (PatternHasProperty(Child, Property, ISE))
2028 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002029 }
2030
2031 return false;
2032}
2033
Evan Chengb915f312005-12-09 22:45:35 +00002034class PatternCodeEmitter {
2035private:
2036 DAGISelEmitter &ISE;
2037
Evan Cheng58e84a62005-12-14 22:02:59 +00002038 // Predicates.
2039 ListInit *Predicates;
Evan Cheng59413202006-04-19 18:07:24 +00002040 // Pattern cost.
2041 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +00002042 // Instruction selector pattern.
2043 TreePatternNode *Pattern;
2044 // Matched instruction.
2045 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002046
Evan Chengb915f312005-12-09 22:45:35 +00002047 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00002048 std::map<std::string, std::string> VariableMap;
2049 // Node to operator mapping
2050 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00002051 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002052 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00002053 std::set<std::string> Duplicates;
Evan Cheng61a02092006-04-28 02:08:10 +00002054 /// These nodes are being marked "in-flight" so they cannot be folded.
2055 std::vector<std::string> InflightNodes;
Evan Chengb915f312005-12-09 22:45:35 +00002056
Chris Lattner8a0604b2006-01-28 20:31:24 +00002057 /// GeneratedCode - This is the buffer that we emit code to. The first bool
2058 /// indicates whether this is an exit predicate (something that should be
2059 /// tested, and if true, the match fails) [when true] or normal code to emit
2060 /// [when false].
2061 std::vector<std::pair<bool, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002062 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2063 /// the set of patterns for each top-level opcode.
Evan Chengd7805a72006-02-09 07:16:09 +00002064 std::set<std::pair<bool, std::string> > &GeneratedDecl;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002065
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002066 std::string ChainName;
Evan Chenged66e852006-03-09 08:19:11 +00002067 bool NewTF;
Evan Chenge41bf822006-02-05 06:43:12 +00002068 bool DoReplace;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002069 unsigned TmpNo;
2070
2071 void emitCheck(const std::string &S) {
2072 if (!S.empty())
2073 GeneratedCode.push_back(std::make_pair(true, S));
2074 }
2075 void emitCode(const std::string &S) {
2076 if (!S.empty())
2077 GeneratedCode.push_back(std::make_pair(false, S));
2078 }
Evan Chengd7805a72006-02-09 07:16:09 +00002079 void emitDecl(const std::string &S, bool isSDNode=false) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002080 assert(!S.empty() && "Invalid declaration");
Evan Chengd7805a72006-02-09 07:16:09 +00002081 GeneratedDecl.insert(std::make_pair(isSDNode, S));
Evan Cheng21ad3922006-02-07 00:37:41 +00002082 }
Evan Chengb915f312005-12-09 22:45:35 +00002083public:
Evan Cheng58e84a62005-12-14 22:02:59 +00002084 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2085 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng21ad3922006-02-07 00:37:41 +00002086 std::vector<std::pair<bool, std::string> > &gc,
Evan Chengd7805a72006-02-09 07:16:09 +00002087 std::set<std::pair<bool, std::string> > &gd,
Evan Cheng21ad3922006-02-07 00:37:41 +00002088 bool dorep)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002089 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Chenged66e852006-03-09 08:19:11 +00002090 GeneratedCode(gc), GeneratedDecl(gd),
2091 NewTF(false), DoReplace(dorep), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00002092
2093 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2094 /// if the match fails. At this point, we already know that the opcode for N
2095 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00002096 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2097 const std::string &RootName, const std::string &ParentName,
2098 const std::string &ChainSuffix, bool &FoundChain) {
2099 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00002100 // Emit instruction predicates. Each predicate is just a string for now.
2101 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002102 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00002103 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2104 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2105 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002106 if (!Def->isSubClassOf("Predicate")) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002107 Def->dump();
2108 assert(0 && "Unknown predicate type!");
2109 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002110 if (!PredicateCheck.empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002111 PredicateCheck += " || ";
2112 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00002113 }
2114 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002115
2116 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00002117 }
2118
Evan Chengb915f312005-12-09 22:45:35 +00002119 if (N->isLeaf()) {
2120 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002121 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00002122 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002123 return;
2124 } else if (!NodeIsComplexPattern(N)) {
2125 assert(0 && "Cannot match this as a leaf value!");
2126 abort();
2127 }
2128 }
2129
Chris Lattner488580c2006-01-28 19:06:51 +00002130 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002131 // we already saw this in the pattern, emit code to verify dagness.
2132 if (!N->getName().empty()) {
2133 std::string &VarMapEntry = VariableMap[N->getName()];
2134 if (VarMapEntry.empty()) {
2135 VarMapEntry = RootName;
2136 } else {
2137 // If we get here, this is a second reference to a specific name. Since
2138 // we already have checked that the first reference is valid, we don't
2139 // have to recursively match it, just check that it's the same as the
2140 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002141 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00002142 return;
2143 }
Evan Chengf805c2e2006-01-12 19:35:54 +00002144
2145 if (!N->isLeaf())
2146 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00002147 }
2148
2149
2150 // Emit code to load the child nodes and match their contents recursively.
2151 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00002152 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2153 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2154 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00002155 bool EmittedUseCheck = false;
2156 bool EmittedSlctedCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00002157 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00002158 if (NodeHasChain)
2159 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00002160 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00002161 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Evan Cheng61a02092006-04-28 02:08:10 +00002162 // Not in flight?
Evan Cheng55d0fa12006-04-28 18:54:11 +00002163 emitCheck("InFlightSet.count(" + RootName + ".Val) == 0");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002164 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002165 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002166 EmittedUseCheck = true;
2167 // hasOneUse() check is not strong enough. If the original node has
2168 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002169 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002170 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002171 "))");
2172
Evan Cheng1feeeec2006-01-26 19:13:45 +00002173 EmittedSlctedCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002174 if (NodeHasChain) {
2175 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2176 // has a chain use.
2177 // This a workaround for this problem:
2178 //
2179 // [ch, r : ld]
2180 // ^ ^
2181 // | |
2182 // [XX]--/ \- [flag : cmp]
2183 // ^ ^
2184 // | |
2185 // \---[br flag]-
2186 //
2187 // cmp + br should be considered as a single node as they are flagged
2188 // together. So, if the ld is folded into the cmp, the XX node in the
2189 // graph is now both an operand and a use of the ld/cmp/br node.
2190 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2191 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2192
2193 // If the immediate use can somehow reach this node through another
2194 // path, then can't fold it either or it will create a cycle.
2195 // e.g. In the following diagram, XX can reach ld through YY. If
2196 // ld is folded into XX, then YY is both a predecessor and a successor
2197 // of XX.
2198 //
2199 // [ld]
2200 // ^ ^
2201 // | |
2202 // / \---
2203 // / [YY]
2204 // | ^
2205 // [XX]-------|
2206 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2207 if (PInfo.getNumOperands() > 1 ||
2208 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2209 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2210 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
Evan Cheng6f8aaf22006-03-07 08:31:27 +00002211 if (PInfo.getNumOperands() > 1) {
2212 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2213 ".Val)");
2214 } else {
2215 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2216 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2217 ".Val))");
2218 }
Evan Chenge41bf822006-02-05 06:43:12 +00002219 }
Evan Chengb915f312005-12-09 22:45:35 +00002220 }
Evan Chenge41bf822006-02-05 06:43:12 +00002221
Evan Chengc15d18c2006-01-27 22:13:45 +00002222 if (NodeHasChain) {
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002223 ChainName = "Chain" + ChainSuffix;
Evan Cheng21ad3922006-02-07 00:37:41 +00002224 emitDecl(ChainName);
Evan Chenged66e852006-03-09 08:19:11 +00002225 if (FoundChain) {
2226 // FIXME: temporary workaround for a common case where chain
2227 // is a TokenFactor and the previous "inner" chain is an operand.
2228 NewTF = true;
2229 emitDecl("OldTF", true);
2230 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2231 RootName + ".Val, Chain.Val, OldTF)).Val");
2232 } else {
2233 FoundChain = true;
2234 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2235 }
Evan Cheng1cf6db22006-01-06 00:41:12 +00002236 }
Evan Chengb915f312005-12-09 22:45:35 +00002237 }
2238
Evan Cheng54597732006-01-26 00:22:25 +00002239 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002240 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002241 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002242 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2243 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002244 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002245 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2246 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2247 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002248 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2249 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002250 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002251 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002252 }
Evan Cheng1feeeec2006-01-26 19:13:45 +00002253 if (!EmittedSlctedCheck)
2254 // hasOneUse() check is not strong enough. If the original node has
2255 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002256 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002257 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002258 "))");
Evan Cheng54597732006-01-26 00:22:25 +00002259 }
2260
Evan Chengb915f312005-12-09 22:45:35 +00002261 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002262 emitDecl(RootName + utostr(OpNo));
2263 emitCode(RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002264 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002265 TreePatternNode *Child = N->getChild(i);
2266
2267 if (!Child->isLeaf()) {
2268 // If it's not a leaf, recursively match.
2269 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002270 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002271 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002272 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2273 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002274 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002275 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2276 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002277 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002278 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002279 // we already saw this in the pattern, emit code to verify dagness.
2280 if (!Child->getName().empty()) {
2281 std::string &VarMapEntry = VariableMap[Child->getName()];
2282 if (VarMapEntry.empty()) {
2283 VarMapEntry = RootName + utostr(OpNo);
2284 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002285 // If we get here, this is a second reference to a specific name.
2286 // Since we already have checked that the first reference is valid,
2287 // we don't have to recursively match it, just check that it's the
2288 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002289 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002290 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002291 continue;
2292 }
2293 }
2294
2295 // Handle leaves of various types.
2296 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2297 Record *LeafRec = DI->getDef();
2298 if (LeafRec->isSubClassOf("RegisterClass")) {
2299 // Handle register references. Nothing to do here.
2300 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002301 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002302 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2303 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00002304 } else if (LeafRec->getName() == "srcvalue") {
2305 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002306 } else if (LeafRec->isSubClassOf("ValueType")) {
2307 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002308 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002309 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002310 } else if (LeafRec->isSubClassOf("CondCode")) {
2311 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002312 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002313 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002314 } else {
2315 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002316 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00002317 assert(0 && "Unknown leaf type!");
2318 }
Chris Lattner488580c2006-01-28 19:06:51 +00002319 } else if (IntInit *II =
2320 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002321 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2322 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002323 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002324 RootName + utostr(OpNo) + ")->getSignExtended();");
2325
2326 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002327 } else {
2328 Child->dump();
2329 assert(0 && "Unknown leaf type!");
2330 }
2331 }
2332 }
2333
2334 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002335 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002336 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002337 }
2338
2339 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2340 /// we actually have to build a DAG!
2341 std::pair<unsigned, unsigned>
Chris Lattner947604b2006-03-24 21:52:20 +00002342 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2343 bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002344 // This is something selected from the pattern we matched.
2345 if (!N->getName().empty()) {
Evan Chengb915f312005-12-09 22:45:35 +00002346 std::string &Val = VariableMap[N->getName()];
2347 assert(!Val.empty() &&
2348 "Variable referenced but not defined and not caught earlier!");
2349 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2350 // Already selected this operand, just return the tmpval.
2351 return std::make_pair(1, atoi(Val.c_str()+3));
2352 }
2353
2354 const ComplexPattern *CP;
2355 unsigned ResNo = TmpNo++;
2356 unsigned NumRes = 1;
2357 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002358 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002359 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002360 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002361 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002362 case MVT::i1: CastType = "bool"; break;
2363 case MVT::i8: CastType = "unsigned char"; break;
2364 case MVT::i16: CastType = "unsigned short"; break;
2365 case MVT::i32: CastType = "unsigned"; break;
2366 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002367 }
Chris Lattner78593132006-01-29 20:01:35 +00002368 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
Andrew Lenharth2cba57c2006-01-29 05:17:22 +00002369 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
Evan Cheng21ad3922006-02-07 00:37:41 +00002370 emitDecl("Tmp" + utostr(ResNo));
2371 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002372 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
Evan Cheng2618d072006-05-17 20:37:59 +00002373 "C, " + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengbb48e332006-01-12 07:54:57 +00002374 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002375 Record *Op = OperatorMap[N->getName()];
2376 // Transform ExternalSymbol to TargetExternalSymbol
2377 if (Op && Op->getName() == "externalsym") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002378 emitDecl("Tmp" + utostr(ResNo));
2379 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002380 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002381 Val + ")->getSymbol(), " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002382 getEnumName(N->getTypeNum(0)) + ");");
2383 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002384 emitDecl("Tmp" + utostr(ResNo));
2385 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002386 }
Evan Chengb915f312005-12-09 22:45:35 +00002387 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002388 Record *Op = OperatorMap[N->getName()];
2389 // Transform GlobalAddress to TargetGlobalAddress
2390 if (Op && Op->getName() == "globaladdr") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002391 emitDecl("Tmp" + utostr(ResNo));
2392 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002393 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
Evan Cheng2618d072006-05-17 20:37:59 +00002394 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002395 ");");
2396 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002397 emitDecl("Tmp" + utostr(ResNo));
2398 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002399 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002400 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng21ad3922006-02-07 00:37:41 +00002401 emitDecl("Tmp" + utostr(ResNo));
2402 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengbb48e332006-01-12 07:54:57 +00002403 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002404 emitDecl("Tmp" + utostr(ResNo));
2405 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002406 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2407 std::string Fn = CP->getSelectFunc();
2408 NumRes = CP->getNumOperands();
Evan Cheng21ad3922006-02-07 00:37:41 +00002409 for (unsigned i = 0; i < NumRes; ++i)
2410 emitDecl("Tmp" + utostr(i+ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002411
Evan Cheng21ad3922006-02-07 00:37:41 +00002412 std::string Code = Fn + "(" + Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002413 for (unsigned i = 0; i < NumRes; i++)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002414 Code += ", Tmp" + utostr(i + ResNo);
2415 emitCheck(Code + ")");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002416
Evan Cheng61a02092006-04-28 02:08:10 +00002417 for (unsigned i = 0; i < NumRes; ++i) {
2418 emitCode("InFlightSet.insert(Tmp" + utostr(i+ResNo) + ".Val);");
2419 InflightNodes.push_back("Tmp" + utostr(i+ResNo));
2420 }
Evan Cheng2216d8a2006-02-05 05:22:18 +00002421 for (unsigned i = 0; i < NumRes; ++i)
Evan Cheng34167212006-02-09 00:37:58 +00002422 emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
Evan Cheng2216d8a2006-02-05 05:22:18 +00002423 utostr(i+ResNo) + ");");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002424
Evan Chengb915f312005-12-09 22:45:35 +00002425 TmpNo = ResNo + NumRes;
2426 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002427 emitDecl("Tmp" + utostr(ResNo));
Evan Cheng863bf5a2006-03-20 22:53:06 +00002428 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2429 // node even if it isn't one. Don't select it.
2430 if (LikeLeaf)
2431 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Cheng61a02092006-04-28 02:08:10 +00002432 else {
Evan Cheng863bf5a2006-03-20 22:53:06 +00002433 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
Evan Cheng61a02092006-04-28 02:08:10 +00002434 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00002435
2436 if (isRoot && N->isLeaf()) {
2437 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2438 emitCode("return;");
2439 }
Evan Chengb915f312005-12-09 22:45:35 +00002440 }
2441 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2442 // value if used multiple times by this pattern result.
2443 Val = "Tmp"+utostr(ResNo);
2444 return std::make_pair(NumRes, ResNo);
2445 }
Evan Chengb915f312005-12-09 22:45:35 +00002446 if (N->isLeaf()) {
2447 // If this is an explicit register reference, handle it.
2448 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2449 unsigned ResNo = TmpNo++;
2450 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002451 emitDecl("Tmp" + utostr(ResNo));
2452 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Evan Cheng2618d072006-05-17 20:37:59 +00002453 ISE.getQualifiedName(DI->getDef()) + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002454 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002455 return std::make_pair(1, ResNo);
2456 }
2457 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2458 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002459 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng21ad3922006-02-07 00:37:41 +00002460 emitDecl("Tmp" + utostr(ResNo));
2461 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002462 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
Evan Cheng2618d072006-05-17 20:37:59 +00002463 ", " + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002464 return std::make_pair(1, ResNo);
2465 }
2466
2467 N->dump();
2468 assert(0 && "Unknown leaf type!");
2469 return std::make_pair(1, ~0U);
2470 }
2471
2472 Record *Op = N->getOperator();
2473 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002474 const CodeGenTarget &CGT = ISE.getTargetInfo();
2475 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002476 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng045953c2006-05-10 00:05:46 +00002477 TreePattern *InstPat = Inst.getPattern();
2478 TreePatternNode *InstPatNode =
2479 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2480 : (InstPat ? InstPat->getOnlyTree() : NULL);
2481 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2482 InstPatNode = InstPatNode->getChild(1);
2483 }
2484 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2485 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2486 bool NodeHasOptInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002487 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002488 bool NodeHasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002489 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002490 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2491 PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2492 bool NodeHasChain = InstPatNode &&
2493 PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002494 bool InputHasChain = isRoot &&
2495 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng4fba2812005-12-20 07:37:41 +00002496
Evan Cheng045953c2006-05-10 00:05:46 +00002497 if (NodeHasInFlag || NodeHasOutFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng21ad3922006-02-07 00:37:41 +00002498 emitDecl("InFlag");
Evan Cheng045953c2006-05-10 00:05:46 +00002499 if (NodeHasOptInFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002500 emitCode("bool HasOptInFlag = false;");
Evan Cheng4fba2812005-12-20 07:37:41 +00002501
Evan Cheng823b7522006-01-19 21:57:10 +00002502 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002503 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002504 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2505 MVT::ValueType VT = Pattern->getTypeNum(i);
2506 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002507 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002508 }
2509
Evan Chengb915f312005-12-09 22:45:35 +00002510 // Determine operand emission order. Complex pattern first.
2511 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2512 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2513 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2514 TreePatternNode *Child = N->getChild(i);
2515 if (i == 0) {
2516 EmitOrder.push_back(std::make_pair(i, Child));
2517 OI = EmitOrder.begin();
2518 } else if (NodeIsComplexPattern(Child)) {
2519 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2520 } else {
2521 EmitOrder.push_back(std::make_pair(i, Child));
2522 }
2523 }
2524
Evan Cheng61a02092006-04-28 02:08:10 +00002525 // Make sure these operands which would be selected won't be folded while
2526 // the isel traverses the DAG upward.
Evan Chengb915f312005-12-09 22:45:35 +00002527 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2528 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
Evan Cheng61a02092006-04-28 02:08:10 +00002529 TreePatternNode *Child = EmitOrder[i].second;
2530 if (!Child->getName().empty()) {
2531 std::string &Val = VariableMap[Child->getName()];
2532 assert(!Val.empty() &&
2533 "Variable referenced but not defined and not caught earlier!");
2534 if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) {
2535 emitCode("InFlightSet.insert(" + Val + ".Val);");
2536 InflightNodes.push_back(Val);
2537 }
2538 }
2539 }
2540
2541 // Emit all of the operands.
2542 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
Evan Chengb915f312005-12-09 22:45:35 +00002543 unsigned OpOrder = EmitOrder[i].first;
2544 TreePatternNode *Child = EmitOrder[i].second;
2545 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2546 NumTemps[OpOrder] = NumTemp;
2547 }
2548
2549 // List all the operands in the right order.
2550 std::vector<unsigned> Ops;
2551 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2552 for (unsigned j = 0; j < NumTemps[i].first; j++)
2553 Ops.push_back(NumTemps[i].second + j);
2554 }
2555
Evan Chengb915f312005-12-09 22:45:35 +00002556 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +00002557 bool ChainEmitted = NodeHasChain;
2558 if (NodeHasChain)
Evan Cheng34167212006-02-09 00:37:58 +00002559 emitCode("Select(" + ChainName + ", " + ChainName + ");");
Evan Cheng045953c2006-05-10 00:05:46 +00002560 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng54597732006-01-26 00:22:25 +00002561 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
Evan Chengb915f312005-12-09 22:45:35 +00002562
Evan Cheng045953c2006-05-10 00:05:46 +00002563 if (isRoot) {
2564 // The operands have been selected. Remove them from InFlightSet.
2565 for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2566 AE = InflightNodes.end(); AI != AE; ++AI)
2567 emitCode("InFlightSet.erase(" + *AI + ".Val);");
2568 }
2569
Evan Chengb915f312005-12-09 22:45:35 +00002570 unsigned NumResults = Inst.getNumResults();
2571 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002572 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2573 NodeHasOptInFlag) {
Evan Cheng045953c2006-05-10 00:05:46 +00002574 if (NodeHasOptInFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002575 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
Evan Chengd7805a72006-02-09 07:16:09 +00002576 emitDecl("ResNode", true);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002577 emitCode("if (HasOptInFlag)");
Evan Chengd7805a72006-02-09 07:16:09 +00002578 std::string Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002579 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002580
Evan Cheng9789aaa2006-01-24 20:46:50 +00002581 // Output order: results, chain, flags
2582 // Result types.
Evan Cheng3eff89b2006-05-10 02:47:57 +00002583 if (PatResults > 0) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002584 if (N->getTypeNum(0) != MVT::isVoid)
Evan Cheng2618d072006-05-17 20:37:59 +00002585 Code += ", " + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002586 }
Evan Cheng045953c2006-05-10 00:05:46 +00002587 if (NodeHasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002588 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002589 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002590 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002591
2592 // Inputs.
2593 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002594 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002595 if (NodeHasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002596 emitCode(Code + ", InFlag);");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002597
Chris Lattner8a0604b2006-01-28 20:31:24 +00002598 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002599 Code = " ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002600 II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002601
2602 // Output order: results, chain, flags
2603 // Result types.
Evan Cheng3eff89b2006-05-10 02:47:57 +00002604 if (PatResults > 0 && N->getTypeNum(0) != MVT::isVoid)
Evan Cheng2618d072006-05-17 20:37:59 +00002605 Code += ", " + getEnumName(N->getTypeNum(0));
Evan Cheng045953c2006-05-10 00:05:46 +00002606 if (NodeHasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002607 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002608 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002609 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002610
2611 // Inputs.
2612 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002613 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002614 if (NodeHasChain) Code += ", " + ChainName + ");";
Chris Lattner8a0604b2006-01-28 20:31:24 +00002615 emitCode(Code);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002616
2617 if (NodeHasChain)
2618 // Remember which op produces the chain.
2619 emitCode(ChainName + " = SDOperand(ResNode" +
2620 ", " + utostr(PatResults) + ");");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002621 } else {
Evan Cheng045953c2006-05-10 00:05:46 +00002622 std::string Code;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002623 std::string NodeName;
Evan Cheng045953c2006-05-10 00:05:46 +00002624 if (!isRoot) {
Evan Cheng3eff89b2006-05-10 02:47:57 +00002625 NodeName = "Tmp" + utostr(ResNo);
Evan Cheng045953c2006-05-10 00:05:46 +00002626 emitDecl(NodeName);
2627 Code = NodeName + " = SDOperand(";
2628 } else {
Evan Cheng3eff89b2006-05-10 02:47:57 +00002629 NodeName = "ResNode";
Evan Cheng045953c2006-05-10 00:05:46 +00002630 emitDecl(NodeName, true);
2631 Code = NodeName + " = ";
2632 }
2633 Code += "CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002634 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002635
2636 // Output order: results, chain, flags
2637 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002638 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
Evan Cheng2618d072006-05-17 20:37:59 +00002639 Code += ", " + getEnumName(N->getTypeNum(0));
Evan Cheng045953c2006-05-10 00:05:46 +00002640 if (NodeHasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002641 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002642 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002643 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002644
2645 // Inputs.
2646 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002647 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002648 if (NodeHasChain) Code += ", " + ChainName;
2649 if (NodeHasInFlag || HasImpInputs) Code += ", InFlag";
2650 if (!isRoot)
2651 emitCode(Code + "), 0);");
2652 else
2653 emitCode(Code + ");");
Evan Cheng3eff89b2006-05-10 02:47:57 +00002654
2655 if (NodeHasChain)
2656 // Remember which op produces the chain.
2657 if (!isRoot)
2658 emitCode(ChainName + " = SDOperand(" + NodeName +
2659 ".Val, " + utostr(PatResults) + ");");
2660 else
2661 emitCode(ChainName + " = SDOperand(" + NodeName +
2662 ", " + utostr(PatResults) + ");");
Evan Chengbcecf332005-12-17 01:19:28 +00002663 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002664
Evan Cheng045953c2006-05-10 00:05:46 +00002665 if (!isRoot)
2666 return std::make_pair(1, ResNo);
2667
Evan Chenged66e852006-03-09 08:19:11 +00002668 if (NewTF)
2669 emitCode("if (OldTF) "
2670 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2671 ChainName + ".Val, 0);");
2672
2673 for (unsigned i = 0; i < NumResults; i++)
Evan Cheng67212a02006-02-09 22:12:27 +00002674 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002675 utostr(i) + ", ResNode, " + utostr(i) + ");");
Evan Chengf9fc25d2005-12-19 22:40:04 +00002676
Evan Cheng54597732006-01-26 00:22:25 +00002677 if (NodeHasOutFlag)
Evan Chengd7805a72006-02-09 07:16:09 +00002678 emitCode("InFlag = SDOperand(ResNode, " +
Evan Cheng045953c2006-05-10 00:05:46 +00002679 utostr(NumResults + (unsigned)NodeHasChain) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002680
Chris Lattner8a0604b2006-01-28 20:31:24 +00002681 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
Evan Chenged66e852006-03-09 08:19:11 +00002682 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2683 "0, ResNode, 0);");
2684 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00002685 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002686
Evan Cheng045953c2006-05-10 00:05:46 +00002687 if (InputHasChain) {
Evan Cheng67212a02006-02-09 22:12:27 +00002688 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Cheng3eff89b2006-05-10 02:47:57 +00002689 utostr(PatResults) + ", " + ChainName + ".Val, " +
2690 ChainName + ".ResNo" + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002691 if (DoReplace)
Evan Chenged66e852006-03-09 08:19:11 +00002692 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
Evan Cheng3eff89b2006-05-10 02:47:57 +00002693 utostr(PatResults) + ", " + ChainName + ".Val, " +
2694 ChainName + ".ResNo" + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002695 }
2696
Evan Cheng97938882005-12-22 02:24:50 +00002697 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002698 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002699 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng67212a02006-02-09 22:12:27 +00002700 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2701 FoldedChains[j].first + ".Val, " +
2702 utostr(FoldedChains[j].second) + ", ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002703 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002704
2705 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2706 std::string Code =
Evan Cheng67212a02006-02-09 22:12:27 +00002707 FoldedChains[j].first + ".Val, " +
2708 utostr(FoldedChains[j].second) + ", ";
2709 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002710 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002711 }
Evan Chengb915f312005-12-09 22:45:35 +00002712 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002713
Evan Cheng54597732006-01-26 00:22:25 +00002714 if (NodeHasOutFlag)
Evan Cheng67212a02006-02-09 22:12:27 +00002715 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Cheng045953c2006-05-10 00:05:46 +00002716 utostr(PatResults + (unsigned)InputHasChain) +
Evan Chenged66e852006-03-09 08:19:11 +00002717 ", InFlag.Val, InFlag.ResNo);");
Evan Cheng97938882005-12-22 02:24:50 +00002718
Evan Chenged66e852006-03-09 08:19:11 +00002719 // User does not expect the instruction would produce a chain!
Evan Cheng045953c2006-05-10 00:05:46 +00002720 bool AddedChain = NodeHasChain && !InputHasChain;
Evan Cheng54597732006-01-26 00:22:25 +00002721 if (AddedChain && NodeHasOutFlag) {
Evan Chenged66e852006-03-09 08:19:11 +00002722 if (PatResults == 0) {
Evan Chengd7805a72006-02-09 07:16:09 +00002723 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002724 } else {
Evan Chenged66e852006-03-09 08:19:11 +00002725 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
Evan Chengd7805a72006-02-09 07:16:09 +00002726 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002727 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002728 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002729 }
Evan Cheng3eff89b2006-05-10 02:47:57 +00002730 } else if (InputHasChain && !NodeHasChain) {
2731 // One of the inner node produces a chain.
2732 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2733 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2734 if (NodeHasOutFlag) {
2735 emitCode("else if (N.ResNo > " + utostr(PatResults) + ")");
2736 emitCode(" Result = SDOperand(ResNode, N.ResNo-1);");
2737 }
2738 emitCode("else");
2739 emitCode(" Result = SDOperand(" + ChainName + ".Val, " + ChainName + ".ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002740 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002741 emitCode("Result = SDOperand(ResNode, N.ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002742 }
Evan Chengb915f312005-12-09 22:45:35 +00002743 } else {
2744 // If this instruction is the root, and if there is only one use of it,
2745 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002746 emitCode("if (N.Val->hasOneUse()) {");
Evan Cheng34167212006-02-09 00:37:58 +00002747 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002748 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002749 if (N->getTypeNum(0) != MVT::isVoid)
Evan Cheng2618d072006-05-17 20:37:59 +00002750 Code += ", " + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002751 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002752 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002753 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002754 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002755 if (NodeHasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002756 Code += ", InFlag";
2757 emitCode(Code + ");");
2758 emitCode("} else {");
Evan Chengd7805a72006-02-09 07:16:09 +00002759 emitDecl("ResNode", true);
2760 Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002761 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002762 if (N->getTypeNum(0) != MVT::isVoid)
Evan Cheng2618d072006-05-17 20:37:59 +00002763 Code += ", " + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002764 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002765 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002766 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002767 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002768 if (NodeHasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002769 Code += ", InFlag";
2770 emitCode(Code + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002771 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2772 "ResNode, 0);");
2773 emitCode(" Result = SDOperand(ResNode, 0);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002774 emitCode("}");
Evan Chengb915f312005-12-09 22:45:35 +00002775 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002776
Evan Cheng34167212006-02-09 00:37:58 +00002777 if (isRoot)
2778 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002779 return std::make_pair(1, ResNo);
2780 } else if (Op->isSubClassOf("SDNodeXForm")) {
2781 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00002782 // PatLeaf node - the operand may or may not be a leaf node. But it should
2783 // behave like one.
2784 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
Evan Chengb915f312005-12-09 22:45:35 +00002785 unsigned ResNo = TmpNo++;
Evan Cheng21ad3922006-02-07 00:37:41 +00002786 emitDecl("Tmp" + utostr(ResNo));
2787 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Chris Lattner8a0604b2006-01-28 20:31:24 +00002788 + "(Tmp" + utostr(OpVal) + ".Val);");
Evan Chengb915f312005-12-09 22:45:35 +00002789 if (isRoot) {
Evan Cheng67212a02006-02-09 22:12:27 +00002790 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2791 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2792 utostr(ResNo) + ".ResNo);");
Evan Cheng34167212006-02-09 00:37:58 +00002793 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2794 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002795 }
2796 return std::make_pair(1, ResNo);
2797 } else {
2798 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002799 std::cerr << "\n";
2800 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002801 }
2802 }
2803
Chris Lattner488580c2006-01-28 19:06:51 +00002804 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2805 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002806 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2807 /// for, this returns true otherwise false if Pat has all types.
2808 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2809 const std::string &Prefix) {
2810 // Did we find one?
2811 if (!Pat->hasTypeSet()) {
2812 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002813 Pat->setTypes(Other->getExtTypes());
Chris Lattner67a202b2006-01-28 20:43:52 +00002814 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002815 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002816 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002817 }
2818
Evan Cheng51fecc82006-01-09 18:27:06 +00002819 unsigned OpNo =
2820 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002821 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2822 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2823 Prefix + utostr(OpNo)))
2824 return true;
2825 return false;
2826 }
2827
2828private:
Evan Cheng54597732006-01-26 00:22:25 +00002829 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002830 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002831 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2832 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002833 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002834 unsigned OpNo =
2835 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002836 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2837 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002838 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2839 TreePatternNode *Child = N->getChild(i);
2840 if (!Child->isLeaf()) {
Evan Cheng54597732006-01-26 00:22:25 +00002841 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002842 } else {
2843 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002844 if (!Child->getName().empty()) {
2845 std::string Name = RootName + utostr(OpNo);
2846 if (Duplicates.find(Name) != Duplicates.end())
2847 // A duplicate! Do not emit a copy for this node.
2848 continue;
2849 }
2850
Evan Chengb915f312005-12-09 22:45:35 +00002851 Record *RR = DI->getDef();
2852 if (RR->isSubClassOf("Register")) {
2853 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002854 if (RVT == MVT::Flag) {
Evan Cheng34167212006-02-09 00:37:58 +00002855 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
Evan Chengb2c6d492006-01-11 22:16:13 +00002856 } else {
2857 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002858 emitDecl("Chain");
2859 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002860 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002861 ChainEmitted = true;
2862 }
Evan Cheng34167212006-02-09 00:37:58 +00002863 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2864 RootName + utostr(OpNo) + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002865 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002866 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
Evan Cheng2618d072006-05-17 20:37:59 +00002867 ", " + getEnumName(RVT) + "), " +
Evan Chengd7805a72006-02-09 07:16:09 +00002868 RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng67212a02006-02-09 22:12:27 +00002869 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2870 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00002871 }
2872 }
2873 }
2874 }
2875 }
Evan Cheng54597732006-01-26 00:22:25 +00002876
2877 if (HasInFlag || HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002878 std::string Code;
Evan Cheng54597732006-01-26 00:22:25 +00002879 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002880 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2881 ") {");
2882 Code = " ";
Evan Cheng54597732006-01-26 00:22:25 +00002883 }
Evan Cheng34167212006-02-09 00:37:58 +00002884 emitCode(Code + "Select(InFlag, " + RootName +
2885 ".getOperand(" + utostr(OpNo) + "));");
Evan Cheng54597732006-01-26 00:22:25 +00002886 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002887 emitCode(" HasOptInFlag = true;");
2888 emitCode("}");
Evan Cheng54597732006-01-26 00:22:25 +00002889 }
2890 }
Evan Chengb915f312005-12-09 22:45:35 +00002891 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002892
2893 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002894 /// as specified by the instruction. It returns true if any copy is
2895 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002896 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002897 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002898 Record *Op = N->getOperator();
2899 if (Op->isSubClassOf("Instruction")) {
2900 const DAGInstruction &Inst = ISE.getInstruction(Op);
2901 const CodeGenTarget &CGT = ISE.getTargetInfo();
Evan Cheng4fba2812005-12-20 07:37:41 +00002902 unsigned NumImpResults = Inst.getNumImpResults();
2903 for (unsigned i = 0; i < NumImpResults; i++) {
2904 Record *RR = Inst.getImpResult(i);
2905 if (RR->isSubClassOf("Register")) {
2906 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2907 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002908 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002909 emitDecl("Chain");
2910 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002911 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002912 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002913 }
Evan Chengd7805a72006-02-09 07:16:09 +00002914 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
Evan Cheng2618d072006-05-17 20:37:59 +00002915 ISE.getQualifiedName(RR) + ", " + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00002916 ", InFlag).Val;");
2917 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2918 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002919 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002920 }
2921 }
2922 }
2923 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002924 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002925 }
Evan Chengb915f312005-12-09 22:45:35 +00002926};
2927
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002928/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2929/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00002930/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00002931void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Chenge41bf822006-02-05 06:43:12 +00002932 std::vector<std::pair<bool, std::string> > &GeneratedCode,
Evan Chengd7805a72006-02-09 07:16:09 +00002933 std::set<std::pair<bool, std::string> > &GeneratedDecl,
Evan Chenge41bf822006-02-05 06:43:12 +00002934 bool DoReplace) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002935 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2936 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Cheng21ad3922006-02-07 00:37:41 +00002937 GeneratedCode, GeneratedDecl, DoReplace);
Evan Chengb915f312005-12-09 22:45:35 +00002938
Chris Lattner8fc35682005-09-23 23:16:51 +00002939 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002940 bool FoundChain = false;
Evan Chenge41bf822006-02-05 06:43:12 +00002941 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002942
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002943 // TP - Get *SOME* tree pattern, we don't care which.
2944 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002945
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002946 // At this point, we know that we structurally match the pattern, but the
2947 // types of the nodes may not match. Figure out the fewest number of type
2948 // comparisons we need to emit. For example, if there is only one integer
2949 // type supported by a target, there should be no type comparisons at all for
2950 // integer patterns!
2951 //
2952 // To figure out the fewest number of type checks needed, clone the pattern,
2953 // remove the types, then perform type inference on the pattern as a whole.
2954 // If there are unresolved types, emit an explicit check for those types,
2955 // apply the type to the tree, then rerun type inference. Iterate until all
2956 // types are resolved.
2957 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002958 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002959 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002960
2961 do {
2962 // Resolve/propagate as many types as possible.
2963 try {
2964 bool MadeChange = true;
2965 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00002966 MadeChange = Pat->ApplyTypeConstraints(TP,
2967 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00002968 } catch (...) {
2969 assert(0 && "Error: could not find consistent types for something we"
2970 " already decided was ok!");
2971 abort();
2972 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002973
Chris Lattner7e82f132005-10-15 21:34:21 +00002974 // Insert a check for an unresolved type and add it to the tree. If we find
2975 // an unresolved type to add a check for, this returns true and we iterate,
2976 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002977 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002978
Evan Cheng863bf5a2006-03-20 22:53:06 +00002979 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002980 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00002981}
2982
Chris Lattner24e00a42006-01-29 04:41:05 +00002983/// EraseCodeLine - Erase one code line from all of the patterns. If removing
2984/// a line causes any of them to be empty, remove them and return true when
2985/// done.
2986static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2987 std::vector<std::pair<bool, std::string> > > >
2988 &Patterns) {
2989 bool ErasedPatterns = false;
2990 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2991 Patterns[i].second.pop_back();
2992 if (Patterns[i].second.empty()) {
2993 Patterns.erase(Patterns.begin()+i);
2994 --i; --e;
2995 ErasedPatterns = true;
2996 }
2997 }
2998 return ErasedPatterns;
2999}
3000
Chris Lattner8bc74722006-01-29 04:25:26 +00003001/// EmitPatterns - Emit code for at least one pattern, but try to group common
3002/// code together between the patterns.
3003void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
3004 std::vector<std::pair<bool, std::string> > > >
3005 &Patterns, unsigned Indent,
3006 std::ostream &OS) {
3007 typedef std::pair<bool, std::string> CodeLine;
3008 typedef std::vector<CodeLine> CodeList;
3009 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
3010
3011 if (Patterns.empty()) return;
3012
Chris Lattner24e00a42006-01-29 04:41:05 +00003013 // Figure out how many patterns share the next code line. Explicitly copy
3014 // FirstCodeLine so that we don't invalidate a reference when changing
3015 // Patterns.
3016 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00003017 unsigned LastMatch = Patterns.size()-1;
3018 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
3019 --LastMatch;
3020
3021 // If not all patterns share this line, split the list into two pieces. The
3022 // first chunk will use this line, the second chunk won't.
3023 if (LastMatch != 0) {
3024 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
3025 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
3026
3027 // FIXME: Emit braces?
3028 if (Shared.size() == 1) {
3029 PatternToMatch &Pattern = *Shared.back().first;
3030 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3031 Pattern.getSrcPattern()->print(OS);
3032 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3033 Pattern.getDstPattern()->print(OS);
3034 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003035 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003036 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003037 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003038 << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00003039 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003040 }
3041 if (!FirstCodeLine.first) {
3042 OS << std::string(Indent, ' ') << "{\n";
3043 Indent += 2;
3044 }
3045 EmitPatterns(Shared, Indent, OS);
3046 if (!FirstCodeLine.first) {
3047 Indent -= 2;
3048 OS << std::string(Indent, ' ') << "}\n";
3049 }
3050
3051 if (Other.size() == 1) {
3052 PatternToMatch &Pattern = *Other.back().first;
3053 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3054 Pattern.getSrcPattern()->print(OS);
3055 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3056 Pattern.getDstPattern()->print(OS);
3057 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003058 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003059 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003060 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003061 << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00003062 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003063 }
3064 EmitPatterns(Other, Indent, OS);
3065 return;
3066 }
3067
Chris Lattner24e00a42006-01-29 04:41:05 +00003068 // Remove this code from all of the patterns that share it.
3069 bool ErasedPatterns = EraseCodeLine(Patterns);
3070
Chris Lattner8bc74722006-01-29 04:25:26 +00003071 bool isPredicate = FirstCodeLine.first;
3072
3073 // Otherwise, every pattern in the list has this line. Emit it.
3074 if (!isPredicate) {
3075 // Normal code.
3076 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3077 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00003078 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3079
3080 // If the next code line is another predicate, and if all of the pattern
3081 // in this group share the same next line, emit it inline now. Do this
3082 // until we run out of common predicates.
3083 while (!ErasedPatterns && Patterns.back().second.back().first) {
3084 // Check that all of fhe patterns in Patterns end with the same predicate.
3085 bool AllEndWithSamePredicate = true;
3086 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3087 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3088 AllEndWithSamePredicate = false;
3089 break;
3090 }
3091 // If all of the predicates aren't the same, we can't share them.
3092 if (!AllEndWithSamePredicate) break;
3093
3094 // Otherwise we can. Emit it shared now.
3095 OS << " &&\n" << std::string(Indent+4, ' ')
3096 << Patterns.back().second.back().second;
3097 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00003098 }
Chris Lattner24e00a42006-01-29 04:41:05 +00003099
3100 OS << ") {\n";
3101 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00003102 }
3103
3104 EmitPatterns(Patterns, Indent, OS);
3105
3106 if (isPredicate)
3107 OS << std::string(Indent-2, ' ') << "}\n";
3108}
3109
3110
Chris Lattner37481472005-09-26 21:59:35 +00003111
3112namespace {
3113 /// CompareByRecordName - An ordering predicate that implements less-than by
3114 /// comparing the names records.
3115 struct CompareByRecordName {
3116 bool operator()(const Record *LHS, const Record *RHS) const {
3117 // Sort by name first.
3118 if (LHS->getName() < RHS->getName()) return true;
3119 // If both names are equal, sort by pointer.
3120 return LHS->getName() == RHS->getName() && LHS < RHS;
3121 }
3122 };
3123}
3124
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003125void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003126 std::string InstNS = Target.inst_begin()->second.Namespace;
3127 if (!InstNS.empty()) InstNS += "::";
3128
Chris Lattner602f6922006-01-04 00:25:00 +00003129 // Group the patterns by their top-level opcodes.
3130 std::map<Record*, std::vector<PatternToMatch*>,
3131 CompareByRecordName> PatternsByOpcode;
3132 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3133 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3134 if (!Node->isLeaf()) {
3135 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3136 } else {
3137 const ComplexPattern *CP;
3138 if (IntInit *II =
3139 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3140 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3141 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3142 std::vector<Record*> OpNodes = CP->getRootNodes();
3143 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00003144 PatternsByOpcode[OpNodes[j]]
3145 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003146 }
3147 } else {
3148 std::cerr << "Unrecognized opcode '";
3149 Node->dump();
3150 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00003151 std::cerr <<
3152 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00003153 std::cerr << "'!\n";
3154 exit(1);
3155 }
3156 }
3157 }
3158
3159 // Emit one Select_* method for each top-level opcode. We do this instead of
3160 // emitting one giant switch statement to support compilers where this will
3161 // result in the recursive functions taking less stack space.
3162 for (std::map<Record*, std::vector<PatternToMatch*>,
3163 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3164 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00003165 const std::string &OpName = PBOI->first->getName();
Evan Cheng34167212006-02-09 00:37:58 +00003166 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003167
3168 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Evan Chenge41bf822006-02-05 06:43:12 +00003169 bool OptSlctOrder =
3170 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3171 OpcodeInfo.getNumResults() > 0);
3172
3173 if (OptSlctOrder) {
Evan Chenge41bf822006-02-05 06:43:12 +00003174 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3175 << " && N.getValue(0).hasOneUse()) {\n"
3176 << " SDOperand Dummy = "
3177 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003178 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3179 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3180 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3181 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003182 << " Result = Dummy;\n"
3183 << " return;\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003184 << " }\n";
3185 }
3186
Chris Lattner602f6922006-01-04 00:25:00 +00003187 std::vector<PatternToMatch*> &Patterns = PBOI->second;
Chris Lattner355408b2006-01-29 02:43:35 +00003188 assert(!Patterns.empty() && "No patterns but map has entry?");
Chris Lattner602f6922006-01-04 00:25:00 +00003189
3190 // We want to emit all of the matching code now. However, we want to emit
3191 // the matches in order of minimal cost. Sort the patterns so the least
3192 // cost one is at the start.
3193 std::stable_sort(Patterns.begin(), Patterns.end(),
3194 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00003195
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003196 typedef std::vector<std::pair<bool, std::string> > CodeList;
Evan Cheng21ad3922006-02-07 00:37:41 +00003197 typedef std::set<std::string> DeclSet;
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003198
3199 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
Evan Chengd7805a72006-02-09 07:16:09 +00003200 std::set<std::pair<bool, std::string> > GeneratedDecl;
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003201 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003202 CodeList GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00003203 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3204 OptSlctOrder);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003205 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3206 }
3207
3208 // Scan the code to see if all of the patterns are reachable and if it is
3209 // possible that the last one might not match.
3210 bool mightNotMatch = true;
3211 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3212 CodeList &GeneratedCode = CodeForPatterns[i].second;
3213 mightNotMatch = false;
Chris Lattner355408b2006-01-29 02:43:35 +00003214
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003215 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3216 if (GeneratedCode[j].first) { // predicate.
3217 mightNotMatch = true;
3218 break;
3219 }
3220 }
Chris Lattner355408b2006-01-29 02:43:35 +00003221
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003222 // If this pattern definitely matches, and if it isn't the last one, the
3223 // patterns after it CANNOT ever match. Error out.
3224 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3225 std::cerr << "Pattern '";
3226 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3227 std::cerr << "' is impossible to select!\n";
3228 exit(1);
3229 }
3230 }
Evan Cheng21ad3922006-02-07 00:37:41 +00003231
3232 // Print all declarations.
Chris Lattner947604b2006-03-24 21:52:20 +00003233 for (std::set<std::pair<bool, std::string> >::iterator
3234 I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
Evan Chengd7805a72006-02-09 07:16:09 +00003235 if (I->first)
3236 OS << " SDNode *" << I->second << ";\n";
3237 else
3238 OS << " SDOperand " << I->second << "(0, 0);\n";
Evan Cheng21ad3922006-02-07 00:37:41 +00003239
Chris Lattner8bc74722006-01-29 04:25:26 +00003240 // Loop through and reverse all of the CodeList vectors, as we will be
3241 // accessing them from their logical front, but accessing the end of a
3242 // vector is more efficient.
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003243 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3244 CodeList &GeneratedCode = CodeForPatterns[i].second;
Chris Lattner8bc74722006-01-29 04:25:26 +00003245 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003246 }
Chris Lattner602f6922006-01-04 00:25:00 +00003247
Chris Lattner8bc74722006-01-29 04:25:26 +00003248 // Next, reverse the list of patterns itself for the same reason.
3249 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3250
3251 // Emit all of the patterns now, grouped together to share code.
3252 EmitPatterns(CodeForPatterns, 2, OS);
3253
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003254 // If the last pattern has predicates (which could fail) emit code to catch
3255 // the case where nothing handles a pattern.
Chris Lattnerb026e702006-03-28 00:41:33 +00003256 if (mightNotMatch) {
3257 OS << " std::cerr << \"Cannot yet select: \";\n";
3258 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3259 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3260 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3261 OS << " N.Val->dump(CurDAG);\n";
3262 } else {
3263 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3264 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3265 << " std::cerr << \"intrinsic %\"<< "
3266 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3267 }
3268 OS << " std::cerr << '\\n';\n"
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003269 << " abort();\n";
Chris Lattnerb026e702006-03-28 00:41:33 +00003270 }
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003271 OS << "}\n\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003272 }
3273
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003274 // Emit boilerplate.
Evan Cheng34167212006-02-09 00:37:58 +00003275 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003276 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng34167212006-02-09 00:37:58 +00003277 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003278 << " // Select the flag operand.\n"
3279 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng34167212006-02-09 00:37:58 +00003280 << " Select(Ops.back(), Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00003281 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003282 << " std::vector<MVT::ValueType> VTs;\n"
3283 << " VTs.push_back(MVT::Other);\n"
3284 << " VTs.push_back(MVT::Flag);\n"
3285 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003286 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3287 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003288 << " Result = New.getValue(N.ResNo);\n"
3289 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003290 << "}\n\n";
3291
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003292 OS << "// The main instruction selector code.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003293 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003294 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003295 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003296 << "INSTRUCTION_LIST_END)) {\n"
3297 << " Result = N;\n"
3298 << " return; // Already selected.\n"
3299 << " }\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003300 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003301 << " if (CGMI != CodeGenMap.end()) {\n"
3302 << " Result = CGMI->second;\n"
3303 << " return;\n"
3304 << " }\n\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003305 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003306 << " default: break;\n"
3307 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003308 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003309 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003310 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003311 << " case ISD::TargetConstant:\n"
3312 << " case ISD::TargetConstantPool:\n"
3313 << " case ISD::TargetFrameIndex:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00003314 << " case ISD::TargetJumpTable:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003315 << " case ISD::TargetGlobalAddress: {\n"
3316 << " Result = N;\n"
3317 << " return;\n"
3318 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003319 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003320 << " case ISD::AssertZext: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003321 << " SDOperand Tmp0;\n"
3322 << " Select(Tmp0, N.getOperand(0));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003323 << " if (!N.Val->hasOneUse())\n"
3324 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3325 << "Tmp0.Val, Tmp0.ResNo);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003326 << " Result = Tmp0;\n"
3327 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003328 << " }\n"
3329 << " case ISD::TokenFactor:\n"
3330 << " if (N.getNumOperands() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003331 << " SDOperand Op0, Op1;\n"
3332 << " Select(Op0, N.getOperand(0));\n"
3333 << " Select(Op1, N.getOperand(1));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003334 << " Result = \n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003335 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003336 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3337 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003338 << " } else {\n"
3339 << " std::vector<SDOperand> Ops;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003340 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3341 << " SDOperand Val;\n"
3342 << " Select(Val, N.getOperand(i));\n"
3343 << " Ops.push_back(Val);\n"
3344 << " }\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003345 << " Result = \n"
3346 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3347 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3348 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003349 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003350 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003351 << " case ISD::CopyFromReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003352 << " SDOperand Chain;\n"
3353 << " Select(Chain, N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003354 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3355 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003356 << " if (N.Val->getNumValues() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003357 << " if (Chain == N.getOperand(0)) {\n"
3358 << " Result = N; // No change\n"
3359 << " return;\n"
3360 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003361 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003362 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3363 << "New.Val, 0);\n"
3364 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3365 << "New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003366 << " Result = New.getValue(N.ResNo);\n"
3367 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003368 << " } else {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003369 << " SDOperand Flag;\n"
3370 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003371 << " if (Chain == N.getOperand(0) &&\n"
Evan Cheng34167212006-02-09 00:37:58 +00003372 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3373 << " Result = N; // No change\n"
3374 << " return;\n"
3375 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003376 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003377 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3378 << "New.Val, 0);\n"
3379 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3380 << "New.Val, 1);\n"
3381 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3382 << "New.Val, 2);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003383 << " Result = New.getValue(N.ResNo);\n"
3384 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003385 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003386 << " }\n"
3387 << " case ISD::CopyToReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003388 << " SDOperand Chain;\n"
3389 << " Select(Chain, N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003390 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Evan Cheng34167212006-02-09 00:37:58 +00003391 << " SDOperand Val;\n"
3392 << " Select(Val, N.getOperand(2));\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003393 << " Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003394 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003395 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003396 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003397 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3398 << "Result.Val, 0);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003399 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003400 << " SDOperand Flag(0, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003401 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003402 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003403 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003404 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003405 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3406 << "Result.Val, 0);\n"
3407 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3408 << "Result.Val, 1);\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003409 << " Result = Result.getValue(N.ResNo);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003410 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003411 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003412 << " }\n"
Chris Lattner947604b2006-03-24 21:52:20 +00003413 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003414
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003415
Chris Lattner602f6922006-01-04 00:25:00 +00003416 // Loop over all of the case statements, emiting a call to each method we
3417 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003418 for (std::map<Record*, std::vector<PatternToMatch*>,
3419 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3420 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003421 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00003422 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00003423 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Evan Cheng34167212006-02-09 00:37:58 +00003424 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
Chris Lattner81303322005-09-23 19:36:15 +00003425 }
Chris Lattner81303322005-09-23 19:36:15 +00003426
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003427 OS << " } // end of big switch.\n\n"
3428 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00003429 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3430 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3431 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003432 << " N.Val->dump(CurDAG);\n"
3433 << " } else {\n"
3434 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3435 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3436 << " std::cerr << \"intrinsic %\"<< "
3437 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3438 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003439 << " std::cerr << '\\n';\n"
3440 << " abort();\n"
3441 << "}\n";
3442}
3443
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003444void DAGISelEmitter::run(std::ostream &OS) {
3445 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3446 " target", OS);
3447
Chris Lattner1f39e292005-09-14 00:09:24 +00003448 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3449 << "// *** instruction selector class. These functions are really "
3450 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003451
Chris Lattner296dfe32005-09-24 00:50:51 +00003452 OS << "// Instance var to keep track of multiply used nodes that have \n"
3453 << "// already been selected.\n"
3454 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003455
3456 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003457 << "// and their place handle nodes.\n";
3458 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3459 OS << "// Instance var to keep track of mapping of place handle nodes\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003460 << "// and their replacement nodes.\n";
3461 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
Evan Cheng61a02092006-04-28 02:08:10 +00003462 OS << "// Keep track of nodes that are currently being selecte and therefore\n"
3463 << "// should not be folded.\n";
3464 OS << "std::set<SDNode*> InFlightSet;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003465
3466 OS << "\n";
3467 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3468 << "std::set<SDNode *> &Visited) {\n";
3469 OS << " if (found || !Visited.insert(Use).second) return;\n";
3470 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3471 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3472 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3473 OS << " if (N != Def) {\n";
3474 OS << " findNonImmUse(N, Def, found, Visited);\n";
3475 OS << " } else {\n";
3476 OS << " found = true;\n";
3477 OS << " break;\n";
3478 OS << " }\n";
3479 OS << " }\n";
3480 OS << " }\n";
3481 OS << "}\n";
3482
3483 OS << "\n";
3484 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3485 OS << " std::set<SDNode *> Visited;\n";
3486 OS << " bool found = false;\n";
3487 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3488 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3489 OS << " if (N != Def) {\n";
3490 OS << " findNonImmUse(N, Def, found, Visited);\n";
3491 OS << " if (found) break;\n";
3492 OS << " }\n";
3493 OS << " }\n";
3494 OS << " return found;\n";
3495 OS << "}\n";
3496
3497 OS << "\n";
Evan Cheng024524f2006-02-06 06:03:35 +00003498 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003499 << "// handle node in ReplaceMap.\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003500 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3501 << "unsigned RNum) {\n";
3502 OS << " SDOperand N(H, HNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003503 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3504 OS << " if (HMI != HandleMap.end()) {\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003505 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003506 OS << " HandleMap.erase(N);\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003507 OS << " }\n";
3508 OS << "}\n";
3509
3510 OS << "\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003511 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3512 OS << "// handles.Some handles do not yet have replacements because the\n";
3513 OS << "// nodes they replacements have only dead readers.\n";
3514 OS << "void SelectDanglingHandles() {\n";
3515 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3516 << "HandleMap.begin(),\n"
3517 << " E = HandleMap.end(); I != E; ++I) {\n";
3518 OS << " SDOperand N = I->first;\n";
Evan Cheng34167212006-02-09 00:37:58 +00003519 OS << " SDOperand R;\n";
3520 OS << " Select(R, N.getValue(0));\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003521 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003522 OS << " }\n";
3523 OS << "}\n";
3524 OS << "\n";
3525 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003526 OS << "// specific nodes.\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003527 OS << "void ReplaceHandles() {\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003528 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3529 << "ReplaceMap.begin(),\n"
3530 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3531 OS << " SDOperand From = I->first;\n";
3532 OS << " SDOperand To = I->second;\n";
3533 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3534 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3535 OS << " SDNode *Use = *UI;\n";
3536 OS << " std::vector<SDOperand> Ops;\n";
3537 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3538 OS << " SDOperand O = Use->getOperand(i);\n";
3539 OS << " if (O.Val == From.Val)\n";
3540 OS << " Ops.push_back(To);\n";
3541 OS << " else\n";
3542 OS << " Ops.push_back(O);\n";
3543 OS << " }\n";
3544 OS << " SDOperand U = SDOperand(Use, 0);\n";
3545 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3546 OS << " }\n";
3547 OS << " }\n";
3548 OS << "}\n";
3549
3550 OS << "\n";
Evan Chenged66e852006-03-09 08:19:11 +00003551 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3552 OS << "// if the folding were to happen. This is called when, for example,\n";
3553 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3554 OS << "// then the resulting node's input chain would be the load's input\n";
3555 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3556 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3557 OS << "// with the other operands along with the input chain of the load.\n";
3558 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3559 << "SDNode *Chain, SDNode* &OldTF) {\n";
3560 OS << " OldTF = NULL;\n";
3561 OS << " if (N == Chain) {\n";
3562 OS << " return N->getOperand(0);\n";
3563 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3564 OS << " N->isOperand(Chain)) {\n";
3565 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3566 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3567 << "CodeGenMap.find(Ch);\n";
3568 OS << " if (CGMI != CodeGenMap.end())\n";
3569 OS << " return SDOperand(0, 0);\n";
3570 OS << " OldTF = Chain;\n";
3571 OS << " std::vector<SDOperand> Ops;\n";
3572 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3573 OS << " SDOperand Op = Chain->getOperand(i);\n";
3574 OS << " if (Op.Val == N)\n";
3575 OS << " Ops.push_back(N->getOperand(0));\n";
3576 OS << " else\n";
3577 OS << " Ops.push_back(Op);\n";
3578 OS << " }\n";
3579 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3580 OS << " }\n";
3581 OS << " return SDOperand(0, 0);\n";
3582 OS << "}\n";
3583
3584 OS << "\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003585 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3586 OS << "SDOperand SelectRoot(SDOperand N) {\n";
Evan Cheng34167212006-02-09 00:37:58 +00003587 OS << " SDOperand ResNode;\n";
3588 OS << " Select(ResNode, N);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003589 OS << " SelectDanglingHandles();\n";
3590 OS << " ReplaceHandles();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003591 OS << " ReplaceMap.clear();\n";
Evan Cheng34167212006-02-09 00:37:58 +00003592 OS << " return ResNode;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003593 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003594
Chris Lattner550525e2006-03-24 21:48:51 +00003595 Intrinsics = LoadIntrinsics(Records);
Chris Lattnerca559d02005-09-08 21:03:01 +00003596 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003597 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003598 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003599 ParsePatternFragments(OS);
3600 ParseInstructions();
3601 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003602
Chris Lattnere97603f2005-09-28 19:27:25 +00003603 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003604 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003605 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003606
Chris Lattnere46e17b2005-09-29 19:28:10 +00003607
3608 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3609 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003610 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3611 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003612 std::cerr << "\n";
3613 });
3614
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003615 // At this point, we have full information about the 'Patterns' we need to
3616 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003617 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003618 EmitInstructionSelector(OS);
3619
3620 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3621 E = PatternFragments.end(); I != E; ++I)
3622 delete I->second;
3623 PatternFragments.clear();
3624
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003625 Instructions.clear();
3626}