blob: a63d0603212118ff0726d66a8f6ccb06724fde7f [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) {
597 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000598 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000599 // If it's a regclass or something else known, include the type.
600 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
601 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000602 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
603 // Int inits are always integers. :)
604 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
605
606 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000607 // At some point, it may make sense for this tree pattern to have
608 // multiple types. Assert here that it does not, so we revisit this
609 // code when appropriate.
610 assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
611
612 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
Chris Lattner465c7372005-11-03 05:46:11 +0000613 // Make sure that the value is representable for this type.
614 if (Size < 32) {
615 int Val = (II->getValue() << (32-Size)) >> (32-Size);
616 if (Val != II->getValue())
617 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
618 "' is out of range for type 'MVT::" +
Nate Begemanb73628b2005-12-30 00:12:56 +0000619 getEnumName(getTypeNum(0)) + "'!");
Chris Lattner465c7372005-11-03 05:46:11 +0000620 }
621 }
622
623 return MadeChange;
624 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000625 return false;
626 }
Chris Lattner32707602005-09-08 23:22:48 +0000627
628 // special handling for set, which isn't really an SDNode.
629 if (getOperator()->getName() == "set") {
630 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000631 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
632 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000633
634 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000635 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
636 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000637 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
638 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000639 } else if (getOperator()->isSubClassOf("SDNode")) {
640 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
641
642 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
643 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000644 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000645 // Branch, etc. do not produce results and top-level forms in instr pattern
646 // must have void types.
647 if (NI.getNumResults() == 0)
648 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000649 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000650 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000651 const DAGInstruction &Inst =
652 TP.getDAGISelEmitter().getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000653 bool MadeChange = false;
654 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000655
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000656 assert(NumResults <= 1 &&
657 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000658 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000659 if (NumResults == 0) {
660 MadeChange = UpdateNodeType(MVT::isVoid, TP);
661 } else {
662 Record *ResultNode = Inst.getResult(0);
663 assert(ResultNode->isSubClassOf("RegisterClass") &&
664 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000665
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000666 const CodeGenRegisterClass &RC =
667 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000668 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000669 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000670
671 if (getNumChildren() != Inst.getNumOperands())
672 TP.error("Instruction '" + getOperator()->getName() + " expects " +
673 utostr(Inst.getNumOperands()) + " operands, not " +
674 utostr(getNumChildren()) + " operands!");
675 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000676 Record *OperandNode = Inst.getOperand(i);
677 MVT::ValueType VT;
678 if (OperandNode->isSubClassOf("RegisterClass")) {
679 const CodeGenRegisterClass &RC =
680 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000681 //VT = RC.getValueTypeNum(0);
682 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
683 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000684 } else if (OperandNode->isSubClassOf("Operand")) {
685 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000686 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000687 } else {
688 assert(0 && "Unknown operand type!");
689 abort();
690 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000691 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000692 }
693 return MadeChange;
694 } else {
695 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
696
Evan Chengf26ba692006-03-20 08:09:17 +0000697 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000698 if (getNumChildren() != 1)
699 TP.error("Node transform '" + getOperator()->getName() +
700 "' requires one operand!");
Evan Chengf26ba692006-03-20 08:09:17 +0000701 unsigned char ExtType0 = getExtTypeNum(0);
702 unsigned char ChildExtType0 = getChild(0)->getExtTypeNum(0);
703 if (ExtType0 == MVT::isInt ||
704 ExtType0 == MVT::isFP ||
705 ExtType0 == MVT::isUnknown ||
706 ChildExtType0 == MVT::isInt ||
707 ChildExtType0 == MVT::isFP ||
708 ChildExtType0 == MVT::isUnknown) {
709 // If either the output or input of the xform does not have exact
710 // type info. We assume they must be the same. Otherwise, it is perfectly
711 // legal to transform from one type to a completely different type.
712 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
713 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
714 return MadeChange;
715 }
716 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000717 }
Chris Lattner32707602005-09-08 23:22:48 +0000718}
719
Chris Lattnere97603f2005-09-28 19:27:25 +0000720/// canPatternMatch - If it is impossible for this pattern to match on this
721/// target, fill in Reason and return false. Otherwise, return true. This is
722/// used as a santity check for .td files (to prevent people from writing stuff
723/// that can never possibly work), and to prevent the pattern permuter from
724/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000725bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000726 if (isLeaf()) return true;
727
728 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
729 if (!getChild(i)->canPatternMatch(Reason, ISE))
730 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000731
Chris Lattnere97603f2005-09-28 19:27:25 +0000732 // If this node is a commutative operator, check that the LHS isn't an
733 // immediate.
734 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
735 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
736 // Scan all of the operands of the node and make sure that only the last one
737 // is a constant node.
738 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
739 if (!getChild(i)->isLeaf() &&
740 getChild(i)->getOperator()->getName() == "imm") {
741 Reason = "Immediate value must be on the RHS of commutative operators!";
742 return false;
743 }
744 }
745
746 return true;
747}
Chris Lattner32707602005-09-08 23:22:48 +0000748
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000749//===----------------------------------------------------------------------===//
750// TreePattern implementation
751//
752
Chris Lattneredbd8712005-10-21 01:19:59 +0000753TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000754 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000755 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000756 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
757 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000758}
759
Chris Lattneredbd8712005-10-21 01:19:59 +0000760TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000761 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000762 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000763 Trees.push_back(ParseTreePattern(Pat));
764}
765
Chris Lattneredbd8712005-10-21 01:19:59 +0000766TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000767 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000768 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000769 Trees.push_back(Pat);
770}
771
772
773
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000774void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000775 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000776 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000777}
778
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000779TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
780 Record *Operator = Dag->getNodeType();
781
782 if (Operator->isSubClassOf("ValueType")) {
783 // If the operator is a ValueType, then this must be "type cast" of a leaf
784 // node.
785 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000786 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000787
788 Init *Arg = Dag->getArg(0);
789 TreePatternNode *New;
790 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000791 Record *R = DI->getDef();
792 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
793 Dag->setArg(0, new DagInit(R,
794 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000795 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000796 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000797 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000798 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
799 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000800 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
801 New = new TreePatternNode(II);
802 if (!Dag->getArgName(0).empty())
803 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000804 } else {
805 Arg->dump();
806 error("Unknown leaf value for tree pattern!");
807 return 0;
808 }
809
Chris Lattner32707602005-09-08 23:22:48 +0000810 // Apply the type cast.
811 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000812 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000813 return New;
814 }
815
816 // Verify that this is something that makes sense for an operator.
817 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000818 !Operator->isSubClassOf("Instruction") &&
819 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000820 Operator->getName() != "set")
821 error("Unrecognized node '" + Operator->getName() + "'!");
822
Chris Lattneredbd8712005-10-21 01:19:59 +0000823 // Check to see if this is something that is illegal in an input pattern.
824 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
825 Operator->isSubClassOf("SDNodeXForm")))
826 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
827
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000828 std::vector<TreePatternNode*> Children;
829
830 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
831 Init *Arg = Dag->getArg(i);
832 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
833 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000834 if (Children.back()->getName().empty())
835 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000836 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
837 Record *R = DefI->getDef();
838 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
839 // TreePatternNode if its own.
840 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
841 Dag->setArg(i, new DagInit(R,
842 std::vector<std::pair<Init*, std::string> >()));
843 --i; // Revisit this node...
844 } else {
845 TreePatternNode *Node = new TreePatternNode(DefI);
846 Node->setName(Dag->getArgName(i));
847 Children.push_back(Node);
848
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000849 // Input argument?
850 if (R->getName() == "node") {
851 if (Dag->getArgName(i).empty())
852 error("'node' argument requires a name to match with operand list");
853 Args.push_back(Dag->getArgName(i));
854 }
855 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000856 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
857 TreePatternNode *Node = new TreePatternNode(II);
858 if (!Dag->getArgName(i).empty())
859 error("Constant int argument should not have a name!");
860 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000861 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000862 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000863 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000864 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000865 error("Unknown leaf value for tree pattern!");
866 }
867 }
868
869 return new TreePatternNode(Operator, Children);
870}
871
Chris Lattner32707602005-09-08 23:22:48 +0000872/// InferAllTypes - Infer/propagate as many types throughout the expression
873/// patterns as possible. Return true if all types are infered, false
874/// otherwise. Throw an exception if a type contradiction is found.
875bool TreePattern::InferAllTypes() {
876 bool MadeChange = true;
877 while (MadeChange) {
878 MadeChange = false;
879 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000880 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000881 }
882
883 bool HasUnresolvedTypes = false;
884 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
885 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
886 return !HasUnresolvedTypes;
887}
888
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000889void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000890 OS << getRecord()->getName();
891 if (!Args.empty()) {
892 OS << "(" << Args[0];
893 for (unsigned i = 1, e = Args.size(); i != e; ++i)
894 OS << ", " << Args[i];
895 OS << ")";
896 }
897 OS << ": ";
898
899 if (Trees.size() > 1)
900 OS << "[\n";
901 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
902 OS << "\t";
903 Trees[i]->print(OS);
904 OS << "\n";
905 }
906
907 if (Trees.size() > 1)
908 OS << "]\n";
909}
910
911void TreePattern::dump() const { print(std::cerr); }
912
913
914
915//===----------------------------------------------------------------------===//
916// DAGISelEmitter implementation
917//
918
Chris Lattnerca559d02005-09-08 21:03:01 +0000919// Parse all of the SDNode definitions for the target, populating SDNodes.
920void DAGISelEmitter::ParseNodeInfo() {
921 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
922 while (!Nodes.empty()) {
923 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
924 Nodes.pop_back();
925 }
926}
927
Chris Lattner24eeeb82005-09-13 21:51:00 +0000928/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
929/// map, and emit them to the file as functions.
930void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
931 OS << "\n// Node transformations.\n";
932 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
933 while (!Xforms.empty()) {
934 Record *XFormNode = Xforms.back();
935 Record *SDNode = XFormNode->getValueAsDef("Opcode");
936 std::string Code = XFormNode->getValueAsCode("XFormFunction");
937 SDNodeXForms.insert(std::make_pair(XFormNode,
938 std::make_pair(SDNode, Code)));
939
Chris Lattner1048b7a2005-09-13 22:03:37 +0000940 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000941 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
942 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
943
Chris Lattner1048b7a2005-09-13 22:03:37 +0000944 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000945 << "(SDNode *" << C2 << ") {\n";
946 if (ClassName != "SDNode")
947 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
948 OS << Code << "\n}\n";
949 }
950
951 Xforms.pop_back();
952 }
953}
954
Evan Cheng0fc71982005-12-08 02:00:36 +0000955void DAGISelEmitter::ParseComplexPatterns() {
956 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
957 while (!AMs.empty()) {
958 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
959 AMs.pop_back();
960 }
961}
Chris Lattner24eeeb82005-09-13 21:51:00 +0000962
963
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000964/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
965/// file, building up the PatternFragments map. After we've collected them all,
966/// inline fragments together as necessary, so that there are no references left
967/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000968///
969/// This also emits all of the predicate functions to the output file.
970///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000971void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000972 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
973
974 // First step, parse all of the fragments and emit predicate functions.
975 OS << "\n// Predicate functions.\n";
976 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000977 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000978 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000979 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000980
981 // Validate the argument list, converting it to map, to discard duplicates.
982 std::vector<std::string> &Args = P->getArgList();
983 std::set<std::string> OperandsMap(Args.begin(), Args.end());
984
985 if (OperandsMap.count(""))
986 P->error("Cannot have unnamed 'node' values in pattern fragment!");
987
988 // Parse the operands list.
989 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
990 if (OpsList->getNodeType()->getName() != "ops")
991 P->error("Operands list should start with '(ops ... '!");
992
993 // Copy over the arguments.
994 Args.clear();
995 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
996 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
997 static_cast<DefInit*>(OpsList->getArg(j))->
998 getDef()->getName() != "node")
999 P->error("Operands list should all be 'node' values.");
1000 if (OpsList->getArgName(j).empty())
1001 P->error("Operands list should have names for each operand!");
1002 if (!OperandsMap.count(OpsList->getArgName(j)))
1003 P->error("'" + OpsList->getArgName(j) +
1004 "' does not occur in pattern or was multiply specified!");
1005 OperandsMap.erase(OpsList->getArgName(j));
1006 Args.push_back(OpsList->getArgName(j));
1007 }
1008
1009 if (!OperandsMap.empty())
1010 P->error("Operands list does not contain an entry for operand '" +
1011 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001012
1013 // If there is a code init for this fragment, emit the predicate code and
1014 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001015 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1016 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +00001017 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001018 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +00001019 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001020 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1021
Chris Lattner1048b7a2005-09-13 22:03:37 +00001022 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001023 << "(SDNode *" << C2 << ") {\n";
1024 if (ClassName != "SDNode")
1025 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +00001026 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001027 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001028 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001029
1030 // If there is a node transformation corresponding to this, keep track of
1031 // it.
1032 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1033 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001034 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001035 }
1036
1037 OS << "\n\n";
1038
1039 // Now that we've parsed all of the tree fragments, do a closure on them so
1040 // that there are not references to PatFrags left inside of them.
1041 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1042 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001043 TreePattern *ThePat = I->second;
1044 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001045
Chris Lattner32707602005-09-08 23:22:48 +00001046 // Infer as many types as possible. Don't worry about it if we don't infer
1047 // all of them, some may depend on the inputs of the pattern.
1048 try {
1049 ThePat->InferAllTypes();
1050 } catch (...) {
1051 // If this pattern fragment is not supported by this target (no types can
1052 // satisfy its constraints), just ignore it. If the bogus pattern is
1053 // actually used by instructions, the type consistency error will be
1054 // reported there.
1055 }
1056
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001057 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001058 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001059 }
1060}
1061
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001062/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001063/// instruction input. Return true if this is a real use.
1064static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001065 std::map<std::string, TreePatternNode*> &InstInputs,
1066 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001067 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001068 if (Pat->getName().empty()) {
1069 if (Pat->isLeaf()) {
1070 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1071 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1072 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001073 else if (DI && DI->getDef()->isSubClassOf("Register"))
1074 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001075 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001076 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001077 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001078
1079 Record *Rec;
1080 if (Pat->isLeaf()) {
1081 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1082 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1083 Rec = DI->getDef();
1084 } else {
1085 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1086 Rec = Pat->getOperator();
1087 }
1088
Evan Cheng01f318b2005-12-14 02:21:57 +00001089 // SRCVALUE nodes are ignored.
1090 if (Rec->getName() == "srcvalue")
1091 return false;
1092
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001093 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1094 if (!Slot) {
1095 Slot = Pat;
1096 } else {
1097 Record *SlotRec;
1098 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001099 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001100 } else {
1101 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1102 SlotRec = Slot->getOperator();
1103 }
1104
1105 // Ensure that the inputs agree if we've already seen this input.
1106 if (Rec != SlotRec)
1107 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001108 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001109 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1110 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001111 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001112}
1113
1114/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1115/// part of "I", the instruction), computing the set of inputs and outputs of
1116/// the pattern. Report errors if we see anything naughty.
1117void DAGISelEmitter::
1118FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1119 std::map<std::string, TreePatternNode*> &InstInputs,
Evan Cheng420132e2006-03-20 06:04:09 +00001120 std::map<std::string, TreePatternNode*> &InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001121 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001122 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001123 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001124 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001125 if (!isUse && Pat->getTransformFn())
1126 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001127 return;
1128 } else if (Pat->getOperator()->getName() != "set") {
1129 // If this is not a set, verify that the children nodes are not void typed,
1130 // and recurse.
1131 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001132 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001133 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001134 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001135 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001136 }
1137
1138 // If this is a non-leaf node with no children, treat it basically as if
1139 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001140 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001141 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001142 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001143
Chris Lattnerf1311842005-09-14 23:05:13 +00001144 if (!isUse && Pat->getTransformFn())
1145 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001146 return;
1147 }
1148
1149 // Otherwise, this is a set, validate and collect instruction results.
1150 if (Pat->getNumChildren() == 0)
1151 I->error("set requires operands!");
1152 else if (Pat->getNumChildren() & 1)
1153 I->error("set requires an even number of operands");
1154
Chris Lattnerf1311842005-09-14 23:05:13 +00001155 if (Pat->getTransformFn())
1156 I->error("Cannot specify a transform function on a set node!");
1157
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001158 // Check the set destinations.
1159 unsigned NumValues = Pat->getNumChildren()/2;
1160 for (unsigned i = 0; i != NumValues; ++i) {
1161 TreePatternNode *Dest = Pat->getChild(i);
1162 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001163 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001164
1165 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1166 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001167 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001168
Evan Chengbcecf332005-12-17 01:19:28 +00001169 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1170 if (Dest->getName().empty())
1171 I->error("set destination must have a name!");
1172 if (InstResults.count(Dest->getName()))
1173 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001174 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001175 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001176 InstImpResults.push_back(Val->getDef());
1177 } else {
1178 I->error("set destination should be a register!");
1179 }
1180
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001181 // Verify and collect info from the computation.
1182 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001183 InstInputs, InstResults,
1184 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001185 }
1186}
1187
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001188/// ParseInstructions - Parse all of the instructions, inlining and resolving
1189/// any fragments involved. This populates the Instructions list with fully
1190/// resolved instructions.
1191void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001192 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1193
1194 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001195 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001196
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001197 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1198 LI = Instrs[i]->getValueAsListInit("Pattern");
1199
1200 // If there is no pattern, only collect minimal information about the
1201 // instruction for its operand list. We have to assume that there is one
1202 // result, as we have no detailed info.
1203 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001204 std::vector<Record*> Results;
1205 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001206
1207 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001208
Evan Cheng3a217f32005-12-22 02:35:21 +00001209 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001210 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001211 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001212 // These produce no results
1213 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1214 Operands.push_back(InstInfo.OperandList[j].Rec);
1215 } else {
1216 // Assume the first operand is the result.
1217 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001218
Evan Cheng3a217f32005-12-22 02:35:21 +00001219 // The rest are inputs.
1220 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1221 Operands.push_back(InstInfo.OperandList[j].Rec);
1222 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001223 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001224
1225 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001226 std::vector<Record*> ImpResults;
1227 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001228 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001229 DAGInstruction(0, Results, Operands, ImpResults,
1230 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001231 continue; // no pattern.
1232 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001233
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001234 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001235 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001236 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001237 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001238
Chris Lattner95f6b762005-09-08 23:26:30 +00001239 // Infer as many types as possible. If we cannot infer all of them, we can
1240 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001241 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001242 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001243
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001244 // InstInputs - Keep track of all of the inputs of the instruction, along
1245 // with the record they are declared as.
1246 std::map<std::string, TreePatternNode*> InstInputs;
1247
1248 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001249 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001250 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001251
1252 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001253 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001254
Chris Lattner1f39e292005-09-14 00:09:24 +00001255 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001256 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001257 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1258 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001259 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001260 I->error("Top-level forms in instruction pattern should have"
1261 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001262
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001263 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001264 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001265 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001266 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001267
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001268 // Now that we have inputs and outputs of the pattern, inspect the operands
1269 // list for the instruction. This determines the order that operands are
1270 // added to the machine instruction the node corresponds to.
1271 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001272
1273 // Parse the operands list from the (ops) list, validating it.
1274 std::vector<std::string> &Args = I->getArgList();
1275 assert(Args.empty() && "Args list should still be empty here!");
1276 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1277
1278 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001279 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001280 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001281 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001282 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001283 I->error("'" + InstResults.begin()->first +
1284 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001285 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001286
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001287 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001288 TreePatternNode *RNode = InstResults[OpName];
1289 if (i == 0)
1290 Res0Node = RNode;
1291 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001292 if (R == 0)
1293 I->error("Operand $" + OpName + " should be a set destination: all "
1294 "outputs must occur before inputs in operand list!");
1295
1296 if (CGI.OperandList[i].Rec != R)
1297 I->error("Operand $" + OpName + " class mismatch!");
1298
Chris Lattnerae6d8282005-09-15 21:51:12 +00001299 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001300 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001301
Chris Lattner39e8af92005-09-14 18:19:25 +00001302 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001303 InstResults.erase(OpName);
1304 }
1305
Chris Lattner0b592252005-09-14 21:59:34 +00001306 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1307 // the copy while we're checking the inputs.
1308 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001309
1310 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001311 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001312 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1313 const std::string &OpName = CGI.OperandList[i].Name;
1314 if (OpName.empty())
1315 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1316
Chris Lattner0b592252005-09-14 21:59:34 +00001317 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001318 I->error("Operand $" + OpName +
1319 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001320 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001321 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001322
1323 if (InVal->isLeaf() &&
1324 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1325 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001326 if (CGI.OperandList[i].Rec != InRec &&
1327 !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001328 I->error("Operand $" + OpName + "'s register class disagrees"
1329 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001330 }
1331 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001332
Chris Lattner2175c182005-09-14 23:01:59 +00001333 // Construct the result for the dest-pattern operand list.
1334 TreePatternNode *OpNode = InVal->clone();
1335
1336 // No predicate is useful on the result.
1337 OpNode->setPredicateFn("");
1338
1339 // Promote the xform function to be an explicit node if set.
1340 if (Record *Xform = OpNode->getTransformFn()) {
1341 OpNode->setTransformFn(0);
1342 std::vector<TreePatternNode*> Children;
1343 Children.push_back(OpNode);
1344 OpNode = new TreePatternNode(Xform, Children);
1345 }
1346
1347 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001348 }
1349
Chris Lattner0b592252005-09-14 21:59:34 +00001350 if (!InstInputsCheck.empty())
1351 I->error("Input operand $" + InstInputsCheck.begin()->first +
1352 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001353
1354 TreePatternNode *ResultPattern =
1355 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001356 // Copy fully inferred output node type to instruction result pattern.
1357 if (NumResults > 0)
1358 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001359
1360 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001361 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001362 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1363
1364 // Use a temporary tree pattern to infer all types and make sure that the
1365 // constructed result is correct. This depends on the instruction already
1366 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001367 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001368 Temp.InferAllTypes();
1369
1370 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1371 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001372
Chris Lattner32707602005-09-08 23:22:48 +00001373 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001374 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001375
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001376 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001377 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1378 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001379 DAGInstruction &TheInst = II->second;
1380 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001381 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001382
Chris Lattner1f39e292005-09-14 00:09:24 +00001383 if (I->getNumTrees() != 1) {
1384 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1385 continue;
1386 }
1387 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001388 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001389 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001390 if (Pattern->getNumChildren() != 2)
1391 continue; // Not a set of a single value (not handled so far)
1392
1393 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001394 } else{
1395 // Not a set (store or something?)
1396 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001397 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001398
1399 std::string Reason;
1400 if (!SrcPattern->canPatternMatch(Reason, *this))
1401 I->error("Instruction can never match: " + Reason);
1402
Evan Cheng58e84a62005-12-14 22:02:59 +00001403 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001404 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001405 PatternsToMatch.
1406 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1407 SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001408 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001409}
1410
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001411void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001412 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001413
Chris Lattnerabbb6052005-09-15 21:42:00 +00001414 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001415 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001416 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001417
Chris Lattnerabbb6052005-09-15 21:42:00 +00001418 // Inline pattern fragments into it.
1419 Pattern->InlinePatternFragments();
1420
1421 // Infer as many types as possible. If we cannot infer all of them, we can
1422 // never do anything with this pattern: report it to the user.
1423 if (!Pattern->InferAllTypes())
1424 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001425
1426 // Validate that the input pattern is correct.
1427 {
1428 std::map<std::string, TreePatternNode*> InstInputs;
Evan Cheng420132e2006-03-20 06:04:09 +00001429 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001430 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001431 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001432 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001433 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001434 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001435 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001436
1437 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1438 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001439
1440 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001441 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001442
1443 // Inline pattern fragments into it.
1444 Result->InlinePatternFragments();
1445
1446 // Infer as many types as possible. If we cannot infer all of them, we can
1447 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001448 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001449 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001450
1451 if (Result->getNumTrees() != 1)
1452 Result->error("Cannot handle instructions producing instructions "
1453 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001454
1455 std::string Reason;
1456 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1457 Pattern->error("Pattern can never match: " + Reason);
1458
Evan Cheng58e84a62005-12-14 22:02:59 +00001459 PatternsToMatch.
1460 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1461 Pattern->getOnlyTree(),
1462 Result->getOnlyTree()));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001463 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001464}
1465
Chris Lattnere46e17b2005-09-29 19:28:10 +00001466/// CombineChildVariants - Given a bunch of permutations of each child of the
1467/// 'operator' node, put them together in all possible ways.
1468static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001469 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001470 std::vector<TreePatternNode*> &OutVariants,
1471 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001472 // Make sure that each operand has at least one variant to choose from.
1473 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1474 if (ChildVariants[i].empty())
1475 return;
1476
Chris Lattnere46e17b2005-09-29 19:28:10 +00001477 // The end result is an all-pairs construction of the resultant pattern.
1478 std::vector<unsigned> Idxs;
1479 Idxs.resize(ChildVariants.size());
1480 bool NotDone = true;
1481 while (NotDone) {
1482 // Create the variant and add it to the output list.
1483 std::vector<TreePatternNode*> NewChildren;
1484 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1485 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1486 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1487
1488 // Copy over properties.
1489 R->setName(Orig->getName());
1490 R->setPredicateFn(Orig->getPredicateFn());
1491 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001492 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001493
1494 // If this pattern cannot every match, do not include it as a variant.
1495 std::string ErrString;
1496 if (!R->canPatternMatch(ErrString, ISE)) {
1497 delete R;
1498 } else {
1499 bool AlreadyExists = false;
1500
1501 // Scan to see if this pattern has already been emitted. We can get
1502 // duplication due to things like commuting:
1503 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1504 // which are the same pattern. Ignore the dups.
1505 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1506 if (R->isIsomorphicTo(OutVariants[i])) {
1507 AlreadyExists = true;
1508 break;
1509 }
1510
1511 if (AlreadyExists)
1512 delete R;
1513 else
1514 OutVariants.push_back(R);
1515 }
1516
1517 // Increment indices to the next permutation.
1518 NotDone = false;
1519 // Look for something we can increment without causing a wrap-around.
1520 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1521 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1522 NotDone = true; // Found something to increment.
1523 break;
1524 }
1525 Idxs[IdxsIdx] = 0;
1526 }
1527 }
1528}
1529
Chris Lattneraf302912005-09-29 22:36:54 +00001530/// CombineChildVariants - A helper function for binary operators.
1531///
1532static void CombineChildVariants(TreePatternNode *Orig,
1533 const std::vector<TreePatternNode*> &LHS,
1534 const std::vector<TreePatternNode*> &RHS,
1535 std::vector<TreePatternNode*> &OutVariants,
1536 DAGISelEmitter &ISE) {
1537 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1538 ChildVariants.push_back(LHS);
1539 ChildVariants.push_back(RHS);
1540 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1541}
1542
1543
1544static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1545 std::vector<TreePatternNode *> &Children) {
1546 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1547 Record *Operator = N->getOperator();
1548
1549 // Only permit raw nodes.
1550 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1551 N->getTransformFn()) {
1552 Children.push_back(N);
1553 return;
1554 }
1555
1556 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1557 Children.push_back(N->getChild(0));
1558 else
1559 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1560
1561 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1562 Children.push_back(N->getChild(1));
1563 else
1564 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1565}
1566
Chris Lattnere46e17b2005-09-29 19:28:10 +00001567/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1568/// the (potentially recursive) pattern by using algebraic laws.
1569///
1570static void GenerateVariantsOf(TreePatternNode *N,
1571 std::vector<TreePatternNode*> &OutVariants,
1572 DAGISelEmitter &ISE) {
1573 // We cannot permute leaves.
1574 if (N->isLeaf()) {
1575 OutVariants.push_back(N);
1576 return;
1577 }
1578
1579 // Look up interesting info about the node.
1580 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1581
1582 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001583 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1584 // Reassociate by pulling together all of the linked operators
1585 std::vector<TreePatternNode*> MaximalChildren;
1586 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1587
1588 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1589 // permutations.
1590 if (MaximalChildren.size() == 3) {
1591 // Find the variants of all of our maximal children.
1592 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1593 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1594 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1595 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1596
1597 // There are only two ways we can permute the tree:
1598 // (A op B) op C and A op (B op C)
1599 // Within these forms, we can also permute A/B/C.
1600
1601 // Generate legal pair permutations of A/B/C.
1602 std::vector<TreePatternNode*> ABVariants;
1603 std::vector<TreePatternNode*> BAVariants;
1604 std::vector<TreePatternNode*> ACVariants;
1605 std::vector<TreePatternNode*> CAVariants;
1606 std::vector<TreePatternNode*> BCVariants;
1607 std::vector<TreePatternNode*> CBVariants;
1608 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1609 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1610 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1611 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1612 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1613 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1614
1615 // Combine those into the result: (x op x) op x
1616 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1617 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1618 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1619 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1620 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1621 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1622
1623 // Combine those into the result: x op (x op x)
1624 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1625 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1626 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1627 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1628 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1629 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1630 return;
1631 }
1632 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001633
1634 // Compute permutations of all children.
1635 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1636 ChildVariants.resize(N->getNumChildren());
1637 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1638 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1639
1640 // Build all permutations based on how the children were formed.
1641 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1642
1643 // If this node is commutative, consider the commuted order.
1644 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1645 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001646 // Consider the commuted order.
1647 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1648 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001649 }
1650}
1651
1652
Chris Lattnere97603f2005-09-28 19:27:25 +00001653// GenerateVariants - Generate variants. For example, commutative patterns can
1654// match multiple ways. Add them to PatternsToMatch as well.
1655void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001656
1657 DEBUG(std::cerr << "Generating instruction variants.\n");
1658
1659 // Loop over all of the patterns we've collected, checking to see if we can
1660 // generate variants of the instruction, through the exploitation of
1661 // identities. This permits the target to provide agressive matching without
1662 // the .td file having to contain tons of variants of instructions.
1663 //
1664 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1665 // intentionally do not reconsider these. Any variants of added patterns have
1666 // already been added.
1667 //
1668 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1669 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001670 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001671
1672 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001673 Variants.erase(Variants.begin()); // Remove the original pattern.
1674
1675 if (Variants.empty()) // No variants for this pattern.
1676 continue;
1677
1678 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001679 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001680 std::cerr << "\n");
1681
1682 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1683 TreePatternNode *Variant = Variants[v];
1684
1685 DEBUG(std::cerr << " VAR#" << v << ": ";
1686 Variant->dump();
1687 std::cerr << "\n");
1688
1689 // Scan to see if an instruction or explicit pattern already matches this.
1690 bool AlreadyExists = false;
1691 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1692 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001693 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001694 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1695 AlreadyExists = true;
1696 break;
1697 }
1698 }
1699 // If we already have it, ignore the variant.
1700 if (AlreadyExists) continue;
1701
1702 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001703 PatternsToMatch.
1704 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1705 Variant, PatternsToMatch[i].getDstPattern()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001706 }
1707
1708 DEBUG(std::cerr << "\n");
1709 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001710}
1711
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001712
Evan Cheng0fc71982005-12-08 02:00:36 +00001713// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1714// ComplexPattern.
1715static bool NodeIsComplexPattern(TreePatternNode *N)
1716{
1717 return (N->isLeaf() &&
1718 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1719 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1720 isSubClassOf("ComplexPattern"));
1721}
1722
1723// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1724// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1725static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1726 DAGISelEmitter &ISE)
1727{
1728 if (N->isLeaf() &&
1729 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1730 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1731 isSubClassOf("ComplexPattern")) {
1732 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1733 ->getDef());
1734 }
1735 return NULL;
1736}
1737
Chris Lattner05814af2005-09-28 17:57:56 +00001738/// getPatternSize - Return the 'size' of this pattern. We want to match large
1739/// patterns before small ones. This is used to determine the size of a
1740/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001741static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng4a7c2842006-01-06 22:19:44 +00001742 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1743 isExtFloatingPointInVTs(P->getExtTypes()) ||
1744 P->getExtTypeNum(0) == MVT::isVoid ||
1745 P->getExtTypeNum(0) == MVT::Flag &&
1746 "Not a valid pattern node to size!");
Evan Chenge1050d62006-01-06 02:30:23 +00001747 unsigned Size = 2; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00001748 // If the root node is a ConstantSDNode, increases its size.
1749 // e.g. (set R32:$dst, 0).
1750 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1751 Size++;
Evan Cheng0fc71982005-12-08 02:00:36 +00001752
1753 // FIXME: This is a hack to statically increase the priority of patterns
1754 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1755 // Later we can allow complexity / cost for each pattern to be (optionally)
1756 // specified. To get best possible pattern match we'll need to dynamically
1757 // calculate the complexity of all patterns a dag can potentially map to.
1758 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1759 if (AM)
Evan Cheng4a7c2842006-01-06 22:19:44 +00001760 Size += AM->getNumOperands() * 2;
Chris Lattner3e179802006-02-03 18:06:02 +00001761
1762 // If this node has some predicate function that must match, it adds to the
1763 // complexity of this node.
1764 if (!P->getPredicateFn().empty())
1765 ++Size;
1766
Chris Lattner05814af2005-09-28 17:57:56 +00001767 // Count children in the count if they are also nodes.
1768 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1769 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001770 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001771 Size += getPatternSize(Child, ISE);
1772 else if (Child->isLeaf()) {
1773 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner3e179802006-02-03 18:06:02 +00001774 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
Evan Cheng4a7c2842006-01-06 22:19:44 +00001775 else if (NodeIsComplexPattern(Child))
1776 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00001777 else if (!Child->getPredicateFn().empty())
1778 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001779 }
Chris Lattner05814af2005-09-28 17:57:56 +00001780 }
1781
1782 return Size;
1783}
1784
1785/// getResultPatternCost - Compute the number of instructions for this pattern.
1786/// This is a temporary hack. We should really include the instruction
1787/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00001788static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00001789 if (P->isLeaf()) return 0;
1790
Evan Chengfbad7082006-02-18 02:33:09 +00001791 unsigned Cost = 0;
1792 Record *Op = P->getOperator();
1793 if (Op->isSubClassOf("Instruction")) {
1794 Cost++;
1795 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1796 if (II.usesCustomDAGSchedInserter)
1797 Cost += 10;
1798 }
Chris Lattner05814af2005-09-28 17:57:56 +00001799 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00001800 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001801 return Cost;
1802}
1803
1804// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1805// In particular, we want to match maximal patterns first and lowest cost within
1806// a particular complexity first.
1807struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001808 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1809 DAGISelEmitter &ISE;
1810
Evan Cheng58e84a62005-12-14 22:02:59 +00001811 bool operator()(PatternToMatch *LHS,
1812 PatternToMatch *RHS) {
1813 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1814 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001815 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1816 if (LHSSize < RHSSize) return false;
1817
1818 // If the patterns have equal complexity, compare generated instruction cost
Evan Chengfbad7082006-02-18 02:33:09 +00001819 return getResultPatternCost(LHS->getDstPattern(), ISE) <
1820 getResultPatternCost(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001821 }
1822};
1823
Nate Begeman6510b222005-12-01 04:51:06 +00001824/// getRegisterValueType - Look up and return the first ValueType of specified
1825/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001826static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001827 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1828 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001829 return MVT::Other;
1830}
1831
Chris Lattner72fe91c2005-09-24 00:40:24 +00001832
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001833/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1834/// type information from it.
1835static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001836 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001837 if (!N->isLeaf())
1838 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1839 RemoveAllTypes(N->getChild(i));
1840}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001841
Chris Lattner0614b622005-11-02 06:49:14 +00001842Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1843 Record *N = Records.getDef(Name);
1844 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1845 return N;
1846}
1847
Evan Cheng51fecc82006-01-09 18:27:06 +00001848/// NodeHasProperty - return true if TreePatternNode has the specified
1849/// property.
1850static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1851 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001852{
1853 if (N->isLeaf()) return false;
1854 Record *Operator = N->getOperator();
1855 if (!Operator->isSubClassOf("SDNode")) return false;
1856
1857 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00001858 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00001859}
1860
Evan Cheng51fecc82006-01-09 18:27:06 +00001861static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1862 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001863{
Evan Cheng51fecc82006-01-09 18:27:06 +00001864 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00001865 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00001866
1867 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1868 TreePatternNode *Child = N->getChild(i);
1869 if (PatternHasProperty(Child, Property, ISE))
1870 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001871 }
1872
1873 return false;
1874}
1875
Evan Chengb915f312005-12-09 22:45:35 +00001876class PatternCodeEmitter {
1877private:
1878 DAGISelEmitter &ISE;
1879
Evan Cheng58e84a62005-12-14 22:02:59 +00001880 // Predicates.
1881 ListInit *Predicates;
1882 // Instruction selector pattern.
1883 TreePatternNode *Pattern;
1884 // Matched instruction.
1885 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001886
Evan Chengb915f312005-12-09 22:45:35 +00001887 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00001888 std::map<std::string, std::string> VariableMap;
1889 // Node to operator mapping
1890 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00001891 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001892 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00001893 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +00001894
Chris Lattner8a0604b2006-01-28 20:31:24 +00001895 /// GeneratedCode - This is the buffer that we emit code to. The first bool
1896 /// indicates whether this is an exit predicate (something that should be
1897 /// tested, and if true, the match fails) [when true] or normal code to emit
1898 /// [when false].
1899 std::vector<std::pair<bool, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00001900 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
1901 /// the set of patterns for each top-level opcode.
Evan Chengd7805a72006-02-09 07:16:09 +00001902 std::set<std::pair<bool, std::string> > &GeneratedDecl;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001903
Evan Chenge4a8a6e2006-02-03 06:22:41 +00001904 std::string ChainName;
Evan Chenged66e852006-03-09 08:19:11 +00001905 bool NewTF;
Evan Chenge41bf822006-02-05 06:43:12 +00001906 bool DoReplace;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001907 unsigned TmpNo;
1908
1909 void emitCheck(const std::string &S) {
1910 if (!S.empty())
1911 GeneratedCode.push_back(std::make_pair(true, S));
1912 }
1913 void emitCode(const std::string &S) {
1914 if (!S.empty())
1915 GeneratedCode.push_back(std::make_pair(false, S));
1916 }
Evan Chengd7805a72006-02-09 07:16:09 +00001917 void emitDecl(const std::string &S, bool isSDNode=false) {
Evan Cheng21ad3922006-02-07 00:37:41 +00001918 assert(!S.empty() && "Invalid declaration");
Evan Chengd7805a72006-02-09 07:16:09 +00001919 GeneratedDecl.insert(std::make_pair(isSDNode, S));
Evan Cheng21ad3922006-02-07 00:37:41 +00001920 }
Evan Chengb915f312005-12-09 22:45:35 +00001921public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001922 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1923 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng21ad3922006-02-07 00:37:41 +00001924 std::vector<std::pair<bool, std::string> > &gc,
Evan Chengd7805a72006-02-09 07:16:09 +00001925 std::set<std::pair<bool, std::string> > &gd,
Evan Cheng21ad3922006-02-07 00:37:41 +00001926 bool dorep)
Chris Lattner8a0604b2006-01-28 20:31:24 +00001927 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Chenged66e852006-03-09 08:19:11 +00001928 GeneratedCode(gc), GeneratedDecl(gd),
1929 NewTF(false), DoReplace(dorep), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00001930
1931 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1932 /// if the match fails. At this point, we already know that the opcode for N
1933 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00001934 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
1935 const std::string &RootName, const std::string &ParentName,
1936 const std::string &ChainSuffix, bool &FoundChain) {
1937 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00001938 // Emit instruction predicates. Each predicate is just a string for now.
1939 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001940 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00001941 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1942 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1943 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00001944 if (!Def->isSubClassOf("Predicate")) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001945 Def->dump();
1946 assert(0 && "Unknown predicate type!");
1947 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00001948 if (!PredicateCheck.empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00001949 PredicateCheck += " || ";
1950 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00001951 }
1952 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00001953
1954 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00001955 }
1956
Evan Chengb915f312005-12-09 22:45:35 +00001957 if (N->isLeaf()) {
1958 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001959 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00001960 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00001961 return;
1962 } else if (!NodeIsComplexPattern(N)) {
1963 assert(0 && "Cannot match this as a leaf value!");
1964 abort();
1965 }
1966 }
1967
Chris Lattner488580c2006-01-28 19:06:51 +00001968 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00001969 // we already saw this in the pattern, emit code to verify dagness.
1970 if (!N->getName().empty()) {
1971 std::string &VarMapEntry = VariableMap[N->getName()];
1972 if (VarMapEntry.empty()) {
1973 VarMapEntry = RootName;
1974 } else {
1975 // If we get here, this is a second reference to a specific name. Since
1976 // we already have checked that the first reference is valid, we don't
1977 // have to recursively match it, just check that it's the same as the
1978 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00001979 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00001980 return;
1981 }
Evan Chengf805c2e2006-01-12 19:35:54 +00001982
1983 if (!N->isLeaf())
1984 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00001985 }
1986
1987
1988 // Emit code to load the child nodes and match their contents recursively.
1989 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00001990 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
1991 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
1992 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00001993 bool EmittedUseCheck = false;
1994 bool EmittedSlctedCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00001995 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00001996 if (NodeHasChain)
1997 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00001998 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001999 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattner8a0604b2006-01-28 20:31:24 +00002000 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002001 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002002 EmittedUseCheck = true;
2003 // hasOneUse() check is not strong enough. If the original node has
2004 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002005 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002006 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002007 "))");
2008
Evan Cheng1feeeec2006-01-26 19:13:45 +00002009 EmittedSlctedCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002010 if (NodeHasChain) {
2011 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2012 // has a chain use.
2013 // This a workaround for this problem:
2014 //
2015 // [ch, r : ld]
2016 // ^ ^
2017 // | |
2018 // [XX]--/ \- [flag : cmp]
2019 // ^ ^
2020 // | |
2021 // \---[br flag]-
2022 //
2023 // cmp + br should be considered as a single node as they are flagged
2024 // together. So, if the ld is folded into the cmp, the XX node in the
2025 // graph is now both an operand and a use of the ld/cmp/br node.
2026 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2027 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2028
2029 // If the immediate use can somehow reach this node through another
2030 // path, then can't fold it either or it will create a cycle.
2031 // e.g. In the following diagram, XX can reach ld through YY. If
2032 // ld is folded into XX, then YY is both a predecessor and a successor
2033 // of XX.
2034 //
2035 // [ld]
2036 // ^ ^
2037 // | |
2038 // / \---
2039 // / [YY]
2040 // | ^
2041 // [XX]-------|
2042 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2043 if (PInfo.getNumOperands() > 1 ||
2044 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2045 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2046 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
Evan Cheng6f8aaf22006-03-07 08:31:27 +00002047 if (PInfo.getNumOperands() > 1) {
2048 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2049 ".Val)");
2050 } else {
2051 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2052 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2053 ".Val))");
2054 }
Evan Chenge41bf822006-02-05 06:43:12 +00002055 }
Evan Chengb915f312005-12-09 22:45:35 +00002056 }
Evan Chenge41bf822006-02-05 06:43:12 +00002057
Evan Chengc15d18c2006-01-27 22:13:45 +00002058 if (NodeHasChain) {
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002059 ChainName = "Chain" + ChainSuffix;
Evan Cheng21ad3922006-02-07 00:37:41 +00002060 emitDecl(ChainName);
Evan Chenged66e852006-03-09 08:19:11 +00002061 if (FoundChain) {
2062 // FIXME: temporary workaround for a common case where chain
2063 // is a TokenFactor and the previous "inner" chain is an operand.
2064 NewTF = true;
2065 emitDecl("OldTF", true);
2066 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2067 RootName + ".Val, Chain.Val, OldTF)).Val");
2068 } else {
2069 FoundChain = true;
2070 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2071 }
Evan Cheng1cf6db22006-01-06 00:41:12 +00002072 }
Evan Chengb915f312005-12-09 22:45:35 +00002073 }
2074
Evan Cheng54597732006-01-26 00:22:25 +00002075 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002076 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002077 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002078 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2079 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002080 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002081 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2082 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2083 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002084 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2085 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002086 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002087 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002088 }
Evan Cheng1feeeec2006-01-26 19:13:45 +00002089 if (!EmittedSlctedCheck)
2090 // hasOneUse() check is not strong enough. If the original node has
2091 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002092 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002093 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002094 "))");
Evan Cheng54597732006-01-26 00:22:25 +00002095 }
2096
Evan Chengb915f312005-12-09 22:45:35 +00002097 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002098 emitDecl(RootName + utostr(OpNo));
2099 emitCode(RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002100 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002101 TreePatternNode *Child = N->getChild(i);
2102
2103 if (!Child->isLeaf()) {
2104 // If it's not a leaf, recursively match.
2105 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002106 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002107 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002108 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2109 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002110 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002111 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2112 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002113 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002114 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002115 // we already saw this in the pattern, emit code to verify dagness.
2116 if (!Child->getName().empty()) {
2117 std::string &VarMapEntry = VariableMap[Child->getName()];
2118 if (VarMapEntry.empty()) {
2119 VarMapEntry = RootName + utostr(OpNo);
2120 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002121 // If we get here, this is a second reference to a specific name.
2122 // Since we already have checked that the first reference is valid,
2123 // we don't have to recursively match it, just check that it's the
2124 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002125 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002126 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002127 continue;
2128 }
2129 }
2130
2131 // Handle leaves of various types.
2132 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2133 Record *LeafRec = DI->getDef();
2134 if (LeafRec->isSubClassOf("RegisterClass")) {
2135 // Handle register references. Nothing to do here.
2136 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002137 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002138 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2139 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00002140 } else if (LeafRec->getName() == "srcvalue") {
2141 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002142 } else if (LeafRec->isSubClassOf("ValueType")) {
2143 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002144 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002145 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002146 } else if (LeafRec->isSubClassOf("CondCode")) {
2147 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002148 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002149 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002150 } else {
2151 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002152 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00002153 assert(0 && "Unknown leaf type!");
2154 }
Chris Lattner488580c2006-01-28 19:06:51 +00002155 } else if (IntInit *II =
2156 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002157 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2158 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002159 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002160 RootName + utostr(OpNo) + ")->getSignExtended();");
2161
2162 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002163 } else {
2164 Child->dump();
2165 assert(0 && "Unknown leaf type!");
2166 }
2167 }
2168 }
2169
2170 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002171 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002172 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002173 }
2174
2175 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2176 /// we actually have to build a DAG!
2177 std::pair<unsigned, unsigned>
2178 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
2179 // This is something selected from the pattern we matched.
2180 if (!N->getName().empty()) {
2181 assert(!isRoot && "Root of pattern cannot be a leaf!");
2182 std::string &Val = VariableMap[N->getName()];
2183 assert(!Val.empty() &&
2184 "Variable referenced but not defined and not caught earlier!");
2185 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2186 // Already selected this operand, just return the tmpval.
2187 return std::make_pair(1, atoi(Val.c_str()+3));
2188 }
2189
2190 const ComplexPattern *CP;
2191 unsigned ResNo = TmpNo++;
2192 unsigned NumRes = 1;
2193 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002194 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002195 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002196 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002197 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002198 case MVT::i1: CastType = "bool"; break;
2199 case MVT::i8: CastType = "unsigned char"; break;
2200 case MVT::i16: CastType = "unsigned short"; break;
2201 case MVT::i32: CastType = "unsigned"; break;
2202 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002203 }
Chris Lattner78593132006-01-29 20:01:35 +00002204 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
Andrew Lenharth2cba57c2006-01-29 05:17:22 +00002205 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
Evan Cheng21ad3922006-02-07 00:37:41 +00002206 emitDecl("Tmp" + utostr(ResNo));
2207 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002208 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2209 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengbb48e332006-01-12 07:54:57 +00002210 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002211 Record *Op = OperatorMap[N->getName()];
2212 // Transform ExternalSymbol to TargetExternalSymbol
2213 if (Op && Op->getName() == "externalsym") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002214 emitDecl("Tmp" + utostr(ResNo));
2215 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002216 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2217 Val + ")->getSymbol(), MVT::" +
2218 getEnumName(N->getTypeNum(0)) + ");");
2219 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002220 emitDecl("Tmp" + utostr(ResNo));
2221 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002222 }
Evan Chengb915f312005-12-09 22:45:35 +00002223 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002224 Record *Op = OperatorMap[N->getName()];
2225 // Transform GlobalAddress to TargetGlobalAddress
2226 if (Op && Op->getName() == "globaladdr") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002227 emitDecl("Tmp" + utostr(ResNo));
2228 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002229 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2230 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2231 ");");
2232 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002233 emitDecl("Tmp" + utostr(ResNo));
2234 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002235 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002236 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng21ad3922006-02-07 00:37:41 +00002237 emitDecl("Tmp" + utostr(ResNo));
2238 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengbb48e332006-01-12 07:54:57 +00002239 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002240 emitDecl("Tmp" + utostr(ResNo));
2241 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002242 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2243 std::string Fn = CP->getSelectFunc();
2244 NumRes = CP->getNumOperands();
Evan Cheng21ad3922006-02-07 00:37:41 +00002245 for (unsigned i = 0; i < NumRes; ++i)
2246 emitDecl("Tmp" + utostr(i+ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002247
Evan Cheng21ad3922006-02-07 00:37:41 +00002248 std::string Code = Fn + "(" + Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002249 for (unsigned i = 0; i < NumRes; i++)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002250 Code += ", Tmp" + utostr(i + ResNo);
2251 emitCheck(Code + ")");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002252
Evan Cheng2216d8a2006-02-05 05:22:18 +00002253 for (unsigned i = 0; i < NumRes; ++i)
Evan Cheng34167212006-02-09 00:37:58 +00002254 emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
Evan Cheng2216d8a2006-02-05 05:22:18 +00002255 utostr(i+ResNo) + ");");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002256
Evan Chengb915f312005-12-09 22:45:35 +00002257 TmpNo = ResNo + NumRes;
2258 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002259 emitDecl("Tmp" + utostr(ResNo));
Evan Cheng34167212006-02-09 00:37:58 +00002260 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002261 }
2262 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2263 // value if used multiple times by this pattern result.
2264 Val = "Tmp"+utostr(ResNo);
2265 return std::make_pair(NumRes, ResNo);
2266 }
2267
2268 if (N->isLeaf()) {
2269 // If this is an explicit register reference, handle it.
2270 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2271 unsigned ResNo = TmpNo++;
2272 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002273 emitDecl("Tmp" + utostr(ResNo));
2274 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002275 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2276 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002277 return std::make_pair(1, ResNo);
2278 }
2279 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2280 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002281 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng21ad3922006-02-07 00:37:41 +00002282 emitDecl("Tmp" + utostr(ResNo));
2283 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002284 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2285 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002286 return std::make_pair(1, ResNo);
2287 }
2288
2289 N->dump();
2290 assert(0 && "Unknown leaf type!");
2291 return std::make_pair(1, ~0U);
2292 }
2293
2294 Record *Op = N->getOperator();
2295 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002296 const CodeGenTarget &CGT = ISE.getTargetInfo();
2297 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002298 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002299 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2300 bool HasImpResults = Inst.getNumImpResults() > 0;
Evan Cheng54597732006-01-26 00:22:25 +00002301 bool HasOptInFlag = isRoot &&
2302 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002303 bool HasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002304 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2305 bool NodeHasOutFlag = HasImpResults ||
Evan Cheng51fecc82006-01-09 18:27:06 +00002306 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
Evan Cheng823b7522006-01-19 21:57:10 +00002307 bool NodeHasChain =
2308 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002309 bool HasChain = II.hasCtrlDep ||
2310 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
Evan Cheng4fba2812005-12-20 07:37:41 +00002311
Evan Cheng54597732006-01-26 00:22:25 +00002312 if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
Evan Cheng21ad3922006-02-07 00:37:41 +00002313 emitDecl("InFlag");
Evan Cheng54597732006-01-26 00:22:25 +00002314 if (HasOptInFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002315 emitCode("bool HasOptInFlag = false;");
Evan Cheng4fba2812005-12-20 07:37:41 +00002316
Evan Cheng823b7522006-01-19 21:57:10 +00002317 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002318 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002319 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2320 MVT::ValueType VT = Pattern->getTypeNum(i);
2321 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002322 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002323 }
2324
Evan Chengb915f312005-12-09 22:45:35 +00002325 // Determine operand emission order. Complex pattern first.
2326 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2327 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2328 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2329 TreePatternNode *Child = N->getChild(i);
2330 if (i == 0) {
2331 EmitOrder.push_back(std::make_pair(i, Child));
2332 OI = EmitOrder.begin();
2333 } else if (NodeIsComplexPattern(Child)) {
2334 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2335 } else {
2336 EmitOrder.push_back(std::make_pair(i, Child));
2337 }
2338 }
2339
2340 // Emit all of the operands.
2341 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2342 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2343 unsigned OpOrder = EmitOrder[i].first;
2344 TreePatternNode *Child = EmitOrder[i].second;
2345 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2346 NumTemps[OpOrder] = NumTemp;
2347 }
2348
2349 // List all the operands in the right order.
2350 std::vector<unsigned> Ops;
2351 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2352 for (unsigned j = 0; j < NumTemps[i].first; j++)
2353 Ops.push_back(NumTemps[i].second + j);
2354 }
2355
Evan Chengb915f312005-12-09 22:45:35 +00002356 // Emit all the chain and CopyToReg stuff.
Evan Chengb2c6d492006-01-11 22:16:13 +00002357 bool ChainEmitted = HasChain;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002358 if (HasChain)
Evan Cheng34167212006-02-09 00:37:58 +00002359 emitCode("Select(" + ChainName + ", " + ChainName + ");");
Evan Cheng54597732006-01-26 00:22:25 +00002360 if (HasInFlag || HasOptInFlag || HasImpInputs)
2361 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
Evan Chengb915f312005-12-09 22:45:35 +00002362
Evan Chengb915f312005-12-09 22:45:35 +00002363 unsigned NumResults = Inst.getNumResults();
2364 unsigned ResNo = TmpNo++;
2365 if (!isRoot) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002366 emitDecl("Tmp" + utostr(ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002367 std::string Code =
Evan Chengd7805a72006-02-09 07:16:09 +00002368 "Tmp" + utostr(ResNo) + " = SDOperand(CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002369 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002370 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002371 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002372 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002373 Code += ", MVT::Flag";
Evan Chengbcecf332005-12-17 01:19:28 +00002374
Evan Chengb915f312005-12-09 22:45:35 +00002375 unsigned LastOp = 0;
2376 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2377 LastOp = Ops[i];
Chris Lattner8a0604b2006-01-28 20:31:24 +00002378 Code += ", Tmp" + utostr(LastOp);
Evan Chengb915f312005-12-09 22:45:35 +00002379 }
Evan Chengd7805a72006-02-09 07:16:09 +00002380 emitCode(Code + "), 0);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002381 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002382 // Must have at least one result
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002383 emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002384 utostr(NumResults) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002385 }
Evan Cheng54597732006-01-26 00:22:25 +00002386 } else if (HasChain || NodeHasOutFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002387 if (HasOptInFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002388 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
Evan Chengd7805a72006-02-09 07:16:09 +00002389 emitDecl("ResNode", true);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002390 emitCode("if (HasOptInFlag)");
Evan Chengd7805a72006-02-09 07:16:09 +00002391 std::string Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002392 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002393
Evan Cheng9789aaa2006-01-24 20:46:50 +00002394 // Output order: results, chain, flags
2395 // Result types.
2396 if (NumResults > 0) {
2397 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002398 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002399 }
2400 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002401 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002402 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002403 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002404
2405 // Inputs.
2406 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002407 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002408 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002409 emitCode(Code + ", InFlag);");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002410
Chris Lattner8a0604b2006-01-28 20:31:24 +00002411 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002412 Code = " ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002413 II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002414
2415 // Output order: results, chain, flags
2416 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002417 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2418 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002419 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002420 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002421 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002422 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002423
2424 // Inputs.
2425 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002426 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002427 if (HasChain) Code += ", " + ChainName + ");";
Chris Lattner8a0604b2006-01-28 20:31:24 +00002428 emitCode(Code);
Evan Cheng9789aaa2006-01-24 20:46:50 +00002429 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002430 emitDecl("ResNode", true);
2431 std::string Code = "ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002432 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002433
2434 // Output order: results, chain, flags
2435 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002436 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2437 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002438 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002439 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002440 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002441 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002442
2443 // Inputs.
2444 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002445 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002446 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002447 if (HasInFlag || HasImpInputs) Code += ", InFlag";
2448 emitCode(Code + ");");
Evan Chengbcecf332005-12-17 01:19:28 +00002449 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002450
Evan Chenged66e852006-03-09 08:19:11 +00002451 if (NewTF)
2452 emitCode("if (OldTF) "
2453 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2454 ChainName + ".Val, 0);");
2455
2456 for (unsigned i = 0; i < NumResults; i++)
Evan Cheng67212a02006-02-09 22:12:27 +00002457 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002458 utostr(i) + ", ResNode, " + utostr(i) + ");");
Evan Chengf9fc25d2005-12-19 22:40:04 +00002459
Evan Cheng54597732006-01-26 00:22:25 +00002460 if (NodeHasOutFlag)
Evan Chengd7805a72006-02-09 07:16:09 +00002461 emitCode("InFlag = SDOperand(ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002462 utostr(NumResults + (unsigned)HasChain) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002463
Chris Lattner8a0604b2006-01-28 20:31:24 +00002464 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
Evan Chenged66e852006-03-09 08:19:11 +00002465 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2466 "0, ResNode, 0);");
2467 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00002468 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002469
Evan Chenge41bf822006-02-05 06:43:12 +00002470 if (NodeHasChain) {
Evan Cheng67212a02006-02-09 22:12:27 +00002471 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002472 utostr(PatResults) + ", ResNode, " +
2473 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002474 if (DoReplace)
Evan Chenged66e852006-03-09 08:19:11 +00002475 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2476 utostr(PatResults) + ", " + "ResNode, " +
2477 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002478 }
2479
Evan Cheng97938882005-12-22 02:24:50 +00002480 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002481 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002482 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng67212a02006-02-09 22:12:27 +00002483 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2484 FoldedChains[j].first + ".Val, " +
2485 utostr(FoldedChains[j].second) + ", ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002486 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002487
2488 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2489 std::string Code =
Evan Cheng67212a02006-02-09 22:12:27 +00002490 FoldedChains[j].first + ".Val, " +
2491 utostr(FoldedChains[j].second) + ", ";
2492 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002493 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002494 }
Evan Chengb915f312005-12-09 22:45:35 +00002495 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002496
Evan Cheng54597732006-01-26 00:22:25 +00002497 if (NodeHasOutFlag)
Evan Cheng67212a02006-02-09 22:12:27 +00002498 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002499 utostr(PatResults + (unsigned)NodeHasChain) +
2500 ", InFlag.Val, InFlag.ResNo);");
Evan Cheng97938882005-12-22 02:24:50 +00002501
Evan Chenged66e852006-03-09 08:19:11 +00002502 // User does not expect the instruction would produce a chain!
2503 bool AddedChain = HasChain && !NodeHasChain;
Evan Cheng54597732006-01-26 00:22:25 +00002504 if (AddedChain && NodeHasOutFlag) {
Evan Chenged66e852006-03-09 08:19:11 +00002505 if (PatResults == 0) {
Evan Chengd7805a72006-02-09 07:16:09 +00002506 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002507 } else {
Evan Chenged66e852006-03-09 08:19:11 +00002508 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
Evan Chengd7805a72006-02-09 07:16:09 +00002509 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002510 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002511 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002512 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002513 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002514 emitCode("Result = SDOperand(ResNode, N.ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002515 }
Evan Chengb915f312005-12-09 22:45:35 +00002516 } else {
2517 // If this instruction is the root, and if there is only one use of it,
2518 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002519 emitCode("if (N.Val->hasOneUse()) {");
Evan Cheng34167212006-02-09 00:37:58 +00002520 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002521 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002522 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002523 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002524 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002525 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002526 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002527 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002528 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002529 Code += ", InFlag";
2530 emitCode(Code + ");");
2531 emitCode("} else {");
Evan Chengd7805a72006-02-09 07:16:09 +00002532 emitDecl("ResNode", true);
2533 Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002534 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002535 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002536 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002537 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002538 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002539 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002540 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002541 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002542 Code += ", InFlag";
2543 emitCode(Code + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002544 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2545 "ResNode, 0);");
2546 emitCode(" Result = SDOperand(ResNode, 0);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002547 emitCode("}");
Evan Chengb915f312005-12-09 22:45:35 +00002548 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002549
Evan Cheng34167212006-02-09 00:37:58 +00002550 if (isRoot)
2551 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002552 return std::make_pair(1, ResNo);
2553 } else if (Op->isSubClassOf("SDNodeXForm")) {
2554 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002555 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002556 unsigned ResNo = TmpNo++;
Evan Cheng21ad3922006-02-07 00:37:41 +00002557 emitDecl("Tmp" + utostr(ResNo));
2558 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Chris Lattner8a0604b2006-01-28 20:31:24 +00002559 + "(Tmp" + utostr(OpVal) + ".Val);");
Evan Chengb915f312005-12-09 22:45:35 +00002560 if (isRoot) {
Evan Cheng67212a02006-02-09 22:12:27 +00002561 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2562 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2563 utostr(ResNo) + ".ResNo);");
Evan Cheng34167212006-02-09 00:37:58 +00002564 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2565 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002566 }
2567 return std::make_pair(1, ResNo);
2568 } else {
2569 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002570 std::cerr << "\n";
2571 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002572 }
2573 }
2574
Chris Lattner488580c2006-01-28 19:06:51 +00002575 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2576 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002577 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2578 /// for, this returns true otherwise false if Pat has all types.
2579 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2580 const std::string &Prefix) {
2581 // Did we find one?
2582 if (!Pat->hasTypeSet()) {
2583 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002584 Pat->setTypes(Other->getExtTypes());
Chris Lattner67a202b2006-01-28 20:43:52 +00002585 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002586 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002587 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002588 }
2589
Evan Cheng51fecc82006-01-09 18:27:06 +00002590 unsigned OpNo =
2591 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002592 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2593 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2594 Prefix + utostr(OpNo)))
2595 return true;
2596 return false;
2597 }
2598
2599private:
Evan Cheng54597732006-01-26 00:22:25 +00002600 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002601 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002602 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2603 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002604 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002605 unsigned OpNo =
2606 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002607 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2608 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002609 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2610 TreePatternNode *Child = N->getChild(i);
2611 if (!Child->isLeaf()) {
Evan Cheng54597732006-01-26 00:22:25 +00002612 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002613 } else {
2614 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002615 if (!Child->getName().empty()) {
2616 std::string Name = RootName + utostr(OpNo);
2617 if (Duplicates.find(Name) != Duplicates.end())
2618 // A duplicate! Do not emit a copy for this node.
2619 continue;
2620 }
2621
Evan Chengb915f312005-12-09 22:45:35 +00002622 Record *RR = DI->getDef();
2623 if (RR->isSubClassOf("Register")) {
2624 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002625 if (RVT == MVT::Flag) {
Evan Cheng34167212006-02-09 00:37:58 +00002626 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
Evan Chengb2c6d492006-01-11 22:16:13 +00002627 } else {
2628 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002629 emitDecl("Chain");
2630 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002631 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002632 ChainEmitted = true;
2633 }
Evan Cheng34167212006-02-09 00:37:58 +00002634 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2635 RootName + utostr(OpNo) + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002636 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002637 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
Evan Cheng34167212006-02-09 00:37:58 +00002638 ", MVT::" + getEnumName(RVT) + "), " +
Evan Chengd7805a72006-02-09 07:16:09 +00002639 RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng67212a02006-02-09 22:12:27 +00002640 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2641 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00002642 }
2643 }
2644 }
2645 }
2646 }
Evan Cheng54597732006-01-26 00:22:25 +00002647
2648 if (HasInFlag || HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002649 std::string Code;
Evan Cheng54597732006-01-26 00:22:25 +00002650 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002651 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2652 ") {");
2653 Code = " ";
Evan Cheng54597732006-01-26 00:22:25 +00002654 }
Evan Cheng34167212006-02-09 00:37:58 +00002655 emitCode(Code + "Select(InFlag, " + RootName +
2656 ".getOperand(" + utostr(OpNo) + "));");
Evan Cheng54597732006-01-26 00:22:25 +00002657 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002658 emitCode(" HasOptInFlag = true;");
2659 emitCode("}");
Evan Cheng54597732006-01-26 00:22:25 +00002660 }
2661 }
Evan Chengb915f312005-12-09 22:45:35 +00002662 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002663
2664 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002665 /// as specified by the instruction. It returns true if any copy is
2666 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002667 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002668 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002669 Record *Op = N->getOperator();
2670 if (Op->isSubClassOf("Instruction")) {
2671 const DAGInstruction &Inst = ISE.getInstruction(Op);
2672 const CodeGenTarget &CGT = ISE.getTargetInfo();
2673 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2674 unsigned NumImpResults = Inst.getNumImpResults();
2675 for (unsigned i = 0; i < NumImpResults; i++) {
2676 Record *RR = Inst.getImpResult(i);
2677 if (RR->isSubClassOf("Register")) {
2678 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2679 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002680 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002681 emitDecl("Chain");
2682 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002683 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002684 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002685 }
Evan Chengd7805a72006-02-09 07:16:09 +00002686 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002687 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00002688 ", InFlag).Val;");
2689 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2690 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002691 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002692 }
2693 }
2694 }
2695 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002696 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002697 }
Evan Chengb915f312005-12-09 22:45:35 +00002698};
2699
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002700/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2701/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00002702/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00002703void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Chenge41bf822006-02-05 06:43:12 +00002704 std::vector<std::pair<bool, std::string> > &GeneratedCode,
Evan Chengd7805a72006-02-09 07:16:09 +00002705 std::set<std::pair<bool, std::string> > &GeneratedDecl,
Evan Chenge41bf822006-02-05 06:43:12 +00002706 bool DoReplace) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002707 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2708 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Cheng21ad3922006-02-07 00:37:41 +00002709 GeneratedCode, GeneratedDecl, DoReplace);
Evan Chengb915f312005-12-09 22:45:35 +00002710
Chris Lattner8fc35682005-09-23 23:16:51 +00002711 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002712 bool FoundChain = false;
Evan Chenge41bf822006-02-05 06:43:12 +00002713 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002714
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002715 // TP - Get *SOME* tree pattern, we don't care which.
2716 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002717
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002718 // At this point, we know that we structurally match the pattern, but the
2719 // types of the nodes may not match. Figure out the fewest number of type
2720 // comparisons we need to emit. For example, if there is only one integer
2721 // type supported by a target, there should be no type comparisons at all for
2722 // integer patterns!
2723 //
2724 // To figure out the fewest number of type checks needed, clone the pattern,
2725 // remove the types, then perform type inference on the pattern as a whole.
2726 // If there are unresolved types, emit an explicit check for those types,
2727 // apply the type to the tree, then rerun type inference. Iterate until all
2728 // types are resolved.
2729 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002730 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002731 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002732
2733 do {
2734 // Resolve/propagate as many types as possible.
2735 try {
2736 bool MadeChange = true;
2737 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00002738 MadeChange = Pat->ApplyTypeConstraints(TP,
2739 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00002740 } catch (...) {
2741 assert(0 && "Error: could not find consistent types for something we"
2742 " already decided was ok!");
2743 abort();
2744 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002745
Chris Lattner7e82f132005-10-15 21:34:21 +00002746 // Insert a check for an unresolved type and add it to the tree. If we find
2747 // an unresolved type to add a check for, this returns true and we iterate,
2748 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002749 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002750
Evan Cheng58e84a62005-12-14 22:02:59 +00002751 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002752 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00002753}
2754
Chris Lattner24e00a42006-01-29 04:41:05 +00002755/// EraseCodeLine - Erase one code line from all of the patterns. If removing
2756/// a line causes any of them to be empty, remove them and return true when
2757/// done.
2758static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2759 std::vector<std::pair<bool, std::string> > > >
2760 &Patterns) {
2761 bool ErasedPatterns = false;
2762 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2763 Patterns[i].second.pop_back();
2764 if (Patterns[i].second.empty()) {
2765 Patterns.erase(Patterns.begin()+i);
2766 --i; --e;
2767 ErasedPatterns = true;
2768 }
2769 }
2770 return ErasedPatterns;
2771}
2772
Chris Lattner8bc74722006-01-29 04:25:26 +00002773/// EmitPatterns - Emit code for at least one pattern, but try to group common
2774/// code together between the patterns.
2775void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
2776 std::vector<std::pair<bool, std::string> > > >
2777 &Patterns, unsigned Indent,
2778 std::ostream &OS) {
2779 typedef std::pair<bool, std::string> CodeLine;
2780 typedef std::vector<CodeLine> CodeList;
2781 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2782
2783 if (Patterns.empty()) return;
2784
Chris Lattner24e00a42006-01-29 04:41:05 +00002785 // Figure out how many patterns share the next code line. Explicitly copy
2786 // FirstCodeLine so that we don't invalidate a reference when changing
2787 // Patterns.
2788 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00002789 unsigned LastMatch = Patterns.size()-1;
2790 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2791 --LastMatch;
2792
2793 // If not all patterns share this line, split the list into two pieces. The
2794 // first chunk will use this line, the second chunk won't.
2795 if (LastMatch != 0) {
2796 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2797 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2798
2799 // FIXME: Emit braces?
2800 if (Shared.size() == 1) {
2801 PatternToMatch &Pattern = *Shared.back().first;
2802 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2803 Pattern.getSrcPattern()->print(OS);
2804 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2805 Pattern.getDstPattern()->print(OS);
2806 OS << "\n";
2807 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2808 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00002809 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00002810 }
2811 if (!FirstCodeLine.first) {
2812 OS << std::string(Indent, ' ') << "{\n";
2813 Indent += 2;
2814 }
2815 EmitPatterns(Shared, Indent, OS);
2816 if (!FirstCodeLine.first) {
2817 Indent -= 2;
2818 OS << std::string(Indent, ' ') << "}\n";
2819 }
2820
2821 if (Other.size() == 1) {
2822 PatternToMatch &Pattern = *Other.back().first;
2823 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2824 Pattern.getSrcPattern()->print(OS);
2825 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2826 Pattern.getDstPattern()->print(OS);
2827 OS << "\n";
2828 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2829 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00002830 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00002831 }
2832 EmitPatterns(Other, Indent, OS);
2833 return;
2834 }
2835
Chris Lattner24e00a42006-01-29 04:41:05 +00002836 // Remove this code from all of the patterns that share it.
2837 bool ErasedPatterns = EraseCodeLine(Patterns);
2838
Chris Lattner8bc74722006-01-29 04:25:26 +00002839 bool isPredicate = FirstCodeLine.first;
2840
2841 // Otherwise, every pattern in the list has this line. Emit it.
2842 if (!isPredicate) {
2843 // Normal code.
2844 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2845 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00002846 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2847
2848 // If the next code line is another predicate, and if all of the pattern
2849 // in this group share the same next line, emit it inline now. Do this
2850 // until we run out of common predicates.
2851 while (!ErasedPatterns && Patterns.back().second.back().first) {
2852 // Check that all of fhe patterns in Patterns end with the same predicate.
2853 bool AllEndWithSamePredicate = true;
2854 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2855 if (Patterns[i].second.back() != Patterns.back().second.back()) {
2856 AllEndWithSamePredicate = false;
2857 break;
2858 }
2859 // If all of the predicates aren't the same, we can't share them.
2860 if (!AllEndWithSamePredicate) break;
2861
2862 // Otherwise we can. Emit it shared now.
2863 OS << " &&\n" << std::string(Indent+4, ' ')
2864 << Patterns.back().second.back().second;
2865 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00002866 }
Chris Lattner24e00a42006-01-29 04:41:05 +00002867
2868 OS << ") {\n";
2869 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00002870 }
2871
2872 EmitPatterns(Patterns, Indent, OS);
2873
2874 if (isPredicate)
2875 OS << std::string(Indent-2, ' ') << "}\n";
2876}
2877
2878
Chris Lattner37481472005-09-26 21:59:35 +00002879
2880namespace {
2881 /// CompareByRecordName - An ordering predicate that implements less-than by
2882 /// comparing the names records.
2883 struct CompareByRecordName {
2884 bool operator()(const Record *LHS, const Record *RHS) const {
2885 // Sort by name first.
2886 if (LHS->getName() < RHS->getName()) return true;
2887 // If both names are equal, sort by pointer.
2888 return LHS->getName() == RHS->getName() && LHS < RHS;
2889 }
2890 };
2891}
2892
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002893void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002894 std::string InstNS = Target.inst_begin()->second.Namespace;
2895 if (!InstNS.empty()) InstNS += "::";
2896
Chris Lattner602f6922006-01-04 00:25:00 +00002897 // Group the patterns by their top-level opcodes.
2898 std::map<Record*, std::vector<PatternToMatch*>,
2899 CompareByRecordName> PatternsByOpcode;
2900 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2901 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2902 if (!Node->isLeaf()) {
2903 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2904 } else {
2905 const ComplexPattern *CP;
2906 if (IntInit *II =
2907 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2908 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2909 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2910 std::vector<Record*> OpNodes = CP->getRootNodes();
2911 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00002912 PatternsByOpcode[OpNodes[j]]
2913 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00002914 }
2915 } else {
2916 std::cerr << "Unrecognized opcode '";
2917 Node->dump();
2918 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00002919 std::cerr <<
2920 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00002921 std::cerr << "'!\n";
2922 exit(1);
2923 }
2924 }
2925 }
2926
2927 // Emit one Select_* method for each top-level opcode. We do this instead of
2928 // emitting one giant switch statement to support compilers where this will
2929 // result in the recursive functions taking less stack space.
2930 for (std::map<Record*, std::vector<PatternToMatch*>,
2931 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2932 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00002933 const std::string &OpName = PBOI->first->getName();
Evan Cheng34167212006-02-09 00:37:58 +00002934 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
Chris Lattner602f6922006-01-04 00:25:00 +00002935
2936 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Evan Chenge41bf822006-02-05 06:43:12 +00002937 bool OptSlctOrder =
2938 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
2939 OpcodeInfo.getNumResults() > 0);
2940
2941 if (OptSlctOrder) {
Evan Chenge41bf822006-02-05 06:43:12 +00002942 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
2943 << " && N.getValue(0).hasOneUse()) {\n"
2944 << " SDOperand Dummy = "
2945 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00002946 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2947 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
2948 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
2949 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00002950 << " Result = Dummy;\n"
2951 << " return;\n"
Evan Chenge41bf822006-02-05 06:43:12 +00002952 << " }\n";
2953 }
2954
Chris Lattner602f6922006-01-04 00:25:00 +00002955 std::vector<PatternToMatch*> &Patterns = PBOI->second;
Chris Lattner355408b2006-01-29 02:43:35 +00002956 assert(!Patterns.empty() && "No patterns but map has entry?");
Chris Lattner602f6922006-01-04 00:25:00 +00002957
2958 // We want to emit all of the matching code now. However, we want to emit
2959 // the matches in order of minimal cost. Sort the patterns so the least
2960 // cost one is at the start.
2961 std::stable_sort(Patterns.begin(), Patterns.end(),
2962 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00002963
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002964 typedef std::vector<std::pair<bool, std::string> > CodeList;
Evan Cheng21ad3922006-02-07 00:37:41 +00002965 typedef std::set<std::string> DeclSet;
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002966
2967 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
Evan Chengd7805a72006-02-09 07:16:09 +00002968 std::set<std::pair<bool, std::string> > GeneratedDecl;
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002969 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002970 CodeList GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002971 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
2972 OptSlctOrder);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002973 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
2974 }
2975
2976 // Scan the code to see if all of the patterns are reachable and if it is
2977 // possible that the last one might not match.
2978 bool mightNotMatch = true;
2979 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2980 CodeList &GeneratedCode = CodeForPatterns[i].second;
2981 mightNotMatch = false;
Chris Lattner355408b2006-01-29 02:43:35 +00002982
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002983 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
2984 if (GeneratedCode[j].first) { // predicate.
2985 mightNotMatch = true;
2986 break;
2987 }
2988 }
Chris Lattner355408b2006-01-29 02:43:35 +00002989
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002990 // If this pattern definitely matches, and if it isn't the last one, the
2991 // patterns after it CANNOT ever match. Error out.
2992 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
2993 std::cerr << "Pattern '";
2994 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
2995 std::cerr << "' is impossible to select!\n";
2996 exit(1);
2997 }
2998 }
Evan Cheng21ad3922006-02-07 00:37:41 +00002999
3000 // Print all declarations.
Evan Chengd7805a72006-02-09 07:16:09 +00003001 for (std::set<std::pair<bool, std::string> >::iterator I = GeneratedDecl.begin(),
Evan Cheng21ad3922006-02-07 00:37:41 +00003002 E = GeneratedDecl.end(); I != E; ++I)
Evan Chengd7805a72006-02-09 07:16:09 +00003003 if (I->first)
3004 OS << " SDNode *" << I->second << ";\n";
3005 else
3006 OS << " SDOperand " << I->second << "(0, 0);\n";
Evan Cheng21ad3922006-02-07 00:37:41 +00003007
Chris Lattner8bc74722006-01-29 04:25:26 +00003008 // Loop through and reverse all of the CodeList vectors, as we will be
3009 // accessing them from their logical front, but accessing the end of a
3010 // vector is more efficient.
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003011 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3012 CodeList &GeneratedCode = CodeForPatterns[i].second;
Chris Lattner8bc74722006-01-29 04:25:26 +00003013 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003014 }
Chris Lattner602f6922006-01-04 00:25:00 +00003015
Chris Lattner8bc74722006-01-29 04:25:26 +00003016 // Next, reverse the list of patterns itself for the same reason.
3017 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3018
3019 // Emit all of the patterns now, grouped together to share code.
3020 EmitPatterns(CodeForPatterns, 2, OS);
3021
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003022 // If the last pattern has predicates (which could fail) emit code to catch
3023 // the case where nothing handles a pattern.
Chris Lattner355408b2006-01-29 02:43:35 +00003024 if (mightNotMatch)
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003025 OS << " std::cerr << \"Cannot yet select: \";\n"
3026 << " N.Val->dump(CurDAG);\n"
3027 << " std::cerr << '\\n';\n"
3028 << " abort();\n";
3029
3030 OS << "}\n\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003031 }
3032
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003033 // Emit boilerplate.
Evan Cheng34167212006-02-09 00:37:58 +00003034 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003035 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng34167212006-02-09 00:37:58 +00003036 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003037 << " // Select the flag operand.\n"
3038 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng34167212006-02-09 00:37:58 +00003039 << " Select(Ops.back(), Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00003040 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003041 << " std::vector<MVT::ValueType> VTs;\n"
3042 << " VTs.push_back(MVT::Other);\n"
3043 << " VTs.push_back(MVT::Flag);\n"
3044 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003045 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3046 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003047 << " Result = New.getValue(N.ResNo);\n"
3048 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003049 << "}\n\n";
3050
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003051 OS << "// The main instruction selector code.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003052 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003053 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003054 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003055 << "INSTRUCTION_LIST_END)) {\n"
3056 << " Result = N;\n"
3057 << " return; // Already selected.\n"
3058 << " }\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003059 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003060 << " if (CGMI != CodeGenMap.end()) {\n"
3061 << " Result = CGMI->second;\n"
3062 << " return;\n"
3063 << " }\n\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003064 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003065 << " default: break;\n"
3066 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003067 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003068 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003069 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003070 << " case ISD::TargetConstant:\n"
3071 << " case ISD::TargetConstantPool:\n"
3072 << " case ISD::TargetFrameIndex:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003073 << " case ISD::TargetGlobalAddress: {\n"
3074 << " Result = N;\n"
3075 << " return;\n"
3076 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003077 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003078 << " case ISD::AssertZext: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003079 << " SDOperand Tmp0;\n"
3080 << " Select(Tmp0, N.getOperand(0));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003081 << " if (!N.Val->hasOneUse())\n"
3082 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3083 << "Tmp0.Val, Tmp0.ResNo);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003084 << " Result = Tmp0;\n"
3085 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003086 << " }\n"
3087 << " case ISD::TokenFactor:\n"
3088 << " if (N.getNumOperands() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003089 << " SDOperand Op0, Op1;\n"
3090 << " Select(Op0, N.getOperand(0));\n"
3091 << " Select(Op1, N.getOperand(1));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003092 << " Result = \n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003093 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003094 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3095 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003096 << " } else {\n"
3097 << " std::vector<SDOperand> Ops;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003098 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3099 << " SDOperand Val;\n"
3100 << " Select(Val, N.getOperand(i));\n"
3101 << " Ops.push_back(Val);\n"
3102 << " }\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003103 << " Result = \n"
3104 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3105 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3106 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003107 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003108 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003109 << " case ISD::CopyFromReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003110 << " SDOperand Chain;\n"
3111 << " Select(Chain, N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003112 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3113 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003114 << " if (N.Val->getNumValues() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003115 << " if (Chain == N.getOperand(0)) {\n"
3116 << " Result = N; // No change\n"
3117 << " return;\n"
3118 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003119 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003120 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3121 << "New.Val, 0);\n"
3122 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3123 << "New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003124 << " Result = New.getValue(N.ResNo);\n"
3125 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003126 << " } else {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003127 << " SDOperand Flag;\n"
3128 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003129 << " if (Chain == N.getOperand(0) &&\n"
Evan Cheng34167212006-02-09 00:37:58 +00003130 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3131 << " Result = N; // No change\n"
3132 << " return;\n"
3133 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003134 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003135 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3136 << "New.Val, 0);\n"
3137 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3138 << "New.Val, 1);\n"
3139 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3140 << "New.Val, 2);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003141 << " Result = New.getValue(N.ResNo);\n"
3142 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003143 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003144 << " }\n"
3145 << " case ISD::CopyToReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003146 << " SDOperand Chain;\n"
3147 << " Select(Chain, N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003148 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Evan Cheng34167212006-02-09 00:37:58 +00003149 << " SDOperand Val;\n"
3150 << " Select(Val, N.getOperand(2));\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003151 << " Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003152 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003153 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003154 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003155 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3156 << "Result.Val, 0);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003157 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003158 << " SDOperand Flag(0, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003159 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003160 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003161 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003162 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003163 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3164 << "Result.Val, 0);\n"
3165 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3166 << "Result.Val, 1);\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003167 << " Result = Result.getValue(N.ResNo);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003168 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003169 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003170 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003171 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003172
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003173
Chris Lattner602f6922006-01-04 00:25:00 +00003174 // Loop over all of the case statements, emiting a call to each method we
3175 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003176 for (std::map<Record*, std::vector<PatternToMatch*>,
3177 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3178 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003179 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00003180 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00003181 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Evan Cheng34167212006-02-09 00:37:58 +00003182 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
Chris Lattner81303322005-09-23 19:36:15 +00003183 }
Chris Lattner81303322005-09-23 19:36:15 +00003184
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003185 OS << " } // end of big switch.\n\n"
3186 << " std::cerr << \"Cannot yet select: \";\n"
Evan Cheng97938882005-12-22 02:24:50 +00003187 << " N.Val->dump(CurDAG);\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003188 << " std::cerr << '\\n';\n"
3189 << " abort();\n"
3190 << "}\n";
3191}
3192
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003193void DAGISelEmitter::run(std::ostream &OS) {
3194 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3195 " target", OS);
3196
Chris Lattner1f39e292005-09-14 00:09:24 +00003197 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3198 << "// *** instruction selector class. These functions are really "
3199 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003200
Chris Lattner296dfe32005-09-24 00:50:51 +00003201 OS << "// Instance var to keep track of multiply used nodes that have \n"
3202 << "// already been selected.\n"
3203 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003204
3205 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003206 << "// and their place handle nodes.\n";
3207 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3208 OS << "// Instance var to keep track of mapping of place handle nodes\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003209 << "// and their replacement nodes.\n";
3210 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3211
3212 OS << "\n";
3213 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3214 << "std::set<SDNode *> &Visited) {\n";
3215 OS << " if (found || !Visited.insert(Use).second) return;\n";
3216 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3217 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3218 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3219 OS << " if (N != Def) {\n";
3220 OS << " findNonImmUse(N, Def, found, Visited);\n";
3221 OS << " } else {\n";
3222 OS << " found = true;\n";
3223 OS << " break;\n";
3224 OS << " }\n";
3225 OS << " }\n";
3226 OS << " }\n";
3227 OS << "}\n";
3228
3229 OS << "\n";
3230 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3231 OS << " std::set<SDNode *> Visited;\n";
3232 OS << " bool found = false;\n";
3233 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3234 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3235 OS << " if (N != Def) {\n";
3236 OS << " findNonImmUse(N, Def, found, Visited);\n";
3237 OS << " if (found) break;\n";
3238 OS << " }\n";
3239 OS << " }\n";
3240 OS << " return found;\n";
3241 OS << "}\n";
3242
3243 OS << "\n";
Evan Cheng024524f2006-02-06 06:03:35 +00003244 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003245 << "// handle node in ReplaceMap.\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003246 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3247 << "unsigned RNum) {\n";
3248 OS << " SDOperand N(H, HNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003249 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3250 OS << " if (HMI != HandleMap.end()) {\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003251 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003252 OS << " HandleMap.erase(N);\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003253 OS << " }\n";
3254 OS << "}\n";
3255
3256 OS << "\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003257 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3258 OS << "// handles.Some handles do not yet have replacements because the\n";
3259 OS << "// nodes they replacements have only dead readers.\n";
3260 OS << "void SelectDanglingHandles() {\n";
3261 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3262 << "HandleMap.begin(),\n"
3263 << " E = HandleMap.end(); I != E; ++I) {\n";
3264 OS << " SDOperand N = I->first;\n";
Evan Cheng34167212006-02-09 00:37:58 +00003265 OS << " SDOperand R;\n";
3266 OS << " Select(R, N.getValue(0));\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003267 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003268 OS << " }\n";
3269 OS << "}\n";
3270 OS << "\n";
3271 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003272 OS << "// specific nodes.\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003273 OS << "void ReplaceHandles() {\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003274 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3275 << "ReplaceMap.begin(),\n"
3276 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3277 OS << " SDOperand From = I->first;\n";
3278 OS << " SDOperand To = I->second;\n";
3279 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3280 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3281 OS << " SDNode *Use = *UI;\n";
3282 OS << " std::vector<SDOperand> Ops;\n";
3283 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3284 OS << " SDOperand O = Use->getOperand(i);\n";
3285 OS << " if (O.Val == From.Val)\n";
3286 OS << " Ops.push_back(To);\n";
3287 OS << " else\n";
3288 OS << " Ops.push_back(O);\n";
3289 OS << " }\n";
3290 OS << " SDOperand U = SDOperand(Use, 0);\n";
3291 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3292 OS << " }\n";
3293 OS << " }\n";
3294 OS << "}\n";
3295
3296 OS << "\n";
Evan Chenged66e852006-03-09 08:19:11 +00003297 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3298 OS << "// if the folding were to happen. This is called when, for example,\n";
3299 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3300 OS << "// then the resulting node's input chain would be the load's input\n";
3301 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3302 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3303 OS << "// with the other operands along with the input chain of the load.\n";
3304 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3305 << "SDNode *Chain, SDNode* &OldTF) {\n";
3306 OS << " OldTF = NULL;\n";
3307 OS << " if (N == Chain) {\n";
3308 OS << " return N->getOperand(0);\n";
3309 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3310 OS << " N->isOperand(Chain)) {\n";
3311 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3312 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3313 << "CodeGenMap.find(Ch);\n";
3314 OS << " if (CGMI != CodeGenMap.end())\n";
3315 OS << " return SDOperand(0, 0);\n";
3316 OS << " OldTF = Chain;\n";
3317 OS << " std::vector<SDOperand> Ops;\n";
3318 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3319 OS << " SDOperand Op = Chain->getOperand(i);\n";
3320 OS << " if (Op.Val == N)\n";
3321 OS << " Ops.push_back(N->getOperand(0));\n";
3322 OS << " else\n";
3323 OS << " Ops.push_back(Op);\n";
3324 OS << " }\n";
3325 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3326 OS << " }\n";
3327 OS << " return SDOperand(0, 0);\n";
3328 OS << "}\n";
3329
3330 OS << "\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003331 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3332 OS << "SDOperand SelectRoot(SDOperand N) {\n";
Evan Cheng34167212006-02-09 00:37:58 +00003333 OS << " SDOperand ResNode;\n";
3334 OS << " Select(ResNode, N);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003335 OS << " SelectDanglingHandles();\n";
3336 OS << " ReplaceHandles();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003337 OS << " ReplaceMap.clear();\n";
Evan Cheng34167212006-02-09 00:37:58 +00003338 OS << " return ResNode;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003339 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003340
Chris Lattnerca559d02005-09-08 21:03:01 +00003341 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003342 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003343 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003344 ParsePatternFragments(OS);
3345 ParseInstructions();
3346 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003347
Chris Lattnere97603f2005-09-28 19:27:25 +00003348 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003349 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003350 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003351
Chris Lattnere46e17b2005-09-29 19:28:10 +00003352
3353 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3354 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003355 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3356 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003357 std::cerr << "\n";
3358 });
3359
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003360 // At this point, we have full information about the 'Patterns' we need to
3361 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003362 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003363 EmitInstructionSelector(OS);
3364
3365 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3366 E = PatternFragments.end(); I != E; ++I)
3367 delete I->second;
3368 PatternFragments.clear();
3369
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003370 Instructions.clear();
3371}