blob: 7c911bd5be2784c660b088d8432215b0fc9b9a8b [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.
159 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
160 }
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 }
349
Nate Begemanb73628b2005-12-30 00:12:56 +0000350 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
351 assert(hasTypeSet() && "should be handled above!");
352 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
353 if (getExtTypes() == FVTs)
354 return false;
355 setTypes(FVTs);
356 return true;
357 }
358 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
359 assert(hasTypeSet() && "should be handled above!");
Chris Lattner488580c2006-01-28 19:06:51 +0000360 std::vector<unsigned char> FVTs =
361 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
Nate Begemanb73628b2005-12-30 00:12:56 +0000362 if (getExtTypes() == FVTs)
363 return false;
364 setTypes(FVTs);
365 return true;
366 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000367
368 // If we know this is an int or fp type, and we are told it is a specific one,
369 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000370 //
371 // Similarly, we should probably set the type here to the intersection of
372 // {isInt|isFP} and ExtVTs
373 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
374 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
375 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000376 return true;
377 }
378
Chris Lattner1531f202005-10-26 16:59:37 +0000379 if (isLeaf()) {
380 dump();
Evan Chengbcecf332005-12-17 01:19:28 +0000381 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000382 TP.error("Type inference contradiction found in node!");
383 } else {
384 TP.error("Type inference contradiction found in node " +
385 getOperator()->getName() + "!");
386 }
Chris Lattner32707602005-09-08 23:22:48 +0000387 return true; // unreachable
388}
389
390
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000391void TreePatternNode::print(std::ostream &OS) const {
392 if (isLeaf()) {
393 OS << *getLeafValue();
394 } else {
395 OS << "(" << getOperator()->getName();
396 }
397
Nate Begemanb73628b2005-12-30 00:12:56 +0000398 // FIXME: At some point we should handle printing all the value types for
399 // nodes that are multiply typed.
400 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000401 case MVT::Other: OS << ":Other"; break;
402 case MVT::isInt: OS << ":isInt"; break;
403 case MVT::isFP : OS << ":isFP"; break;
404 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Nate Begemanb73628b2005-12-30 00:12:56 +0000405 default: OS << ":" << getTypeNum(0); break;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000406 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000407
408 if (!isLeaf()) {
409 if (getNumChildren() != 0) {
410 OS << " ";
411 getChild(0)->print(OS);
412 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
413 OS << ", ";
414 getChild(i)->print(OS);
415 }
416 }
417 OS << ")";
418 }
419
420 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000421 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000422 if (TransformFn)
423 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000424 if (!getName().empty())
425 OS << ":$" << getName();
426
427}
428void TreePatternNode::dump() const {
429 print(std::cerr);
430}
431
Chris Lattnere46e17b2005-09-29 19:28:10 +0000432/// isIsomorphicTo - Return true if this node is recursively isomorphic to
433/// the specified node. For this comparison, all of the state of the node
434/// is considered, except for the assigned name. Nodes with differing names
435/// that are otherwise identical are considered isomorphic.
436bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
437 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000438 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000439 getPredicateFn() != N->getPredicateFn() ||
440 getTransformFn() != N->getTransformFn())
441 return false;
442
443 if (isLeaf()) {
444 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
445 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
446 return DI->getDef() == NDI->getDef();
447 return getLeafValue() == N->getLeafValue();
448 }
449
450 if (N->getOperator() != getOperator() ||
451 N->getNumChildren() != getNumChildren()) return false;
452 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
453 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
454 return false;
455 return true;
456}
457
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000458/// clone - Make a copy of this tree and all of its children.
459///
460TreePatternNode *TreePatternNode::clone() const {
461 TreePatternNode *New;
462 if (isLeaf()) {
463 New = new TreePatternNode(getLeafValue());
464 } else {
465 std::vector<TreePatternNode*> CChildren;
466 CChildren.reserve(Children.size());
467 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
468 CChildren.push_back(getChild(i)->clone());
469 New = new TreePatternNode(getOperator(), CChildren);
470 }
471 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000472 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000473 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000474 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000475 return New;
476}
477
Chris Lattner32707602005-09-08 23:22:48 +0000478/// SubstituteFormalArguments - Replace the formal arguments in this tree
479/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000480void TreePatternNode::
481SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
482 if (isLeaf()) return;
483
484 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
485 TreePatternNode *Child = getChild(i);
486 if (Child->isLeaf()) {
487 Init *Val = Child->getLeafValue();
488 if (dynamic_cast<DefInit*>(Val) &&
489 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
490 // We found a use of a formal argument, replace it with its value.
491 Child = ArgMap[Child->getName()];
492 assert(Child && "Couldn't find formal argument!");
493 setChild(i, Child);
494 }
495 } else {
496 getChild(i)->SubstituteFormalArguments(ArgMap);
497 }
498 }
499}
500
501
502/// InlinePatternFragments - If this pattern refers to any pattern
503/// fragments, inline them into place, giving us a pattern without any
504/// PatFrag references.
505TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
506 if (isLeaf()) return this; // nothing to do.
507 Record *Op = getOperator();
508
509 if (!Op->isSubClassOf("PatFrag")) {
510 // Just recursively inline children nodes.
511 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
512 setChild(i, getChild(i)->InlinePatternFragments(TP));
513 return this;
514 }
515
516 // Otherwise, we found a reference to a fragment. First, look up its
517 // TreePattern record.
518 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
519
520 // Verify that we are passing the right number of operands.
521 if (Frag->getNumArgs() != Children.size())
522 TP.error("'" + Op->getName() + "' fragment requires " +
523 utostr(Frag->getNumArgs()) + " operands!");
524
Chris Lattner37937092005-09-09 01:15:01 +0000525 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000526
527 // Resolve formal arguments to their actual value.
528 if (Frag->getNumArgs()) {
529 // Compute the map of formal to actual arguments.
530 std::map<std::string, TreePatternNode*> ArgMap;
531 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
532 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
533
534 FragTree->SubstituteFormalArguments(ArgMap);
535 }
536
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000537 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000538 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000539
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000540 // Get a new copy of this fragment to stitch into here.
541 //delete this; // FIXME: implement refcounting!
542 return FragTree;
543}
544
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000545/// getIntrinsicType - Check to see if the specified record has an intrinsic
546/// type which should be applied to it. This infer the type of register
547/// references from the register file information, for example.
548///
Nate Begemanb73628b2005-12-30 00:12:56 +0000549static std::vector<unsigned char> getIntrinsicType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000550 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000551 // Some common return values
552 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
553 std::vector<unsigned char> Other(1, MVT::Other);
554
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000555 // Check to see if this is a register or a register class...
556 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000557 if (NotRegisters)
558 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000559 const CodeGenRegisterClass &RC =
560 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000561 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000562 } else if (R->isSubClassOf("PatFrag")) {
563 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000564 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000565 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000566 if (NotRegisters)
567 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000568 // If the register appears in exactly one regclass, and the regclass has one
569 // value type, use it as the known type.
570 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
571 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
Nate Begemanb73628b2005-12-30 00:12:56 +0000572 return ConvertVTs(RC->getValueTypes());
573 return Unknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000574 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
575 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000576 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000577 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000578 if (NotRegisters)
579 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000580 std::vector<unsigned char>
581 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
582 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000583 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000584 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000585 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000586 }
587
588 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000589 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000590}
591
Chris Lattner32707602005-09-08 23:22:48 +0000592/// ApplyTypeConstraints - Apply all of the type constraints relevent to
593/// this node and its children in the tree. This returns true if it makes a
594/// change, false otherwise. If a type contradiction is found, throw an
595/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000596bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000597 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000598 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000599 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000600 // If it's a regclass or something else known, include the type.
601 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
602 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000603 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
604 // Int inits are always integers. :)
605 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
606
607 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000608 // At some point, it may make sense for this tree pattern to have
609 // multiple types. Assert here that it does not, so we revisit this
610 // code when appropriate.
611 assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
612
613 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
Chris Lattner465c7372005-11-03 05:46:11 +0000614 // Make sure that the value is representable for this type.
615 if (Size < 32) {
616 int Val = (II->getValue() << (32-Size)) >> (32-Size);
617 if (Val != II->getValue())
618 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
619 "' is out of range for type 'MVT::" +
Nate Begemanb73628b2005-12-30 00:12:56 +0000620 getEnumName(getTypeNum(0)) + "'!");
Chris Lattner465c7372005-11-03 05:46:11 +0000621 }
622 }
623
624 return MadeChange;
625 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000626 return false;
627 }
Chris Lattner32707602005-09-08 23:22:48 +0000628
629 // special handling for set, which isn't really an SDNode.
630 if (getOperator()->getName() == "set") {
631 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000632 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
633 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000634
635 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000636 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
637 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000638 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
639 return MadeChange;
Chris Lattner5a1df382006-03-24 23:10:39 +0000640 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
641 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
642 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
643 unsigned IID =
644 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
645 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
646 bool MadeChange = false;
647
648 // Apply the result type to the node.
649 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
650
651 if (getNumChildren() != Int.ArgVTs.size())
Chris Lattner2c4e65d2006-03-27 22:21:18 +0000652 TP.error("Intrinsic '" + Int.Name + "' expects " +
Chris Lattner5a1df382006-03-24 23:10:39 +0000653 utostr(Int.ArgVTs.size()-1) + " operands, not " +
654 utostr(getNumChildren()-1) + " operands!");
655
656 // Apply type info to the intrinsic ID.
657 MVT::ValueType PtrTy = ISE.getTargetInfo().getPointerType();
658 MadeChange |= getChild(0)->UpdateNodeType(PtrTy, TP);
659
660 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
661 MVT::ValueType OpVT = Int.ArgVTs[i];
662 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
663 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
664 }
665 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000666 } else if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000667 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
Chris Lattnerabbb6052005-09-15 21:42:00 +0000668
669 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
670 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000671 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000672 // Branch, etc. do not produce results and top-level forms in instr pattern
673 // must have void types.
674 if (NI.getNumResults() == 0)
675 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000676 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000677 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000678 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000679 bool MadeChange = false;
680 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000681
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000682 assert(NumResults <= 1 &&
683 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000684 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000685 if (NumResults == 0) {
686 MadeChange = UpdateNodeType(MVT::isVoid, TP);
687 } else {
688 Record *ResultNode = Inst.getResult(0);
689 assert(ResultNode->isSubClassOf("RegisterClass") &&
690 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000691
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000692 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000693 ISE.getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000694 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000695 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000696
697 if (getNumChildren() != Inst.getNumOperands())
698 TP.error("Instruction '" + getOperator()->getName() + " expects " +
699 utostr(Inst.getNumOperands()) + " operands, not " +
700 utostr(getNumChildren()) + " operands!");
701 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000702 Record *OperandNode = Inst.getOperand(i);
703 MVT::ValueType VT;
704 if (OperandNode->isSubClassOf("RegisterClass")) {
705 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000706 ISE.getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000707 //VT = RC.getValueTypeNum(0);
708 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
709 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000710 } else if (OperandNode->isSubClassOf("Operand")) {
711 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000712 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000713 } else {
714 assert(0 && "Unknown operand type!");
715 abort();
716 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000717 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000718 }
719 return MadeChange;
720 } else {
721 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
722
Evan Chengf26ba692006-03-20 08:09:17 +0000723 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000724 if (getNumChildren() != 1)
725 TP.error("Node transform '" + getOperator()->getName() +
726 "' requires one operand!");
Chris Lattner4e2f54d2006-03-21 06:42:58 +0000727
728 // If either the output or input of the xform does not have exact
729 // type info. We assume they must be the same. Otherwise, it is perfectly
730 // legal to transform from one type to a completely different type.
731 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Evan Chengf26ba692006-03-20 08:09:17 +0000732 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
733 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
734 return MadeChange;
735 }
736 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000737 }
Chris Lattner32707602005-09-08 23:22:48 +0000738}
739
Chris Lattnere97603f2005-09-28 19:27:25 +0000740/// canPatternMatch - If it is impossible for this pattern to match on this
741/// target, fill in Reason and return false. Otherwise, return true. This is
742/// used as a santity check for .td files (to prevent people from writing stuff
743/// that can never possibly work), and to prevent the pattern permuter from
744/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000745bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000746 if (isLeaf()) return true;
747
748 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
749 if (!getChild(i)->canPatternMatch(Reason, ISE))
750 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000751
Chris Lattner550525e2006-03-24 21:48:51 +0000752 // If this is an intrinsic, handle cases that would make it not match. For
753 // example, if an operand is required to be an immediate.
754 if (getOperator()->isSubClassOf("Intrinsic")) {
755 // TODO:
756 return true;
757 }
758
Chris Lattnere97603f2005-09-28 19:27:25 +0000759 // If this node is a commutative operator, check that the LHS isn't an
760 // immediate.
761 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
762 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
763 // Scan all of the operands of the node and make sure that only the last one
764 // is a constant node.
765 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
766 if (!getChild(i)->isLeaf() &&
767 getChild(i)->getOperator()->getName() == "imm") {
768 Reason = "Immediate value must be on the RHS of commutative operators!";
769 return false;
770 }
771 }
772
773 return true;
774}
Chris Lattner32707602005-09-08 23:22:48 +0000775
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000776//===----------------------------------------------------------------------===//
777// TreePattern implementation
778//
779
Chris Lattneredbd8712005-10-21 01:19:59 +0000780TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000781 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000782 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000783 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
784 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000785}
786
Chris Lattneredbd8712005-10-21 01:19:59 +0000787TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000788 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000789 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000790 Trees.push_back(ParseTreePattern(Pat));
791}
792
Chris Lattneredbd8712005-10-21 01:19:59 +0000793TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000794 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000795 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000796 Trees.push_back(Pat);
797}
798
799
800
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000801void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000802 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000803 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000804}
805
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000806TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
807 Record *Operator = Dag->getNodeType();
808
809 if (Operator->isSubClassOf("ValueType")) {
810 // If the operator is a ValueType, then this must be "type cast" of a leaf
811 // node.
812 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000813 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000814
815 Init *Arg = Dag->getArg(0);
816 TreePatternNode *New;
817 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000818 Record *R = DI->getDef();
819 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
820 Dag->setArg(0, new DagInit(R,
821 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000822 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000823 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000824 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000825 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
826 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000827 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
828 New = new TreePatternNode(II);
829 if (!Dag->getArgName(0).empty())
830 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000831 } else {
832 Arg->dump();
833 error("Unknown leaf value for tree pattern!");
834 return 0;
835 }
836
Chris Lattner32707602005-09-08 23:22:48 +0000837 // Apply the type cast.
838 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000839 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000840 return New;
841 }
842
843 // Verify that this is something that makes sense for an operator.
844 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000845 !Operator->isSubClassOf("Instruction") &&
846 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner550525e2006-03-24 21:48:51 +0000847 !Operator->isSubClassOf("Intrinsic") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000848 Operator->getName() != "set")
849 error("Unrecognized node '" + Operator->getName() + "'!");
850
Chris Lattneredbd8712005-10-21 01:19:59 +0000851 // Check to see if this is something that is illegal in an input pattern.
852 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
Chris Lattner5a1df382006-03-24 23:10:39 +0000853 Operator->isSubClassOf("SDNodeXForm")))
Chris Lattneredbd8712005-10-21 01:19:59 +0000854 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
855
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000856 std::vector<TreePatternNode*> Children;
857
858 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
859 Init *Arg = Dag->getArg(i);
860 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
861 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000862 if (Children.back()->getName().empty())
863 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000864 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
865 Record *R = DefI->getDef();
866 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
867 // TreePatternNode if its own.
868 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
869 Dag->setArg(i, new DagInit(R,
870 std::vector<std::pair<Init*, std::string> >()));
871 --i; // Revisit this node...
872 } else {
873 TreePatternNode *Node = new TreePatternNode(DefI);
874 Node->setName(Dag->getArgName(i));
875 Children.push_back(Node);
876
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000877 // Input argument?
878 if (R->getName() == "node") {
879 if (Dag->getArgName(i).empty())
880 error("'node' argument requires a name to match with operand list");
881 Args.push_back(Dag->getArgName(i));
882 }
883 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000884 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
885 TreePatternNode *Node = new TreePatternNode(II);
886 if (!Dag->getArgName(i).empty())
887 error("Constant int argument should not have a name!");
888 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000889 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000890 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000891 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000892 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000893 error("Unknown leaf value for tree pattern!");
894 }
895 }
896
Chris Lattner5a1df382006-03-24 23:10:39 +0000897 // If the operator is an intrinsic, then this is just syntactic sugar for for
898 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
899 // convert the intrinsic name to a number.
900 if (Operator->isSubClassOf("Intrinsic")) {
901 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
902 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
903
904 // If this intrinsic returns void, it must have side-effects and thus a
905 // chain.
906 if (Int.ArgVTs[0] == MVT::isVoid) {
907 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
908 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
909 // Has side-effects, requires chain.
910 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
911 } else {
912 // Otherwise, no chain.
913 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
914 }
915
916 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
917 Children.insert(Children.begin(), IIDNode);
918 }
919
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000920 return new TreePatternNode(Operator, Children);
921}
922
Chris Lattner32707602005-09-08 23:22:48 +0000923/// InferAllTypes - Infer/propagate as many types throughout the expression
924/// patterns as possible. Return true if all types are infered, false
925/// otherwise. Throw an exception if a type contradiction is found.
926bool TreePattern::InferAllTypes() {
927 bool MadeChange = true;
928 while (MadeChange) {
929 MadeChange = false;
930 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000931 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000932 }
933
934 bool HasUnresolvedTypes = false;
935 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
936 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
937 return !HasUnresolvedTypes;
938}
939
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000940void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000941 OS << getRecord()->getName();
942 if (!Args.empty()) {
943 OS << "(" << Args[0];
944 for (unsigned i = 1, e = Args.size(); i != e; ++i)
945 OS << ", " << Args[i];
946 OS << ")";
947 }
948 OS << ": ";
949
950 if (Trees.size() > 1)
951 OS << "[\n";
952 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
953 OS << "\t";
954 Trees[i]->print(OS);
955 OS << "\n";
956 }
957
958 if (Trees.size() > 1)
959 OS << "]\n";
960}
961
962void TreePattern::dump() const { print(std::cerr); }
963
964
965
966//===----------------------------------------------------------------------===//
967// DAGISelEmitter implementation
968//
969
Chris Lattnerca559d02005-09-08 21:03:01 +0000970// Parse all of the SDNode definitions for the target, populating SDNodes.
971void DAGISelEmitter::ParseNodeInfo() {
972 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
973 while (!Nodes.empty()) {
974 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
975 Nodes.pop_back();
976 }
Chris Lattner5a1df382006-03-24 23:10:39 +0000977
978 // Get the buildin intrinsic nodes.
979 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
980 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
981 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
Chris Lattnerca559d02005-09-08 21:03:01 +0000982}
983
Chris Lattner24eeeb82005-09-13 21:51:00 +0000984/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
985/// map, and emit them to the file as functions.
986void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
987 OS << "\n// Node transformations.\n";
988 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
989 while (!Xforms.empty()) {
990 Record *XFormNode = Xforms.back();
991 Record *SDNode = XFormNode->getValueAsDef("Opcode");
992 std::string Code = XFormNode->getValueAsCode("XFormFunction");
993 SDNodeXForms.insert(std::make_pair(XFormNode,
994 std::make_pair(SDNode, Code)));
995
Chris Lattner1048b7a2005-09-13 22:03:37 +0000996 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000997 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
998 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
999
Chris Lattner1048b7a2005-09-13 22:03:37 +00001000 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +00001001 << "(SDNode *" << C2 << ") {\n";
1002 if (ClassName != "SDNode")
1003 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1004 OS << Code << "\n}\n";
1005 }
1006
1007 Xforms.pop_back();
1008 }
1009}
1010
Evan Cheng0fc71982005-12-08 02:00:36 +00001011void DAGISelEmitter::ParseComplexPatterns() {
1012 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1013 while (!AMs.empty()) {
1014 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1015 AMs.pop_back();
1016 }
1017}
Chris Lattner24eeeb82005-09-13 21:51:00 +00001018
1019
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001020/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1021/// file, building up the PatternFragments map. After we've collected them all,
1022/// inline fragments together as necessary, so that there are no references left
1023/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001024///
1025/// This also emits all of the predicate functions to the output file.
1026///
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001027void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001028 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1029
1030 // First step, parse all of the fragments and emit predicate functions.
1031 OS << "\n// Predicate functions.\n";
1032 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001033 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +00001034 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001035 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +00001036
1037 // Validate the argument list, converting it to map, to discard duplicates.
1038 std::vector<std::string> &Args = P->getArgList();
1039 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1040
1041 if (OperandsMap.count(""))
1042 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1043
1044 // Parse the operands list.
1045 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1046 if (OpsList->getNodeType()->getName() != "ops")
1047 P->error("Operands list should start with '(ops ... '!");
1048
1049 // Copy over the arguments.
1050 Args.clear();
1051 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1052 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1053 static_cast<DefInit*>(OpsList->getArg(j))->
1054 getDef()->getName() != "node")
1055 P->error("Operands list should all be 'node' values.");
1056 if (OpsList->getArgName(j).empty())
1057 P->error("Operands list should have names for each operand!");
1058 if (!OperandsMap.count(OpsList->getArgName(j)))
1059 P->error("'" + OpsList->getArgName(j) +
1060 "' does not occur in pattern or was multiply specified!");
1061 OperandsMap.erase(OpsList->getArgName(j));
1062 Args.push_back(OpsList->getArgName(j));
1063 }
1064
1065 if (!OperandsMap.empty())
1066 P->error("Operands list does not contain an entry for operand '" +
1067 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001068
1069 // If there is a code init for this fragment, emit the predicate code and
1070 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001071 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1072 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +00001073 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001074 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +00001075 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001076 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1077
Chris Lattner1048b7a2005-09-13 22:03:37 +00001078 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001079 << "(SDNode *" << C2 << ") {\n";
1080 if (ClassName != "SDNode")
1081 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +00001082 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001083 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001084 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001085
1086 // If there is a node transformation corresponding to this, keep track of
1087 // it.
1088 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1089 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001090 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001091 }
1092
1093 OS << "\n\n";
1094
1095 // Now that we've parsed all of the tree fragments, do a closure on them so
1096 // that there are not references to PatFrags left inside of them.
1097 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1098 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001099 TreePattern *ThePat = I->second;
1100 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001101
Chris Lattner32707602005-09-08 23:22:48 +00001102 // Infer as many types as possible. Don't worry about it if we don't infer
1103 // all of them, some may depend on the inputs of the pattern.
1104 try {
1105 ThePat->InferAllTypes();
1106 } catch (...) {
1107 // If this pattern fragment is not supported by this target (no types can
1108 // satisfy its constraints), just ignore it. If the bogus pattern is
1109 // actually used by instructions, the type consistency error will be
1110 // reported there.
1111 }
1112
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001113 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001114 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001115 }
1116}
1117
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001118/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001119/// instruction input. Return true if this is a real use.
1120static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001121 std::map<std::string, TreePatternNode*> &InstInputs,
1122 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001123 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001124 if (Pat->getName().empty()) {
1125 if (Pat->isLeaf()) {
1126 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1127 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1128 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001129 else if (DI && DI->getDef()->isSubClassOf("Register"))
1130 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001131 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001132 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001133 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001134
1135 Record *Rec;
1136 if (Pat->isLeaf()) {
1137 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1138 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1139 Rec = DI->getDef();
1140 } else {
1141 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1142 Rec = Pat->getOperator();
1143 }
1144
Evan Cheng01f318b2005-12-14 02:21:57 +00001145 // SRCVALUE nodes are ignored.
1146 if (Rec->getName() == "srcvalue")
1147 return false;
1148
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001149 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1150 if (!Slot) {
1151 Slot = Pat;
1152 } else {
1153 Record *SlotRec;
1154 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001155 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001156 } else {
1157 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1158 SlotRec = Slot->getOperator();
1159 }
1160
1161 // Ensure that the inputs agree if we've already seen this input.
1162 if (Rec != SlotRec)
1163 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001164 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001165 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1166 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001167 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001168}
1169
1170/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1171/// part of "I", the instruction), computing the set of inputs and outputs of
1172/// the pattern. Report errors if we see anything naughty.
1173void DAGISelEmitter::
1174FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1175 std::map<std::string, TreePatternNode*> &InstInputs,
Chris Lattner947604b2006-03-24 21:52:20 +00001176 std::map<std::string, TreePatternNode*>&InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001177 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001178 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001179 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001180 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001181 if (!isUse && Pat->getTransformFn())
1182 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001183 return;
1184 } else if (Pat->getOperator()->getName() != "set") {
1185 // If this is not a set, verify that the children nodes are not void typed,
1186 // and recurse.
1187 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001188 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001189 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001190 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001191 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001192 }
1193
1194 // If this is a non-leaf node with no children, treat it basically as if
1195 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001196 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001197 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001198 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001199
Chris Lattnerf1311842005-09-14 23:05:13 +00001200 if (!isUse && Pat->getTransformFn())
1201 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001202 return;
1203 }
1204
1205 // Otherwise, this is a set, validate and collect instruction results.
1206 if (Pat->getNumChildren() == 0)
1207 I->error("set requires operands!");
1208 else if (Pat->getNumChildren() & 1)
1209 I->error("set requires an even number of operands");
1210
Chris Lattnerf1311842005-09-14 23:05:13 +00001211 if (Pat->getTransformFn())
1212 I->error("Cannot specify a transform function on a set node!");
1213
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001214 // Check the set destinations.
1215 unsigned NumValues = Pat->getNumChildren()/2;
1216 for (unsigned i = 0; i != NumValues; ++i) {
1217 TreePatternNode *Dest = Pat->getChild(i);
1218 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001219 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001220
1221 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1222 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001223 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001224
Evan Chengbcecf332005-12-17 01:19:28 +00001225 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1226 if (Dest->getName().empty())
1227 I->error("set destination must have a name!");
1228 if (InstResults.count(Dest->getName()))
1229 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001230 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001231 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001232 InstImpResults.push_back(Val->getDef());
1233 } else {
1234 I->error("set destination should be a register!");
1235 }
1236
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001237 // Verify and collect info from the computation.
1238 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001239 InstInputs, InstResults,
1240 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001241 }
1242}
1243
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001244/// ParseInstructions - Parse all of the instructions, inlining and resolving
1245/// any fragments involved. This populates the Instructions list with fully
1246/// resolved instructions.
1247void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001248 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1249
1250 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001251 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001252
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001253 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1254 LI = Instrs[i]->getValueAsListInit("Pattern");
1255
1256 // If there is no pattern, only collect minimal information about the
1257 // instruction for its operand list. We have to assume that there is one
1258 // result, as we have no detailed info.
1259 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001260 std::vector<Record*> Results;
1261 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001262
1263 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001264
Evan Cheng3a217f32005-12-22 02:35:21 +00001265 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001266 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001267 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001268 // These produce no results
1269 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1270 Operands.push_back(InstInfo.OperandList[j].Rec);
1271 } else {
1272 // Assume the first operand is the result.
1273 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001274
Evan Cheng3a217f32005-12-22 02:35:21 +00001275 // The rest are inputs.
1276 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1277 Operands.push_back(InstInfo.OperandList[j].Rec);
1278 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001279 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001280
1281 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001282 std::vector<Record*> ImpResults;
1283 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001284 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001285 DAGInstruction(0, Results, Operands, ImpResults,
1286 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001287 continue; // no pattern.
1288 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001289
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001290 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001291 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001292 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001293 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001294
Chris Lattner95f6b762005-09-08 23:26:30 +00001295 // Infer as many types as possible. If we cannot infer all of them, we can
1296 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001297 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001298 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001299
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001300 // InstInputs - Keep track of all of the inputs of the instruction, along
1301 // with the record they are declared as.
1302 std::map<std::string, TreePatternNode*> InstInputs;
1303
1304 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001305 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001306 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001307
1308 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001309 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001310
Chris Lattner1f39e292005-09-14 00:09:24 +00001311 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001312 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001313 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1314 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001315 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001316 I->error("Top-level forms in instruction pattern should have"
1317 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001318
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001319 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001320 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001321 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001322 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001323
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001324 // Now that we have inputs and outputs of the pattern, inspect the operands
1325 // list for the instruction. This determines the order that operands are
1326 // added to the machine instruction the node corresponds to.
1327 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001328
1329 // Parse the operands list from the (ops) list, validating it.
1330 std::vector<std::string> &Args = I->getArgList();
1331 assert(Args.empty() && "Args list should still be empty here!");
1332 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1333
1334 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001335 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001336 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001337 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001338 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001339 I->error("'" + InstResults.begin()->first +
1340 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001341 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001342
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001343 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001344 TreePatternNode *RNode = InstResults[OpName];
Chris Lattner5c4c7742006-03-25 22:12:44 +00001345 if (RNode == 0)
1346 I->error("Operand $" + OpName + " does not exist in operand list!");
1347
Evan Cheng420132e2006-03-20 06:04:09 +00001348 if (i == 0)
1349 Res0Node = RNode;
1350 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001351 if (R == 0)
1352 I->error("Operand $" + OpName + " should be a set destination: all "
1353 "outputs must occur before inputs in operand list!");
1354
1355 if (CGI.OperandList[i].Rec != R)
1356 I->error("Operand $" + OpName + " class mismatch!");
1357
Chris Lattnerae6d8282005-09-15 21:51:12 +00001358 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001359 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001360
Chris Lattner39e8af92005-09-14 18:19:25 +00001361 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001362 InstResults.erase(OpName);
1363 }
1364
Chris Lattner0b592252005-09-14 21:59:34 +00001365 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1366 // the copy while we're checking the inputs.
1367 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001368
1369 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001370 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001371 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1372 const std::string &OpName = CGI.OperandList[i].Name;
1373 if (OpName.empty())
1374 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1375
Chris Lattner0b592252005-09-14 21:59:34 +00001376 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001377 I->error("Operand $" + OpName +
1378 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001379 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001380 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001381
1382 if (InVal->isLeaf() &&
1383 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1384 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001385 if (CGI.OperandList[i].Rec != InRec &&
1386 !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001387 I->error("Operand $" + OpName + "'s register class disagrees"
1388 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001389 }
1390 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001391
Chris Lattner2175c182005-09-14 23:01:59 +00001392 // Construct the result for the dest-pattern operand list.
1393 TreePatternNode *OpNode = InVal->clone();
1394
1395 // No predicate is useful on the result.
1396 OpNode->setPredicateFn("");
1397
1398 // Promote the xform function to be an explicit node if set.
1399 if (Record *Xform = OpNode->getTransformFn()) {
1400 OpNode->setTransformFn(0);
1401 std::vector<TreePatternNode*> Children;
1402 Children.push_back(OpNode);
1403 OpNode = new TreePatternNode(Xform, Children);
1404 }
1405
1406 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001407 }
1408
Chris Lattner0b592252005-09-14 21:59:34 +00001409 if (!InstInputsCheck.empty())
1410 I->error("Input operand $" + InstInputsCheck.begin()->first +
1411 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001412
1413 TreePatternNode *ResultPattern =
1414 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001415 // Copy fully inferred output node type to instruction result pattern.
1416 if (NumResults > 0)
1417 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001418
1419 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001420 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001421 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1422
1423 // Use a temporary tree pattern to infer all types and make sure that the
1424 // constructed result is correct. This depends on the instruction already
1425 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001426 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001427 Temp.InferAllTypes();
1428
1429 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1430 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001431
Chris Lattner32707602005-09-08 23:22:48 +00001432 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001433 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001434
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001435 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001436 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1437 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001438 DAGInstruction &TheInst = II->second;
1439 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001440 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001441
Chris Lattner1f39e292005-09-14 00:09:24 +00001442 if (I->getNumTrees() != 1) {
1443 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1444 continue;
1445 }
1446 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001447 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001448 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001449 if (Pattern->getNumChildren() != 2)
1450 continue; // Not a set of a single value (not handled so far)
1451
1452 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001453 } else{
1454 // Not a set (store or something?)
1455 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001456 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001457
1458 std::string Reason;
1459 if (!SrcPattern->canPatternMatch(Reason, *this))
1460 I->error("Instruction can never match: " + Reason);
1461
Evan Cheng58e84a62005-12-14 22:02:59 +00001462 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001463 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001464 PatternsToMatch.
1465 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1466 SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001467 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001468}
1469
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001470void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001471 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001472
Chris Lattnerabbb6052005-09-15 21:42:00 +00001473 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001474 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001475 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001476
Chris Lattnerabbb6052005-09-15 21:42:00 +00001477 // Inline pattern fragments into it.
1478 Pattern->InlinePatternFragments();
1479
1480 // Infer as many types as possible. If we cannot infer all of them, we can
1481 // never do anything with this pattern: report it to the user.
1482 if (!Pattern->InferAllTypes())
1483 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001484
1485 // Validate that the input pattern is correct.
1486 {
1487 std::map<std::string, TreePatternNode*> InstInputs;
Evan Cheng420132e2006-03-20 06:04:09 +00001488 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001489 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001490 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001491 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001492 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001493 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001494 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001495
1496 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1497 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001498
1499 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001500 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001501
1502 // Inline pattern fragments into it.
1503 Result->InlinePatternFragments();
1504
1505 // Infer as many types as possible. If we cannot infer all of them, we can
1506 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001507 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001508 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001509
1510 if (Result->getNumTrees() != 1)
1511 Result->error("Cannot handle instructions producing instructions "
1512 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001513
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001514 // Promote the xform function to be an explicit node if set.
1515 std::vector<TreePatternNode*> ResultNodeOperands;
1516 TreePatternNode *DstPattern = Result->getOnlyTree();
1517 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1518 TreePatternNode *OpNode = DstPattern->getChild(ii);
1519 if (Record *Xform = OpNode->getTransformFn()) {
1520 OpNode->setTransformFn(0);
1521 std::vector<TreePatternNode*> Children;
1522 Children.push_back(OpNode);
1523 OpNode = new TreePatternNode(Xform, Children);
1524 }
1525 ResultNodeOperands.push_back(OpNode);
1526 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00001527 DstPattern = Result->getOnlyTree();
1528 if (!DstPattern->isLeaf())
1529 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1530 ResultNodeOperands);
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001531 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1532 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1533 Temp.InferAllTypes();
1534
Chris Lattnere97603f2005-09-28 19:27:25 +00001535 std::string Reason;
1536 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1537 Pattern->error("Pattern can never match: " + Reason);
1538
Evan Cheng58e84a62005-12-14 22:02:59 +00001539 PatternsToMatch.
1540 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1541 Pattern->getOnlyTree(),
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001542 Temp.getOnlyTree()));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001543 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001544}
1545
Chris Lattnere46e17b2005-09-29 19:28:10 +00001546/// CombineChildVariants - Given a bunch of permutations of each child of the
1547/// 'operator' node, put them together in all possible ways.
1548static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001549 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001550 std::vector<TreePatternNode*> &OutVariants,
1551 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001552 // Make sure that each operand has at least one variant to choose from.
1553 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1554 if (ChildVariants[i].empty())
1555 return;
1556
Chris Lattnere46e17b2005-09-29 19:28:10 +00001557 // The end result is an all-pairs construction of the resultant pattern.
1558 std::vector<unsigned> Idxs;
1559 Idxs.resize(ChildVariants.size());
1560 bool NotDone = true;
1561 while (NotDone) {
1562 // Create the variant and add it to the output list.
1563 std::vector<TreePatternNode*> NewChildren;
1564 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1565 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1566 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1567
1568 // Copy over properties.
1569 R->setName(Orig->getName());
1570 R->setPredicateFn(Orig->getPredicateFn());
1571 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001572 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001573
1574 // If this pattern cannot every match, do not include it as a variant.
1575 std::string ErrString;
1576 if (!R->canPatternMatch(ErrString, ISE)) {
1577 delete R;
1578 } else {
1579 bool AlreadyExists = false;
1580
1581 // Scan to see if this pattern has already been emitted. We can get
1582 // duplication due to things like commuting:
1583 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1584 // which are the same pattern. Ignore the dups.
1585 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1586 if (R->isIsomorphicTo(OutVariants[i])) {
1587 AlreadyExists = true;
1588 break;
1589 }
1590
1591 if (AlreadyExists)
1592 delete R;
1593 else
1594 OutVariants.push_back(R);
1595 }
1596
1597 // Increment indices to the next permutation.
1598 NotDone = false;
1599 // Look for something we can increment without causing a wrap-around.
1600 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1601 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1602 NotDone = true; // Found something to increment.
1603 break;
1604 }
1605 Idxs[IdxsIdx] = 0;
1606 }
1607 }
1608}
1609
Chris Lattneraf302912005-09-29 22:36:54 +00001610/// CombineChildVariants - A helper function for binary operators.
1611///
1612static void CombineChildVariants(TreePatternNode *Orig,
1613 const std::vector<TreePatternNode*> &LHS,
1614 const std::vector<TreePatternNode*> &RHS,
1615 std::vector<TreePatternNode*> &OutVariants,
1616 DAGISelEmitter &ISE) {
1617 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1618 ChildVariants.push_back(LHS);
1619 ChildVariants.push_back(RHS);
1620 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1621}
1622
1623
1624static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1625 std::vector<TreePatternNode *> &Children) {
1626 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1627 Record *Operator = N->getOperator();
1628
1629 // Only permit raw nodes.
1630 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1631 N->getTransformFn()) {
1632 Children.push_back(N);
1633 return;
1634 }
1635
1636 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1637 Children.push_back(N->getChild(0));
1638 else
1639 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1640
1641 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1642 Children.push_back(N->getChild(1));
1643 else
1644 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1645}
1646
Chris Lattnere46e17b2005-09-29 19:28:10 +00001647/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1648/// the (potentially recursive) pattern by using algebraic laws.
1649///
1650static void GenerateVariantsOf(TreePatternNode *N,
1651 std::vector<TreePatternNode*> &OutVariants,
1652 DAGISelEmitter &ISE) {
1653 // We cannot permute leaves.
1654 if (N->isLeaf()) {
1655 OutVariants.push_back(N);
1656 return;
1657 }
1658
1659 // Look up interesting info about the node.
Chris Lattner5a1df382006-03-24 23:10:39 +00001660 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001661
1662 // If this node is associative, reassociate.
Chris Lattner5a1df382006-03-24 23:10:39 +00001663 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
Chris Lattneraf302912005-09-29 22:36:54 +00001664 // Reassociate by pulling together all of the linked operators
1665 std::vector<TreePatternNode*> MaximalChildren;
1666 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1667
1668 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1669 // permutations.
1670 if (MaximalChildren.size() == 3) {
1671 // Find the variants of all of our maximal children.
1672 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1673 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1674 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1675 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1676
1677 // There are only two ways we can permute the tree:
1678 // (A op B) op C and A op (B op C)
1679 // Within these forms, we can also permute A/B/C.
1680
1681 // Generate legal pair permutations of A/B/C.
1682 std::vector<TreePatternNode*> ABVariants;
1683 std::vector<TreePatternNode*> BAVariants;
1684 std::vector<TreePatternNode*> ACVariants;
1685 std::vector<TreePatternNode*> CAVariants;
1686 std::vector<TreePatternNode*> BCVariants;
1687 std::vector<TreePatternNode*> CBVariants;
1688 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1689 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1690 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1691 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1692 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1693 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1694
1695 // Combine those into the result: (x op x) op x
1696 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1697 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1698 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1699 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1700 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1701 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1702
1703 // Combine those into the result: x op (x op x)
1704 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1705 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1706 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1707 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1708 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1709 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1710 return;
1711 }
1712 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001713
1714 // Compute permutations of all children.
1715 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1716 ChildVariants.resize(N->getNumChildren());
1717 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1718 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1719
1720 // Build all permutations based on how the children were formed.
1721 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1722
1723 // If this node is commutative, consider the commuted order.
Chris Lattner5a1df382006-03-24 23:10:39 +00001724 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001725 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001726 // Consider the commuted order.
1727 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1728 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001729 }
1730}
1731
1732
Chris Lattnere97603f2005-09-28 19:27:25 +00001733// GenerateVariants - Generate variants. For example, commutative patterns can
1734// match multiple ways. Add them to PatternsToMatch as well.
1735void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001736
1737 DEBUG(std::cerr << "Generating instruction variants.\n");
1738
1739 // Loop over all of the patterns we've collected, checking to see if we can
1740 // generate variants of the instruction, through the exploitation of
1741 // identities. This permits the target to provide agressive matching without
1742 // the .td file having to contain tons of variants of instructions.
1743 //
1744 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1745 // intentionally do not reconsider these. Any variants of added patterns have
1746 // already been added.
1747 //
1748 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1749 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001750 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001751
1752 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001753 Variants.erase(Variants.begin()); // Remove the original pattern.
1754
1755 if (Variants.empty()) // No variants for this pattern.
1756 continue;
1757
1758 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001759 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001760 std::cerr << "\n");
1761
1762 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1763 TreePatternNode *Variant = Variants[v];
1764
1765 DEBUG(std::cerr << " VAR#" << v << ": ";
1766 Variant->dump();
1767 std::cerr << "\n");
1768
1769 // Scan to see if an instruction or explicit pattern already matches this.
1770 bool AlreadyExists = false;
1771 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1772 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001773 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001774 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1775 AlreadyExists = true;
1776 break;
1777 }
1778 }
1779 // If we already have it, ignore the variant.
1780 if (AlreadyExists) continue;
1781
1782 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001783 PatternsToMatch.
1784 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1785 Variant, PatternsToMatch[i].getDstPattern()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001786 }
1787
1788 DEBUG(std::cerr << "\n");
1789 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001790}
1791
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001792
Evan Cheng0fc71982005-12-08 02:00:36 +00001793// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1794// ComplexPattern.
1795static bool NodeIsComplexPattern(TreePatternNode *N)
1796{
1797 return (N->isLeaf() &&
1798 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1799 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1800 isSubClassOf("ComplexPattern"));
1801}
1802
1803// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1804// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1805static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1806 DAGISelEmitter &ISE)
1807{
1808 if (N->isLeaf() &&
1809 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1810 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1811 isSubClassOf("ComplexPattern")) {
1812 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1813 ->getDef());
1814 }
1815 return NULL;
1816}
1817
Chris Lattner05814af2005-09-28 17:57:56 +00001818/// getPatternSize - Return the 'size' of this pattern. We want to match large
1819/// patterns before small ones. This is used to determine the size of a
1820/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001821static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng4a7c2842006-01-06 22:19:44 +00001822 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1823 isExtFloatingPointInVTs(P->getExtTypes()) ||
1824 P->getExtTypeNum(0) == MVT::isVoid ||
1825 P->getExtTypeNum(0) == MVT::Flag &&
1826 "Not a valid pattern node to size!");
Evan Chenge1050d62006-01-06 02:30:23 +00001827 unsigned Size = 2; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00001828 // If the root node is a ConstantSDNode, increases its size.
1829 // e.g. (set R32:$dst, 0).
1830 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1831 Size++;
Evan Cheng0fc71982005-12-08 02:00:36 +00001832
1833 // FIXME: This is a hack to statically increase the priority of patterns
1834 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1835 // Later we can allow complexity / cost for each pattern to be (optionally)
1836 // specified. To get best possible pattern match we'll need to dynamically
1837 // calculate the complexity of all patterns a dag can potentially map to.
1838 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1839 if (AM)
Evan Cheng4a7c2842006-01-06 22:19:44 +00001840 Size += AM->getNumOperands() * 2;
Chris Lattner3e179802006-02-03 18:06:02 +00001841
1842 // If this node has some predicate function that must match, it adds to the
1843 // complexity of this node.
1844 if (!P->getPredicateFn().empty())
1845 ++Size;
1846
Chris Lattner05814af2005-09-28 17:57:56 +00001847 // Count children in the count if they are also nodes.
1848 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1849 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001850 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001851 Size += getPatternSize(Child, ISE);
1852 else if (Child->isLeaf()) {
1853 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner3e179802006-02-03 18:06:02 +00001854 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
Evan Cheng4a7c2842006-01-06 22:19:44 +00001855 else if (NodeIsComplexPattern(Child))
1856 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00001857 else if (!Child->getPredicateFn().empty())
1858 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001859 }
Chris Lattner05814af2005-09-28 17:57:56 +00001860 }
1861
1862 return Size;
1863}
1864
1865/// getResultPatternCost - Compute the number of instructions for this pattern.
1866/// This is a temporary hack. We should really include the instruction
1867/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00001868static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00001869 if (P->isLeaf()) return 0;
1870
Evan Chengfbad7082006-02-18 02:33:09 +00001871 unsigned Cost = 0;
1872 Record *Op = P->getOperator();
1873 if (Op->isSubClassOf("Instruction")) {
1874 Cost++;
1875 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1876 if (II.usesCustomDAGSchedInserter)
1877 Cost += 10;
1878 }
Chris Lattner05814af2005-09-28 17:57:56 +00001879 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00001880 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001881 return Cost;
1882}
1883
1884// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1885// In particular, we want to match maximal patterns first and lowest cost within
1886// a particular complexity first.
1887struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001888 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1889 DAGISelEmitter &ISE;
1890
Evan Cheng58e84a62005-12-14 22:02:59 +00001891 bool operator()(PatternToMatch *LHS,
1892 PatternToMatch *RHS) {
1893 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1894 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001895 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1896 if (LHSSize < RHSSize) return false;
1897
1898 // If the patterns have equal complexity, compare generated instruction cost
Evan Chengfbad7082006-02-18 02:33:09 +00001899 return getResultPatternCost(LHS->getDstPattern(), ISE) <
1900 getResultPatternCost(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001901 }
1902};
1903
Nate Begeman6510b222005-12-01 04:51:06 +00001904/// getRegisterValueType - Look up and return the first ValueType of specified
1905/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001906static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001907 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1908 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001909 return MVT::Other;
1910}
1911
Chris Lattner72fe91c2005-09-24 00:40:24 +00001912
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001913/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1914/// type information from it.
1915static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001916 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001917 if (!N->isLeaf())
1918 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1919 RemoveAllTypes(N->getChild(i));
1920}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001921
Chris Lattner0614b622005-11-02 06:49:14 +00001922Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1923 Record *N = Records.getDef(Name);
Chris Lattner5a1df382006-03-24 23:10:39 +00001924 if (!N || !N->isSubClassOf("SDNode")) {
1925 std::cerr << "Error getting SDNode '" << Name << "'!\n";
1926 exit(1);
1927 }
Chris Lattner0614b622005-11-02 06:49:14 +00001928 return N;
1929}
1930
Evan Cheng51fecc82006-01-09 18:27:06 +00001931/// NodeHasProperty - return true if TreePatternNode has the specified
1932/// property.
1933static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1934 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001935{
1936 if (N->isLeaf()) return false;
1937 Record *Operator = N->getOperator();
1938 if (!Operator->isSubClassOf("SDNode")) return false;
1939
1940 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00001941 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00001942}
1943
Evan Cheng51fecc82006-01-09 18:27:06 +00001944static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1945 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001946{
Evan Cheng51fecc82006-01-09 18:27:06 +00001947 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00001948 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00001949
1950 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1951 TreePatternNode *Child = N->getChild(i);
1952 if (PatternHasProperty(Child, Property, ISE))
1953 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001954 }
1955
1956 return false;
1957}
1958
Evan Chengb915f312005-12-09 22:45:35 +00001959class PatternCodeEmitter {
1960private:
1961 DAGISelEmitter &ISE;
1962
Evan Cheng58e84a62005-12-14 22:02:59 +00001963 // Predicates.
1964 ListInit *Predicates;
1965 // Instruction selector pattern.
1966 TreePatternNode *Pattern;
1967 // Matched instruction.
1968 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001969
Evan Chengb915f312005-12-09 22:45:35 +00001970 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00001971 std::map<std::string, std::string> VariableMap;
1972 // Node to operator mapping
1973 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00001974 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001975 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00001976 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +00001977
Chris Lattner8a0604b2006-01-28 20:31:24 +00001978 /// GeneratedCode - This is the buffer that we emit code to. The first bool
1979 /// indicates whether this is an exit predicate (something that should be
1980 /// tested, and if true, the match fails) [when true] or normal code to emit
1981 /// [when false].
1982 std::vector<std::pair<bool, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00001983 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
1984 /// the set of patterns for each top-level opcode.
Evan Chengd7805a72006-02-09 07:16:09 +00001985 std::set<std::pair<bool, std::string> > &GeneratedDecl;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001986
Evan Chenge4a8a6e2006-02-03 06:22:41 +00001987 std::string ChainName;
Evan Chenged66e852006-03-09 08:19:11 +00001988 bool NewTF;
Evan Chenge41bf822006-02-05 06:43:12 +00001989 bool DoReplace;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001990 unsigned TmpNo;
1991
1992 void emitCheck(const std::string &S) {
1993 if (!S.empty())
1994 GeneratedCode.push_back(std::make_pair(true, S));
1995 }
1996 void emitCode(const std::string &S) {
1997 if (!S.empty())
1998 GeneratedCode.push_back(std::make_pair(false, S));
1999 }
Evan Chengd7805a72006-02-09 07:16:09 +00002000 void emitDecl(const std::string &S, bool isSDNode=false) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002001 assert(!S.empty() && "Invalid declaration");
Evan Chengd7805a72006-02-09 07:16:09 +00002002 GeneratedDecl.insert(std::make_pair(isSDNode, S));
Evan Cheng21ad3922006-02-07 00:37:41 +00002003 }
Evan Chengb915f312005-12-09 22:45:35 +00002004public:
Evan Cheng58e84a62005-12-14 22:02:59 +00002005 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2006 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng21ad3922006-02-07 00:37:41 +00002007 std::vector<std::pair<bool, std::string> > &gc,
Evan Chengd7805a72006-02-09 07:16:09 +00002008 std::set<std::pair<bool, std::string> > &gd,
Evan Cheng21ad3922006-02-07 00:37:41 +00002009 bool dorep)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002010 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Chenged66e852006-03-09 08:19:11 +00002011 GeneratedCode(gc), GeneratedDecl(gd),
2012 NewTF(false), DoReplace(dorep), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00002013
2014 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2015 /// if the match fails. At this point, we already know that the opcode for N
2016 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00002017 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2018 const std::string &RootName, const std::string &ParentName,
2019 const std::string &ChainSuffix, bool &FoundChain) {
2020 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00002021 // Emit instruction predicates. Each predicate is just a string for now.
2022 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002023 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00002024 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2025 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2026 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002027 if (!Def->isSubClassOf("Predicate")) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002028 Def->dump();
2029 assert(0 && "Unknown predicate type!");
2030 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002031 if (!PredicateCheck.empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002032 PredicateCheck += " || ";
2033 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00002034 }
2035 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002036
2037 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00002038 }
2039
Evan Chengb915f312005-12-09 22:45:35 +00002040 if (N->isLeaf()) {
2041 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002042 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00002043 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002044 return;
2045 } else if (!NodeIsComplexPattern(N)) {
2046 assert(0 && "Cannot match this as a leaf value!");
2047 abort();
2048 }
2049 }
2050
Chris Lattner488580c2006-01-28 19:06:51 +00002051 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002052 // we already saw this in the pattern, emit code to verify dagness.
2053 if (!N->getName().empty()) {
2054 std::string &VarMapEntry = VariableMap[N->getName()];
2055 if (VarMapEntry.empty()) {
2056 VarMapEntry = RootName;
2057 } else {
2058 // If we get here, this is a second reference to a specific name. Since
2059 // we already have checked that the first reference is valid, we don't
2060 // have to recursively match it, just check that it's the same as the
2061 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002062 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00002063 return;
2064 }
Evan Chengf805c2e2006-01-12 19:35:54 +00002065
2066 if (!N->isLeaf())
2067 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00002068 }
2069
2070
2071 // Emit code to load the child nodes and match their contents recursively.
2072 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00002073 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2074 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2075 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00002076 bool EmittedUseCheck = false;
2077 bool EmittedSlctedCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00002078 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00002079 if (NodeHasChain)
2080 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00002081 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00002082 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattner8a0604b2006-01-28 20:31:24 +00002083 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002084 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002085 EmittedUseCheck = true;
2086 // hasOneUse() check is not strong enough. If the original node has
2087 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002088 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002089 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002090 "))");
2091
Evan Cheng1feeeec2006-01-26 19:13:45 +00002092 EmittedSlctedCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002093 if (NodeHasChain) {
2094 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2095 // has a chain use.
2096 // This a workaround for this problem:
2097 //
2098 // [ch, r : ld]
2099 // ^ ^
2100 // | |
2101 // [XX]--/ \- [flag : cmp]
2102 // ^ ^
2103 // | |
2104 // \---[br flag]-
2105 //
2106 // cmp + br should be considered as a single node as they are flagged
2107 // together. So, if the ld is folded into the cmp, the XX node in the
2108 // graph is now both an operand and a use of the ld/cmp/br node.
2109 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2110 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2111
2112 // If the immediate use can somehow reach this node through another
2113 // path, then can't fold it either or it will create a cycle.
2114 // e.g. In the following diagram, XX can reach ld through YY. If
2115 // ld is folded into XX, then YY is both a predecessor and a successor
2116 // of XX.
2117 //
2118 // [ld]
2119 // ^ ^
2120 // | |
2121 // / \---
2122 // / [YY]
2123 // | ^
2124 // [XX]-------|
2125 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2126 if (PInfo.getNumOperands() > 1 ||
2127 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2128 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2129 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
Evan Cheng6f8aaf22006-03-07 08:31:27 +00002130 if (PInfo.getNumOperands() > 1) {
2131 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2132 ".Val)");
2133 } else {
2134 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2135 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2136 ".Val))");
2137 }
Evan Chenge41bf822006-02-05 06:43:12 +00002138 }
Evan Chengb915f312005-12-09 22:45:35 +00002139 }
Evan Chenge41bf822006-02-05 06:43:12 +00002140
Evan Chengc15d18c2006-01-27 22:13:45 +00002141 if (NodeHasChain) {
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002142 ChainName = "Chain" + ChainSuffix;
Evan Cheng21ad3922006-02-07 00:37:41 +00002143 emitDecl(ChainName);
Evan Chenged66e852006-03-09 08:19:11 +00002144 if (FoundChain) {
2145 // FIXME: temporary workaround for a common case where chain
2146 // is a TokenFactor and the previous "inner" chain is an operand.
2147 NewTF = true;
2148 emitDecl("OldTF", true);
2149 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2150 RootName + ".Val, Chain.Val, OldTF)).Val");
2151 } else {
2152 FoundChain = true;
2153 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2154 }
Evan Cheng1cf6db22006-01-06 00:41:12 +00002155 }
Evan Chengb915f312005-12-09 22:45:35 +00002156 }
2157
Evan Cheng54597732006-01-26 00:22:25 +00002158 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002159 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002160 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002161 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2162 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002163 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002164 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2165 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2166 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002167 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2168 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002169 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002170 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002171 }
Evan Cheng1feeeec2006-01-26 19:13:45 +00002172 if (!EmittedSlctedCheck)
2173 // hasOneUse() check is not strong enough. If the original node has
2174 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002175 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002176 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002177 "))");
Evan Cheng54597732006-01-26 00:22:25 +00002178 }
2179
Evan Chengb915f312005-12-09 22:45:35 +00002180 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002181 emitDecl(RootName + utostr(OpNo));
2182 emitCode(RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002183 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002184 TreePatternNode *Child = N->getChild(i);
2185
2186 if (!Child->isLeaf()) {
2187 // If it's not a leaf, recursively match.
2188 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002189 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002190 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002191 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2192 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002193 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002194 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2195 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002196 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002197 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002198 // we already saw this in the pattern, emit code to verify dagness.
2199 if (!Child->getName().empty()) {
2200 std::string &VarMapEntry = VariableMap[Child->getName()];
2201 if (VarMapEntry.empty()) {
2202 VarMapEntry = RootName + utostr(OpNo);
2203 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002204 // If we get here, this is a second reference to a specific name.
2205 // Since we already have checked that the first reference is valid,
2206 // we don't have to recursively match it, just check that it's the
2207 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002208 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002209 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002210 continue;
2211 }
2212 }
2213
2214 // Handle leaves of various types.
2215 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2216 Record *LeafRec = DI->getDef();
2217 if (LeafRec->isSubClassOf("RegisterClass")) {
2218 // Handle register references. Nothing to do here.
2219 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002220 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002221 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2222 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00002223 } else if (LeafRec->getName() == "srcvalue") {
2224 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002225 } else if (LeafRec->isSubClassOf("ValueType")) {
2226 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002227 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002228 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002229 } else if (LeafRec->isSubClassOf("CondCode")) {
2230 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002231 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002232 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002233 } else {
2234 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002235 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00002236 assert(0 && "Unknown leaf type!");
2237 }
Chris Lattner488580c2006-01-28 19:06:51 +00002238 } else if (IntInit *II =
2239 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002240 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2241 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002242 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002243 RootName + utostr(OpNo) + ")->getSignExtended();");
2244
2245 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002246 } else {
2247 Child->dump();
2248 assert(0 && "Unknown leaf type!");
2249 }
2250 }
2251 }
2252
2253 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002254 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002255 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002256 }
2257
2258 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2259 /// we actually have to build a DAG!
2260 std::pair<unsigned, unsigned>
Chris Lattner947604b2006-03-24 21:52:20 +00002261 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2262 bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002263 // This is something selected from the pattern we matched.
2264 if (!N->getName().empty()) {
Evan Chengb915f312005-12-09 22:45:35 +00002265 std::string &Val = VariableMap[N->getName()];
2266 assert(!Val.empty() &&
2267 "Variable referenced but not defined and not caught earlier!");
2268 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2269 // Already selected this operand, just return the tmpval.
2270 return std::make_pair(1, atoi(Val.c_str()+3));
2271 }
2272
2273 const ComplexPattern *CP;
2274 unsigned ResNo = TmpNo++;
2275 unsigned NumRes = 1;
2276 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002277 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002278 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002279 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002280 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002281 case MVT::i1: CastType = "bool"; break;
2282 case MVT::i8: CastType = "unsigned char"; break;
2283 case MVT::i16: CastType = "unsigned short"; break;
2284 case MVT::i32: CastType = "unsigned"; break;
2285 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002286 }
Chris Lattner78593132006-01-29 20:01:35 +00002287 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
Andrew Lenharth2cba57c2006-01-29 05:17:22 +00002288 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
Evan Cheng21ad3922006-02-07 00:37:41 +00002289 emitDecl("Tmp" + utostr(ResNo));
2290 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002291 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2292 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengbb48e332006-01-12 07:54:57 +00002293 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002294 Record *Op = OperatorMap[N->getName()];
2295 // Transform ExternalSymbol to TargetExternalSymbol
2296 if (Op && Op->getName() == "externalsym") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002297 emitDecl("Tmp" + utostr(ResNo));
2298 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002299 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2300 Val + ")->getSymbol(), MVT::" +
2301 getEnumName(N->getTypeNum(0)) + ");");
2302 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002303 emitDecl("Tmp" + utostr(ResNo));
2304 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002305 }
Evan Chengb915f312005-12-09 22:45:35 +00002306 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002307 Record *Op = OperatorMap[N->getName()];
2308 // Transform GlobalAddress to TargetGlobalAddress
2309 if (Op && Op->getName() == "globaladdr") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002310 emitDecl("Tmp" + utostr(ResNo));
2311 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002312 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2313 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2314 ");");
2315 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002316 emitDecl("Tmp" + utostr(ResNo));
2317 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002318 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002319 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng21ad3922006-02-07 00:37:41 +00002320 emitDecl("Tmp" + utostr(ResNo));
2321 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengbb48e332006-01-12 07:54:57 +00002322 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002323 emitDecl("Tmp" + utostr(ResNo));
2324 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002325 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2326 std::string Fn = CP->getSelectFunc();
2327 NumRes = CP->getNumOperands();
Evan Cheng21ad3922006-02-07 00:37:41 +00002328 for (unsigned i = 0; i < NumRes; ++i)
2329 emitDecl("Tmp" + utostr(i+ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002330
Evan Cheng21ad3922006-02-07 00:37:41 +00002331 std::string Code = Fn + "(" + Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002332 for (unsigned i = 0; i < NumRes; i++)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002333 Code += ", Tmp" + utostr(i + ResNo);
2334 emitCheck(Code + ")");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002335
Evan Cheng2216d8a2006-02-05 05:22:18 +00002336 for (unsigned i = 0; i < NumRes; ++i)
Evan Cheng34167212006-02-09 00:37:58 +00002337 emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
Evan Cheng2216d8a2006-02-05 05:22:18 +00002338 utostr(i+ResNo) + ");");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002339
Evan Chengb915f312005-12-09 22:45:35 +00002340 TmpNo = ResNo + NumRes;
2341 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002342 emitDecl("Tmp" + utostr(ResNo));
Evan Cheng863bf5a2006-03-20 22:53:06 +00002343 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2344 // node even if it isn't one. Don't select it.
2345 if (LikeLeaf)
2346 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2347 else
2348 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
Evan Cheng83e1a6a2006-03-23 02:35:32 +00002349
2350 if (isRoot && N->isLeaf()) {
2351 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2352 emitCode("return;");
2353 }
Evan Chengb915f312005-12-09 22:45:35 +00002354 }
2355 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2356 // value if used multiple times by this pattern result.
2357 Val = "Tmp"+utostr(ResNo);
2358 return std::make_pair(NumRes, ResNo);
2359 }
Evan Chengb915f312005-12-09 22:45:35 +00002360 if (N->isLeaf()) {
2361 // If this is an explicit register reference, handle it.
2362 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2363 unsigned ResNo = TmpNo++;
2364 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002365 emitDecl("Tmp" + utostr(ResNo));
2366 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002367 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2368 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002369 return std::make_pair(1, ResNo);
2370 }
2371 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2372 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002373 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng21ad3922006-02-07 00:37:41 +00002374 emitDecl("Tmp" + utostr(ResNo));
2375 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002376 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2377 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002378 return std::make_pair(1, ResNo);
2379 }
2380
2381 N->dump();
2382 assert(0 && "Unknown leaf type!");
2383 return std::make_pair(1, ~0U);
2384 }
2385
2386 Record *Op = N->getOperator();
2387 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002388 const CodeGenTarget &CGT = ISE.getTargetInfo();
2389 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002390 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002391 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2392 bool HasImpResults = Inst.getNumImpResults() > 0;
Evan Cheng54597732006-01-26 00:22:25 +00002393 bool HasOptInFlag = isRoot &&
2394 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002395 bool HasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002396 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2397 bool NodeHasOutFlag = HasImpResults ||
Evan Cheng51fecc82006-01-09 18:27:06 +00002398 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
Evan Cheng823b7522006-01-19 21:57:10 +00002399 bool NodeHasChain =
2400 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002401 bool HasChain = II.hasCtrlDep ||
2402 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
Evan Cheng4fba2812005-12-20 07:37:41 +00002403
Evan Cheng54597732006-01-26 00:22:25 +00002404 if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
Evan Cheng21ad3922006-02-07 00:37:41 +00002405 emitDecl("InFlag");
Evan Cheng54597732006-01-26 00:22:25 +00002406 if (HasOptInFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002407 emitCode("bool HasOptInFlag = false;");
Evan Cheng4fba2812005-12-20 07:37:41 +00002408
Evan Cheng823b7522006-01-19 21:57:10 +00002409 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002410 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002411 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2412 MVT::ValueType VT = Pattern->getTypeNum(i);
2413 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002414 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002415 }
2416
Evan Chengb915f312005-12-09 22:45:35 +00002417 // Determine operand emission order. Complex pattern first.
2418 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2419 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2420 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2421 TreePatternNode *Child = N->getChild(i);
2422 if (i == 0) {
2423 EmitOrder.push_back(std::make_pair(i, Child));
2424 OI = EmitOrder.begin();
2425 } else if (NodeIsComplexPattern(Child)) {
2426 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2427 } else {
2428 EmitOrder.push_back(std::make_pair(i, Child));
2429 }
2430 }
2431
2432 // Emit all of the operands.
2433 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2434 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2435 unsigned OpOrder = EmitOrder[i].first;
2436 TreePatternNode *Child = EmitOrder[i].second;
2437 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2438 NumTemps[OpOrder] = NumTemp;
2439 }
2440
2441 // List all the operands in the right order.
2442 std::vector<unsigned> Ops;
2443 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2444 for (unsigned j = 0; j < NumTemps[i].first; j++)
2445 Ops.push_back(NumTemps[i].second + j);
2446 }
2447
Evan Chengb915f312005-12-09 22:45:35 +00002448 // Emit all the chain and CopyToReg stuff.
Evan Chengb2c6d492006-01-11 22:16:13 +00002449 bool ChainEmitted = HasChain;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002450 if (HasChain)
Evan Cheng34167212006-02-09 00:37:58 +00002451 emitCode("Select(" + ChainName + ", " + ChainName + ");");
Evan Cheng54597732006-01-26 00:22:25 +00002452 if (HasInFlag || HasOptInFlag || HasImpInputs)
2453 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
Evan Chengb915f312005-12-09 22:45:35 +00002454
Evan Chengb915f312005-12-09 22:45:35 +00002455 unsigned NumResults = Inst.getNumResults();
2456 unsigned ResNo = TmpNo++;
2457 if (!isRoot) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002458 emitDecl("Tmp" + utostr(ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002459 std::string Code =
Evan Chengd7805a72006-02-09 07:16:09 +00002460 "Tmp" + utostr(ResNo) + " = SDOperand(CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002461 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002462 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002463 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002464 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002465 Code += ", MVT::Flag";
Evan Chengbcecf332005-12-17 01:19:28 +00002466
Evan Chengb915f312005-12-09 22:45:35 +00002467 unsigned LastOp = 0;
2468 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2469 LastOp = Ops[i];
Chris Lattner8a0604b2006-01-28 20:31:24 +00002470 Code += ", Tmp" + utostr(LastOp);
Evan Chengb915f312005-12-09 22:45:35 +00002471 }
Evan Chengd7805a72006-02-09 07:16:09 +00002472 emitCode(Code + "), 0);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002473 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002474 // Must have at least one result
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002475 emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002476 utostr(NumResults) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002477 }
Evan Cheng54597732006-01-26 00:22:25 +00002478 } else if (HasChain || NodeHasOutFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002479 if (HasOptInFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002480 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
Evan Chengd7805a72006-02-09 07:16:09 +00002481 emitDecl("ResNode", true);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002482 emitCode("if (HasOptInFlag)");
Evan Chengd7805a72006-02-09 07:16:09 +00002483 std::string Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002484 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002485
Evan Cheng9789aaa2006-01-24 20:46:50 +00002486 // Output order: results, chain, flags
2487 // Result types.
2488 if (NumResults > 0) {
2489 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002490 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002491 }
2492 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002493 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002494 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002495 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002496
2497 // Inputs.
2498 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002499 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002500 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002501 emitCode(Code + ", InFlag);");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002502
Chris Lattner8a0604b2006-01-28 20:31:24 +00002503 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002504 Code = " ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002505 II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002506
2507 // Output order: results, chain, flags
2508 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002509 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2510 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002511 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002512 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002513 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002514 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002515
2516 // Inputs.
2517 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002518 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002519 if (HasChain) Code += ", " + ChainName + ");";
Chris Lattner8a0604b2006-01-28 20:31:24 +00002520 emitCode(Code);
Evan Cheng9789aaa2006-01-24 20:46:50 +00002521 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002522 emitDecl("ResNode", true);
2523 std::string Code = "ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002524 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002525
2526 // Output order: results, chain, flags
2527 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002528 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2529 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002530 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002531 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002532 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002533 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002534
2535 // Inputs.
2536 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002537 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002538 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002539 if (HasInFlag || HasImpInputs) Code += ", InFlag";
2540 emitCode(Code + ");");
Evan Chengbcecf332005-12-17 01:19:28 +00002541 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002542
Evan Chenged66e852006-03-09 08:19:11 +00002543 if (NewTF)
2544 emitCode("if (OldTF) "
2545 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2546 ChainName + ".Val, 0);");
2547
2548 for (unsigned i = 0; i < NumResults; i++)
Evan Cheng67212a02006-02-09 22:12:27 +00002549 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002550 utostr(i) + ", ResNode, " + utostr(i) + ");");
Evan Chengf9fc25d2005-12-19 22:40:04 +00002551
Evan Cheng54597732006-01-26 00:22:25 +00002552 if (NodeHasOutFlag)
Evan Chengd7805a72006-02-09 07:16:09 +00002553 emitCode("InFlag = SDOperand(ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002554 utostr(NumResults + (unsigned)HasChain) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002555
Chris Lattner8a0604b2006-01-28 20:31:24 +00002556 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
Evan Chenged66e852006-03-09 08:19:11 +00002557 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2558 "0, ResNode, 0);");
2559 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00002560 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002561
Evan Chenge41bf822006-02-05 06:43:12 +00002562 if (NodeHasChain) {
Evan Cheng67212a02006-02-09 22:12:27 +00002563 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002564 utostr(PatResults) + ", ResNode, " +
2565 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002566 if (DoReplace)
Evan Chenged66e852006-03-09 08:19:11 +00002567 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2568 utostr(PatResults) + ", " + "ResNode, " +
2569 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002570 }
2571
Evan Cheng97938882005-12-22 02:24:50 +00002572 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002573 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002574 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng67212a02006-02-09 22:12:27 +00002575 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2576 FoldedChains[j].first + ".Val, " +
2577 utostr(FoldedChains[j].second) + ", ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002578 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002579
2580 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2581 std::string Code =
Evan Cheng67212a02006-02-09 22:12:27 +00002582 FoldedChains[j].first + ".Val, " +
2583 utostr(FoldedChains[j].second) + ", ";
2584 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002585 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002586 }
Evan Chengb915f312005-12-09 22:45:35 +00002587 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002588
Evan Cheng54597732006-01-26 00:22:25 +00002589 if (NodeHasOutFlag)
Evan Cheng67212a02006-02-09 22:12:27 +00002590 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002591 utostr(PatResults + (unsigned)NodeHasChain) +
2592 ", InFlag.Val, InFlag.ResNo);");
Evan Cheng97938882005-12-22 02:24:50 +00002593
Evan Chenged66e852006-03-09 08:19:11 +00002594 // User does not expect the instruction would produce a chain!
2595 bool AddedChain = HasChain && !NodeHasChain;
Evan Cheng54597732006-01-26 00:22:25 +00002596 if (AddedChain && NodeHasOutFlag) {
Evan Chenged66e852006-03-09 08:19:11 +00002597 if (PatResults == 0) {
Evan Chengd7805a72006-02-09 07:16:09 +00002598 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002599 } else {
Evan Chenged66e852006-03-09 08:19:11 +00002600 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
Evan Chengd7805a72006-02-09 07:16:09 +00002601 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002602 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002603 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002604 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002605 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002606 emitCode("Result = SDOperand(ResNode, N.ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002607 }
Evan Chengb915f312005-12-09 22:45:35 +00002608 } else {
2609 // If this instruction is the root, and if there is only one use of it,
2610 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002611 emitCode("if (N.Val->hasOneUse()) {");
Evan Cheng34167212006-02-09 00:37:58 +00002612 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002613 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002614 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002615 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002616 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002617 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002618 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002619 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002620 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002621 Code += ", InFlag";
2622 emitCode(Code + ");");
2623 emitCode("} else {");
Evan Chengd7805a72006-02-09 07:16:09 +00002624 emitDecl("ResNode", true);
2625 Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002626 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002627 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002628 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002629 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002630 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002631 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002632 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002633 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002634 Code += ", InFlag";
2635 emitCode(Code + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002636 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2637 "ResNode, 0);");
2638 emitCode(" Result = SDOperand(ResNode, 0);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002639 emitCode("}");
Evan Chengb915f312005-12-09 22:45:35 +00002640 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002641
Evan Cheng34167212006-02-09 00:37:58 +00002642 if (isRoot)
2643 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002644 return std::make_pair(1, ResNo);
2645 } else if (Op->isSubClassOf("SDNodeXForm")) {
2646 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00002647 // PatLeaf node - the operand may or may not be a leaf node. But it should
2648 // behave like one.
2649 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
Evan Chengb915f312005-12-09 22:45:35 +00002650 unsigned ResNo = TmpNo++;
Evan Cheng21ad3922006-02-07 00:37:41 +00002651 emitDecl("Tmp" + utostr(ResNo));
2652 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Chris Lattner8a0604b2006-01-28 20:31:24 +00002653 + "(Tmp" + utostr(OpVal) + ".Val);");
Evan Chengb915f312005-12-09 22:45:35 +00002654 if (isRoot) {
Evan Cheng67212a02006-02-09 22:12:27 +00002655 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2656 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2657 utostr(ResNo) + ".ResNo);");
Evan Cheng34167212006-02-09 00:37:58 +00002658 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2659 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002660 }
2661 return std::make_pair(1, ResNo);
2662 } else {
2663 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002664 std::cerr << "\n";
2665 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002666 }
2667 }
2668
Chris Lattner488580c2006-01-28 19:06:51 +00002669 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2670 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002671 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2672 /// for, this returns true otherwise false if Pat has all types.
2673 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2674 const std::string &Prefix) {
2675 // Did we find one?
2676 if (!Pat->hasTypeSet()) {
2677 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002678 Pat->setTypes(Other->getExtTypes());
Chris Lattner67a202b2006-01-28 20:43:52 +00002679 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002680 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002681 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002682 }
2683
Evan Cheng51fecc82006-01-09 18:27:06 +00002684 unsigned OpNo =
2685 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002686 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2687 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2688 Prefix + utostr(OpNo)))
2689 return true;
2690 return false;
2691 }
2692
2693private:
Evan Cheng54597732006-01-26 00:22:25 +00002694 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002695 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002696 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2697 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002698 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002699 unsigned OpNo =
2700 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002701 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2702 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002703 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2704 TreePatternNode *Child = N->getChild(i);
2705 if (!Child->isLeaf()) {
Evan Cheng54597732006-01-26 00:22:25 +00002706 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002707 } else {
2708 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002709 if (!Child->getName().empty()) {
2710 std::string Name = RootName + utostr(OpNo);
2711 if (Duplicates.find(Name) != Duplicates.end())
2712 // A duplicate! Do not emit a copy for this node.
2713 continue;
2714 }
2715
Evan Chengb915f312005-12-09 22:45:35 +00002716 Record *RR = DI->getDef();
2717 if (RR->isSubClassOf("Register")) {
2718 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002719 if (RVT == MVT::Flag) {
Evan Cheng34167212006-02-09 00:37:58 +00002720 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
Evan Chengb2c6d492006-01-11 22:16:13 +00002721 } else {
2722 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002723 emitDecl("Chain");
2724 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002725 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002726 ChainEmitted = true;
2727 }
Evan Cheng34167212006-02-09 00:37:58 +00002728 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2729 RootName + utostr(OpNo) + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002730 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002731 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
Evan Cheng34167212006-02-09 00:37:58 +00002732 ", MVT::" + getEnumName(RVT) + "), " +
Evan Chengd7805a72006-02-09 07:16:09 +00002733 RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng67212a02006-02-09 22:12:27 +00002734 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2735 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00002736 }
2737 }
2738 }
2739 }
2740 }
Evan Cheng54597732006-01-26 00:22:25 +00002741
2742 if (HasInFlag || HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002743 std::string Code;
Evan Cheng54597732006-01-26 00:22:25 +00002744 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002745 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2746 ") {");
2747 Code = " ";
Evan Cheng54597732006-01-26 00:22:25 +00002748 }
Evan Cheng34167212006-02-09 00:37:58 +00002749 emitCode(Code + "Select(InFlag, " + RootName +
2750 ".getOperand(" + utostr(OpNo) + "));");
Evan Cheng54597732006-01-26 00:22:25 +00002751 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002752 emitCode(" HasOptInFlag = true;");
2753 emitCode("}");
Evan Cheng54597732006-01-26 00:22:25 +00002754 }
2755 }
Evan Chengb915f312005-12-09 22:45:35 +00002756 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002757
2758 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002759 /// as specified by the instruction. It returns true if any copy is
2760 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002761 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002762 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002763 Record *Op = N->getOperator();
2764 if (Op->isSubClassOf("Instruction")) {
2765 const DAGInstruction &Inst = ISE.getInstruction(Op);
2766 const CodeGenTarget &CGT = ISE.getTargetInfo();
2767 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2768 unsigned NumImpResults = Inst.getNumImpResults();
2769 for (unsigned i = 0; i < NumImpResults; i++) {
2770 Record *RR = Inst.getImpResult(i);
2771 if (RR->isSubClassOf("Register")) {
2772 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2773 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002774 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002775 emitDecl("Chain");
2776 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002777 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002778 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002779 }
Evan Chengd7805a72006-02-09 07:16:09 +00002780 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002781 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00002782 ", InFlag).Val;");
2783 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2784 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002785 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002786 }
2787 }
2788 }
2789 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002790 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002791 }
Evan Chengb915f312005-12-09 22:45:35 +00002792};
2793
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002794/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2795/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00002796/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00002797void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Chenge41bf822006-02-05 06:43:12 +00002798 std::vector<std::pair<bool, std::string> > &GeneratedCode,
Evan Chengd7805a72006-02-09 07:16:09 +00002799 std::set<std::pair<bool, std::string> > &GeneratedDecl,
Evan Chenge41bf822006-02-05 06:43:12 +00002800 bool DoReplace) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002801 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2802 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Cheng21ad3922006-02-07 00:37:41 +00002803 GeneratedCode, GeneratedDecl, DoReplace);
Evan Chengb915f312005-12-09 22:45:35 +00002804
Chris Lattner8fc35682005-09-23 23:16:51 +00002805 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002806 bool FoundChain = false;
Evan Chenge41bf822006-02-05 06:43:12 +00002807 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002808
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002809 // TP - Get *SOME* tree pattern, we don't care which.
2810 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002811
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002812 // At this point, we know that we structurally match the pattern, but the
2813 // types of the nodes may not match. Figure out the fewest number of type
2814 // comparisons we need to emit. For example, if there is only one integer
2815 // type supported by a target, there should be no type comparisons at all for
2816 // integer patterns!
2817 //
2818 // To figure out the fewest number of type checks needed, clone the pattern,
2819 // remove the types, then perform type inference on the pattern as a whole.
2820 // If there are unresolved types, emit an explicit check for those types,
2821 // apply the type to the tree, then rerun type inference. Iterate until all
2822 // types are resolved.
2823 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002824 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002825 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002826
2827 do {
2828 // Resolve/propagate as many types as possible.
2829 try {
2830 bool MadeChange = true;
2831 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00002832 MadeChange = Pat->ApplyTypeConstraints(TP,
2833 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00002834 } catch (...) {
2835 assert(0 && "Error: could not find consistent types for something we"
2836 " already decided was ok!");
2837 abort();
2838 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002839
Chris Lattner7e82f132005-10-15 21:34:21 +00002840 // Insert a check for an unresolved type and add it to the tree. If we find
2841 // an unresolved type to add a check for, this returns true and we iterate,
2842 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002843 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002844
Evan Cheng863bf5a2006-03-20 22:53:06 +00002845 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002846 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00002847}
2848
Chris Lattner24e00a42006-01-29 04:41:05 +00002849/// EraseCodeLine - Erase one code line from all of the patterns. If removing
2850/// a line causes any of them to be empty, remove them and return true when
2851/// done.
2852static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2853 std::vector<std::pair<bool, std::string> > > >
2854 &Patterns) {
2855 bool ErasedPatterns = false;
2856 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2857 Patterns[i].second.pop_back();
2858 if (Patterns[i].second.empty()) {
2859 Patterns.erase(Patterns.begin()+i);
2860 --i; --e;
2861 ErasedPatterns = true;
2862 }
2863 }
2864 return ErasedPatterns;
2865}
2866
Chris Lattner8bc74722006-01-29 04:25:26 +00002867/// EmitPatterns - Emit code for at least one pattern, but try to group common
2868/// code together between the patterns.
2869void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
2870 std::vector<std::pair<bool, std::string> > > >
2871 &Patterns, unsigned Indent,
2872 std::ostream &OS) {
2873 typedef std::pair<bool, std::string> CodeLine;
2874 typedef std::vector<CodeLine> CodeList;
2875 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2876
2877 if (Patterns.empty()) return;
2878
Chris Lattner24e00a42006-01-29 04:41:05 +00002879 // Figure out how many patterns share the next code line. Explicitly copy
2880 // FirstCodeLine so that we don't invalidate a reference when changing
2881 // Patterns.
2882 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00002883 unsigned LastMatch = Patterns.size()-1;
2884 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2885 --LastMatch;
2886
2887 // If not all patterns share this line, split the list into two pieces. The
2888 // first chunk will use this line, the second chunk won't.
2889 if (LastMatch != 0) {
2890 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2891 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2892
2893 // FIXME: Emit braces?
2894 if (Shared.size() == 1) {
2895 PatternToMatch &Pattern = *Shared.back().first;
2896 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2897 Pattern.getSrcPattern()->print(OS);
2898 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2899 Pattern.getDstPattern()->print(OS);
2900 OS << "\n";
2901 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2902 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00002903 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00002904 }
2905 if (!FirstCodeLine.first) {
2906 OS << std::string(Indent, ' ') << "{\n";
2907 Indent += 2;
2908 }
2909 EmitPatterns(Shared, Indent, OS);
2910 if (!FirstCodeLine.first) {
2911 Indent -= 2;
2912 OS << std::string(Indent, ' ') << "}\n";
2913 }
2914
2915 if (Other.size() == 1) {
2916 PatternToMatch &Pattern = *Other.back().first;
2917 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2918 Pattern.getSrcPattern()->print(OS);
2919 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2920 Pattern.getDstPattern()->print(OS);
2921 OS << "\n";
2922 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2923 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00002924 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00002925 }
2926 EmitPatterns(Other, Indent, OS);
2927 return;
2928 }
2929
Chris Lattner24e00a42006-01-29 04:41:05 +00002930 // Remove this code from all of the patterns that share it.
2931 bool ErasedPatterns = EraseCodeLine(Patterns);
2932
Chris Lattner8bc74722006-01-29 04:25:26 +00002933 bool isPredicate = FirstCodeLine.first;
2934
2935 // Otherwise, every pattern in the list has this line. Emit it.
2936 if (!isPredicate) {
2937 // Normal code.
2938 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2939 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00002940 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2941
2942 // If the next code line is another predicate, and if all of the pattern
2943 // in this group share the same next line, emit it inline now. Do this
2944 // until we run out of common predicates.
2945 while (!ErasedPatterns && Patterns.back().second.back().first) {
2946 // Check that all of fhe patterns in Patterns end with the same predicate.
2947 bool AllEndWithSamePredicate = true;
2948 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2949 if (Patterns[i].second.back() != Patterns.back().second.back()) {
2950 AllEndWithSamePredicate = false;
2951 break;
2952 }
2953 // If all of the predicates aren't the same, we can't share them.
2954 if (!AllEndWithSamePredicate) break;
2955
2956 // Otherwise we can. Emit it shared now.
2957 OS << " &&\n" << std::string(Indent+4, ' ')
2958 << Patterns.back().second.back().second;
2959 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00002960 }
Chris Lattner24e00a42006-01-29 04:41:05 +00002961
2962 OS << ") {\n";
2963 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00002964 }
2965
2966 EmitPatterns(Patterns, Indent, OS);
2967
2968 if (isPredicate)
2969 OS << std::string(Indent-2, ' ') << "}\n";
2970}
2971
2972
Chris Lattner37481472005-09-26 21:59:35 +00002973
2974namespace {
2975 /// CompareByRecordName - An ordering predicate that implements less-than by
2976 /// comparing the names records.
2977 struct CompareByRecordName {
2978 bool operator()(const Record *LHS, const Record *RHS) const {
2979 // Sort by name first.
2980 if (LHS->getName() < RHS->getName()) return true;
2981 // If both names are equal, sort by pointer.
2982 return LHS->getName() == RHS->getName() && LHS < RHS;
2983 }
2984 };
2985}
2986
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002987void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002988 std::string InstNS = Target.inst_begin()->second.Namespace;
2989 if (!InstNS.empty()) InstNS += "::";
2990
Chris Lattner602f6922006-01-04 00:25:00 +00002991 // Group the patterns by their top-level opcodes.
2992 std::map<Record*, std::vector<PatternToMatch*>,
2993 CompareByRecordName> PatternsByOpcode;
2994 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2995 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2996 if (!Node->isLeaf()) {
2997 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2998 } else {
2999 const ComplexPattern *CP;
3000 if (IntInit *II =
3001 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3002 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3003 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3004 std::vector<Record*> OpNodes = CP->getRootNodes();
3005 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00003006 PatternsByOpcode[OpNodes[j]]
3007 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003008 }
3009 } else {
3010 std::cerr << "Unrecognized opcode '";
3011 Node->dump();
3012 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00003013 std::cerr <<
3014 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00003015 std::cerr << "'!\n";
3016 exit(1);
3017 }
3018 }
3019 }
3020
3021 // Emit one Select_* method for each top-level opcode. We do this instead of
3022 // emitting one giant switch statement to support compilers where this will
3023 // result in the recursive functions taking less stack space.
3024 for (std::map<Record*, std::vector<PatternToMatch*>,
3025 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3026 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00003027 const std::string &OpName = PBOI->first->getName();
Evan Cheng34167212006-02-09 00:37:58 +00003028 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003029
3030 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Evan Chenge41bf822006-02-05 06:43:12 +00003031 bool OptSlctOrder =
3032 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3033 OpcodeInfo.getNumResults() > 0);
3034
3035 if (OptSlctOrder) {
Evan Chenge41bf822006-02-05 06:43:12 +00003036 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3037 << " && N.getValue(0).hasOneUse()) {\n"
3038 << " SDOperand Dummy = "
3039 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003040 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3041 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3042 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3043 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003044 << " Result = Dummy;\n"
3045 << " return;\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003046 << " }\n";
3047 }
3048
Chris Lattner602f6922006-01-04 00:25:00 +00003049 std::vector<PatternToMatch*> &Patterns = PBOI->second;
Chris Lattner355408b2006-01-29 02:43:35 +00003050 assert(!Patterns.empty() && "No patterns but map has entry?");
Chris Lattner602f6922006-01-04 00:25:00 +00003051
3052 // We want to emit all of the matching code now. However, we want to emit
3053 // the matches in order of minimal cost. Sort the patterns so the least
3054 // cost one is at the start.
3055 std::stable_sort(Patterns.begin(), Patterns.end(),
3056 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00003057
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003058 typedef std::vector<std::pair<bool, std::string> > CodeList;
Evan Cheng21ad3922006-02-07 00:37:41 +00003059 typedef std::set<std::string> DeclSet;
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003060
3061 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
Evan Chengd7805a72006-02-09 07:16:09 +00003062 std::set<std::pair<bool, std::string> > GeneratedDecl;
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003063 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003064 CodeList GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00003065 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3066 OptSlctOrder);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003067 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3068 }
3069
3070 // Scan the code to see if all of the patterns are reachable and if it is
3071 // possible that the last one might not match.
3072 bool mightNotMatch = true;
3073 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3074 CodeList &GeneratedCode = CodeForPatterns[i].second;
3075 mightNotMatch = false;
Chris Lattner355408b2006-01-29 02:43:35 +00003076
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003077 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3078 if (GeneratedCode[j].first) { // predicate.
3079 mightNotMatch = true;
3080 break;
3081 }
3082 }
Chris Lattner355408b2006-01-29 02:43:35 +00003083
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003084 // If this pattern definitely matches, and if it isn't the last one, the
3085 // patterns after it CANNOT ever match. Error out.
3086 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3087 std::cerr << "Pattern '";
3088 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3089 std::cerr << "' is impossible to select!\n";
3090 exit(1);
3091 }
3092 }
Evan Cheng21ad3922006-02-07 00:37:41 +00003093
3094 // Print all declarations.
Chris Lattner947604b2006-03-24 21:52:20 +00003095 for (std::set<std::pair<bool, std::string> >::iterator
3096 I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
Evan Chengd7805a72006-02-09 07:16:09 +00003097 if (I->first)
3098 OS << " SDNode *" << I->second << ";\n";
3099 else
3100 OS << " SDOperand " << I->second << "(0, 0);\n";
Evan Cheng21ad3922006-02-07 00:37:41 +00003101
Chris Lattner8bc74722006-01-29 04:25:26 +00003102 // Loop through and reverse all of the CodeList vectors, as we will be
3103 // accessing them from their logical front, but accessing the end of a
3104 // vector is more efficient.
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003105 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3106 CodeList &GeneratedCode = CodeForPatterns[i].second;
Chris Lattner8bc74722006-01-29 04:25:26 +00003107 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003108 }
Chris Lattner602f6922006-01-04 00:25:00 +00003109
Chris Lattner8bc74722006-01-29 04:25:26 +00003110 // Next, reverse the list of patterns itself for the same reason.
3111 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3112
3113 // Emit all of the patterns now, grouped together to share code.
3114 EmitPatterns(CodeForPatterns, 2, OS);
3115
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003116 // If the last pattern has predicates (which could fail) emit code to catch
3117 // the case where nothing handles a pattern.
Chris Lattner355408b2006-01-29 02:43:35 +00003118 if (mightNotMatch)
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003119 OS << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003120 << " if (N.getOpcode() != ISD::INTRINSIC) {\n"
3121 << " N.Val->dump(CurDAG);\n"
3122 << " } else {\n"
3123 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3124 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3125 << " std::cerr << \"intrinsic %\"<< "
3126 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3127 << " }\n"
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003128 << " std::cerr << '\\n';\n"
3129 << " abort();\n";
3130
3131 OS << "}\n\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003132 }
3133
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003134 // Emit boilerplate.
Evan Cheng34167212006-02-09 00:37:58 +00003135 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003136 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng34167212006-02-09 00:37:58 +00003137 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003138 << " // Select the flag operand.\n"
3139 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng34167212006-02-09 00:37:58 +00003140 << " Select(Ops.back(), Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00003141 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003142 << " std::vector<MVT::ValueType> VTs;\n"
3143 << " VTs.push_back(MVT::Other);\n"
3144 << " VTs.push_back(MVT::Flag);\n"
3145 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003146 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3147 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003148 << " Result = New.getValue(N.ResNo);\n"
3149 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003150 << "}\n\n";
3151
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003152 OS << "// The main instruction selector code.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003153 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003154 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003155 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003156 << "INSTRUCTION_LIST_END)) {\n"
3157 << " Result = N;\n"
3158 << " return; // Already selected.\n"
3159 << " }\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003160 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003161 << " if (CGMI != CodeGenMap.end()) {\n"
3162 << " Result = CGMI->second;\n"
3163 << " return;\n"
3164 << " }\n\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003165 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003166 << " default: break;\n"
3167 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003168 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003169 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003170 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003171 << " case ISD::TargetConstant:\n"
3172 << " case ISD::TargetConstantPool:\n"
3173 << " case ISD::TargetFrameIndex:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003174 << " case ISD::TargetGlobalAddress: {\n"
3175 << " Result = N;\n"
3176 << " return;\n"
3177 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003178 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003179 << " case ISD::AssertZext: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003180 << " SDOperand Tmp0;\n"
3181 << " Select(Tmp0, N.getOperand(0));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003182 << " if (!N.Val->hasOneUse())\n"
3183 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3184 << "Tmp0.Val, Tmp0.ResNo);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003185 << " Result = Tmp0;\n"
3186 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003187 << " }\n"
3188 << " case ISD::TokenFactor:\n"
3189 << " if (N.getNumOperands() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003190 << " SDOperand Op0, Op1;\n"
3191 << " Select(Op0, N.getOperand(0));\n"
3192 << " Select(Op1, N.getOperand(1));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003193 << " Result = \n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003194 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003195 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3196 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003197 << " } else {\n"
3198 << " std::vector<SDOperand> Ops;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003199 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3200 << " SDOperand Val;\n"
3201 << " Select(Val, N.getOperand(i));\n"
3202 << " Ops.push_back(Val);\n"
3203 << " }\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003204 << " Result = \n"
3205 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3206 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3207 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003208 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003209 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003210 << " case ISD::CopyFromReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003211 << " SDOperand Chain;\n"
3212 << " Select(Chain, N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003213 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3214 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003215 << " if (N.Val->getNumValues() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003216 << " if (Chain == N.getOperand(0)) {\n"
3217 << " Result = N; // No change\n"
3218 << " return;\n"
3219 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003220 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003221 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3222 << "New.Val, 0);\n"
3223 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3224 << "New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003225 << " Result = New.getValue(N.ResNo);\n"
3226 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003227 << " } else {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003228 << " SDOperand Flag;\n"
3229 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003230 << " if (Chain == N.getOperand(0) &&\n"
Evan Cheng34167212006-02-09 00:37:58 +00003231 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3232 << " Result = N; // No change\n"
3233 << " return;\n"
3234 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003235 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003236 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3237 << "New.Val, 0);\n"
3238 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3239 << "New.Val, 1);\n"
3240 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3241 << "New.Val, 2);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003242 << " Result = New.getValue(N.ResNo);\n"
3243 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003244 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003245 << " }\n"
3246 << " case ISD::CopyToReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003247 << " SDOperand Chain;\n"
3248 << " Select(Chain, N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003249 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Evan Cheng34167212006-02-09 00:37:58 +00003250 << " SDOperand Val;\n"
3251 << " Select(Val, N.getOperand(2));\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003252 << " Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003253 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003254 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003255 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003256 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3257 << "Result.Val, 0);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003258 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003259 << " SDOperand Flag(0, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003260 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003261 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003262 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003263 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003264 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3265 << "Result.Val, 0);\n"
3266 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3267 << "Result.Val, 1);\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003268 << " Result = Result.getValue(N.ResNo);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003269 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003270 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003271 << " }\n"
Chris Lattner947604b2006-03-24 21:52:20 +00003272 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003273
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003274
Chris Lattner602f6922006-01-04 00:25:00 +00003275 // Loop over all of the case statements, emiting a call to each method we
3276 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003277 for (std::map<Record*, std::vector<PatternToMatch*>,
3278 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3279 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003280 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00003281 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00003282 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Evan Cheng34167212006-02-09 00:37:58 +00003283 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
Chris Lattner81303322005-09-23 19:36:15 +00003284 }
Chris Lattner81303322005-09-23 19:36:15 +00003285
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003286 OS << " } // end of big switch.\n\n"
3287 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003288 << " if (N.getOpcode() != ISD::INTRINSIC) {\n"
3289 << " N.Val->dump(CurDAG);\n"
3290 << " } else {\n"
3291 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3292 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3293 << " std::cerr << \"intrinsic %\"<< "
3294 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3295 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003296 << " std::cerr << '\\n';\n"
3297 << " abort();\n"
3298 << "}\n";
3299}
3300
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003301void DAGISelEmitter::run(std::ostream &OS) {
3302 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3303 " target", OS);
3304
Chris Lattner1f39e292005-09-14 00:09:24 +00003305 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3306 << "// *** instruction selector class. These functions are really "
3307 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003308
Chris Lattner296dfe32005-09-24 00:50:51 +00003309 OS << "// Instance var to keep track of multiply used nodes that have \n"
3310 << "// already been selected.\n"
3311 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003312
3313 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003314 << "// and their place handle nodes.\n";
3315 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3316 OS << "// Instance var to keep track of mapping of place handle nodes\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003317 << "// and their replacement nodes.\n";
3318 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3319
3320 OS << "\n";
3321 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3322 << "std::set<SDNode *> &Visited) {\n";
3323 OS << " if (found || !Visited.insert(Use).second) return;\n";
3324 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3325 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3326 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3327 OS << " if (N != Def) {\n";
3328 OS << " findNonImmUse(N, Def, found, Visited);\n";
3329 OS << " } else {\n";
3330 OS << " found = true;\n";
3331 OS << " break;\n";
3332 OS << " }\n";
3333 OS << " }\n";
3334 OS << " }\n";
3335 OS << "}\n";
3336
3337 OS << "\n";
3338 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3339 OS << " std::set<SDNode *> Visited;\n";
3340 OS << " bool found = false;\n";
3341 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3342 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3343 OS << " if (N != Def) {\n";
3344 OS << " findNonImmUse(N, Def, found, Visited);\n";
3345 OS << " if (found) break;\n";
3346 OS << " }\n";
3347 OS << " }\n";
3348 OS << " return found;\n";
3349 OS << "}\n";
3350
3351 OS << "\n";
Evan Cheng024524f2006-02-06 06:03:35 +00003352 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003353 << "// handle node in ReplaceMap.\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003354 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3355 << "unsigned RNum) {\n";
3356 OS << " SDOperand N(H, HNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003357 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3358 OS << " if (HMI != HandleMap.end()) {\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003359 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003360 OS << " HandleMap.erase(N);\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003361 OS << " }\n";
3362 OS << "}\n";
3363
3364 OS << "\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003365 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3366 OS << "// handles.Some handles do not yet have replacements because the\n";
3367 OS << "// nodes they replacements have only dead readers.\n";
3368 OS << "void SelectDanglingHandles() {\n";
3369 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3370 << "HandleMap.begin(),\n"
3371 << " E = HandleMap.end(); I != E; ++I) {\n";
3372 OS << " SDOperand N = I->first;\n";
Evan Cheng34167212006-02-09 00:37:58 +00003373 OS << " SDOperand R;\n";
3374 OS << " Select(R, N.getValue(0));\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003375 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003376 OS << " }\n";
3377 OS << "}\n";
3378 OS << "\n";
3379 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003380 OS << "// specific nodes.\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003381 OS << "void ReplaceHandles() {\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003382 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3383 << "ReplaceMap.begin(),\n"
3384 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3385 OS << " SDOperand From = I->first;\n";
3386 OS << " SDOperand To = I->second;\n";
3387 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3388 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3389 OS << " SDNode *Use = *UI;\n";
3390 OS << " std::vector<SDOperand> Ops;\n";
3391 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3392 OS << " SDOperand O = Use->getOperand(i);\n";
3393 OS << " if (O.Val == From.Val)\n";
3394 OS << " Ops.push_back(To);\n";
3395 OS << " else\n";
3396 OS << " Ops.push_back(O);\n";
3397 OS << " }\n";
3398 OS << " SDOperand U = SDOperand(Use, 0);\n";
3399 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3400 OS << " }\n";
3401 OS << " }\n";
3402 OS << "}\n";
3403
3404 OS << "\n";
Evan Chenged66e852006-03-09 08:19:11 +00003405 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3406 OS << "// if the folding were to happen. This is called when, for example,\n";
3407 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3408 OS << "// then the resulting node's input chain would be the load's input\n";
3409 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3410 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3411 OS << "// with the other operands along with the input chain of the load.\n";
3412 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3413 << "SDNode *Chain, SDNode* &OldTF) {\n";
3414 OS << " OldTF = NULL;\n";
3415 OS << " if (N == Chain) {\n";
3416 OS << " return N->getOperand(0);\n";
3417 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3418 OS << " N->isOperand(Chain)) {\n";
3419 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3420 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3421 << "CodeGenMap.find(Ch);\n";
3422 OS << " if (CGMI != CodeGenMap.end())\n";
3423 OS << " return SDOperand(0, 0);\n";
3424 OS << " OldTF = Chain;\n";
3425 OS << " std::vector<SDOperand> Ops;\n";
3426 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3427 OS << " SDOperand Op = Chain->getOperand(i);\n";
3428 OS << " if (Op.Val == N)\n";
3429 OS << " Ops.push_back(N->getOperand(0));\n";
3430 OS << " else\n";
3431 OS << " Ops.push_back(Op);\n";
3432 OS << " }\n";
3433 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3434 OS << " }\n";
3435 OS << " return SDOperand(0, 0);\n";
3436 OS << "}\n";
3437
3438 OS << "\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003439 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3440 OS << "SDOperand SelectRoot(SDOperand N) {\n";
Evan Cheng34167212006-02-09 00:37:58 +00003441 OS << " SDOperand ResNode;\n";
3442 OS << " Select(ResNode, N);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003443 OS << " SelectDanglingHandles();\n";
3444 OS << " ReplaceHandles();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003445 OS << " ReplaceMap.clear();\n";
Evan Cheng34167212006-02-09 00:37:58 +00003446 OS << " return ResNode;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003447 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003448
Chris Lattner550525e2006-03-24 21:48:51 +00003449 Intrinsics = LoadIntrinsics(Records);
Chris Lattnerca559d02005-09-08 21:03:01 +00003450 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003451 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003452 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003453 ParsePatternFragments(OS);
3454 ParseInstructions();
3455 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003456
Chris Lattnere97603f2005-09-28 19:27:25 +00003457 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003458 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003459 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003460
Chris Lattnere46e17b2005-09-29 19:28:10 +00003461
3462 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3463 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003464 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3465 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003466 std::cerr << "\n";
3467 });
3468
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003469 // At this point, we have full information about the 'Patterns' we need to
3470 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003471 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003472 EmitInstructionSelector(OS);
3473
3474 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3475 E = PatternFragments.end(); I != E; ++I)
3476 delete I->second;
3477 PatternFragments.clear();
3478
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003479 Instructions.clear();
3480}