blob: a50827e73553f8d4f1af90e76ea107a7d130b16d [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.
66static bool isExtIntegerInVTs(std::vector<unsigned char> EVTs) {
67 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.
73static bool isExtFloatingPointInVTs(std::vector<unsigned char> EVTs) {
74 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 Lattner33c92e92005-09-08 21:27:15 +0000106 } else {
107 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
108 exit(1);
109 }
110}
111
Chris Lattner32707602005-09-08 23:22:48 +0000112/// getOperandNum - Return the node corresponding to operand #OpNo in tree
113/// N, which has NumResults results.
114TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
115 TreePatternNode *N,
116 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000117 assert(NumResults <= 1 &&
118 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000119
120 if (OpNo < NumResults)
121 return N; // FIXME: need value #
122 else
123 return N->getChild(OpNo-NumResults);
124}
125
126/// ApplyTypeConstraint - Given a node in a pattern, apply this type
127/// constraint to the nodes operands. This returns true if it makes a
128/// change, false otherwise. If a type contradiction is found, throw an
129/// exception.
130bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
131 const SDNodeInfo &NodeInfo,
132 TreePattern &TP) const {
133 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000134 assert(NumResults <= 1 &&
135 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000136
137 // Check that the number of operands is sane.
138 if (NodeInfo.getNumOperands() >= 0) {
139 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
140 TP.error(N->getOperator()->getName() + " node requires exactly " +
141 itostr(NodeInfo.getNumOperands()) + " operands!");
142 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000143
144 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000145
146 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
147
148 switch (ConstraintType) {
149 default: assert(0 && "Unknown constraint type!");
150 case SDTCisVT:
151 // Operand must be a particular type.
152 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000153 case SDTCisPtrTy: {
154 // Operand must be same as target pointer type.
155 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
156 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000157 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000158 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000159 std::vector<MVT::ValueType> IntVTs =
160 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000161
162 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000163 if (IntVTs.size() == 1)
164 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000165 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000166 }
167 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000168 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000169 std::vector<MVT::ValueType> FPVTs =
170 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000171
172 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000173 if (FPVTs.size() == 1)
174 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000175 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000176 }
Chris Lattner32707602005-09-08 23:22:48 +0000177 case SDTCisSameAs: {
178 TreePatternNode *OtherNode =
179 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000180 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
181 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000182 }
183 case SDTCisVTSmallerThanOp: {
184 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
185 // have an integer type that is smaller than the VT.
186 if (!NodeToApply->isLeaf() ||
187 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
188 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
189 ->isSubClassOf("ValueType"))
190 TP.error(N->getOperator()->getName() + " expects a VT operand!");
191 MVT::ValueType VT =
192 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
193 if (!MVT::isInteger(VT))
194 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
195
196 TreePatternNode *OtherNode =
197 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000198
199 // It must be integer.
200 bool MadeChange = false;
201 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
202
Nate Begemanb73628b2005-12-30 00:12:56 +0000203 // This code only handles nodes that have one type set. Assert here so
204 // that we can change this if we ever need to deal with multiple value
205 // types at this point.
206 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
207 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000208 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
209 return false;
210 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000211 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000212 TreePatternNode *BigOperand =
213 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
214
215 // Both operands must be integer or FP, but we don't care which.
216 bool MadeChange = false;
217
Nate Begemanb73628b2005-12-30 00:12:56 +0000218 // This code does not currently handle nodes which have multiple types,
219 // where some types are integer, and some are fp. Assert that this is not
220 // the case.
221 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
222 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
223 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
224 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
225 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
226 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000227 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000228 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000229 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000230 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000231 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000232 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000233 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
234
235 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
236
Nate Begemanb73628b2005-12-30 00:12:56 +0000237 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000238 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000239 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000240 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
241 } else {
242 VTs.clear();
243 }
244
245 switch (VTs.size()) {
246 default: // Too many VT's to pick from.
247 case 0: break; // No info yet.
248 case 1:
249 // Only one VT of this flavor. Cannot ever satisify the constraints.
250 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
251 case 2:
252 // If we have exactly two possible types, the little operand must be the
253 // small one, the big operand should be the big one. Common with
254 // float/double for example.
255 assert(VTs[0] < VTs[1] && "Should be sorted!");
256 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
257 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
258 break;
259 }
260 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000261 }
Chris Lattner32707602005-09-08 23:22:48 +0000262 }
263 return false;
264}
265
266
Chris Lattner33c92e92005-09-08 21:27:15 +0000267//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000268// SDNodeInfo implementation
269//
270SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
271 EnumName = R->getValueAsString("Opcode");
272 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000273 Record *TypeProfile = R->getValueAsDef("TypeProfile");
274 NumResults = TypeProfile->getValueAsInt("NumResults");
275 NumOperands = TypeProfile->getValueAsInt("NumOperands");
276
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000277 // Parse the properties.
278 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000279 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000280 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
281 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000282 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000283 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000284 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000285 } else if (PropList[i]->getName() == "SDNPHasChain") {
286 Properties |= 1 << SDNPHasChain;
Evan Cheng51fecc82006-01-09 18:27:06 +0000287 } else if (PropList[i]->getName() == "SDNPOutFlag") {
288 Properties |= 1 << SDNPOutFlag;
289 } else if (PropList[i]->getName() == "SDNPInFlag") {
290 Properties |= 1 << SDNPInFlag;
291 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
292 Properties |= 1 << SDNPOptInFlag;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000293 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000294 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000295 << "' on node '" << R->getName() << "'!\n";
296 exit(1);
297 }
298 }
299
300
Chris Lattner33c92e92005-09-08 21:27:15 +0000301 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000302 std::vector<Record*> ConstraintList =
303 TypeProfile->getValueAsListOfDefs("Constraints");
304 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000305}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000306
307//===----------------------------------------------------------------------===//
308// TreePatternNode implementation
309//
310
311TreePatternNode::~TreePatternNode() {
312#if 0 // FIXME: implement refcounted tree nodes!
313 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
314 delete getChild(i);
315#endif
316}
317
Chris Lattner32707602005-09-08 23:22:48 +0000318/// UpdateNodeType - Set the node type of N to VT if VT contains
319/// information. If N already contains a conflicting type, then throw an
320/// exception. This returns true if any information was updated.
321///
Nate Begemanb73628b2005-12-30 00:12:56 +0000322bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
323 TreePattern &TP) {
324 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
325
326 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
327 return false;
328 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
329 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000330 return true;
331 }
332
Nate Begemanb73628b2005-12-30 00:12:56 +0000333 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
334 assert(hasTypeSet() && "should be handled above!");
335 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
336 if (getExtTypes() == FVTs)
337 return false;
338 setTypes(FVTs);
339 return true;
340 }
341 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
342 assert(hasTypeSet() && "should be handled above!");
Chris Lattner488580c2006-01-28 19:06:51 +0000343 std::vector<unsigned char> FVTs =
344 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
Nate Begemanb73628b2005-12-30 00:12:56 +0000345 if (getExtTypes() == FVTs)
346 return false;
347 setTypes(FVTs);
348 return true;
349 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000350
351 // If we know this is an int or fp type, and we are told it is a specific one,
352 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000353 //
354 // Similarly, we should probably set the type here to the intersection of
355 // {isInt|isFP} and ExtVTs
356 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
357 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
358 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000359 return true;
360 }
361
Chris Lattner1531f202005-10-26 16:59:37 +0000362 if (isLeaf()) {
363 dump();
Evan Chengbcecf332005-12-17 01:19:28 +0000364 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000365 TP.error("Type inference contradiction found in node!");
366 } else {
367 TP.error("Type inference contradiction found in node " +
368 getOperator()->getName() + "!");
369 }
Chris Lattner32707602005-09-08 23:22:48 +0000370 return true; // unreachable
371}
372
373
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000374void TreePatternNode::print(std::ostream &OS) const {
375 if (isLeaf()) {
376 OS << *getLeafValue();
377 } else {
378 OS << "(" << getOperator()->getName();
379 }
380
Nate Begemanb73628b2005-12-30 00:12:56 +0000381 // FIXME: At some point we should handle printing all the value types for
382 // nodes that are multiply typed.
383 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000384 case MVT::Other: OS << ":Other"; break;
385 case MVT::isInt: OS << ":isInt"; break;
386 case MVT::isFP : OS << ":isFP"; break;
387 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Nate Begemanb73628b2005-12-30 00:12:56 +0000388 default: OS << ":" << getTypeNum(0); break;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000389 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000390
391 if (!isLeaf()) {
392 if (getNumChildren() != 0) {
393 OS << " ";
394 getChild(0)->print(OS);
395 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
396 OS << ", ";
397 getChild(i)->print(OS);
398 }
399 }
400 OS << ")";
401 }
402
403 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000404 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000405 if (TransformFn)
406 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000407 if (!getName().empty())
408 OS << ":$" << getName();
409
410}
411void TreePatternNode::dump() const {
412 print(std::cerr);
413}
414
Chris Lattnere46e17b2005-09-29 19:28:10 +0000415/// isIsomorphicTo - Return true if this node is recursively isomorphic to
416/// the specified node. For this comparison, all of the state of the node
417/// is considered, except for the assigned name. Nodes with differing names
418/// that are otherwise identical are considered isomorphic.
419bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
420 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000421 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000422 getPredicateFn() != N->getPredicateFn() ||
423 getTransformFn() != N->getTransformFn())
424 return false;
425
426 if (isLeaf()) {
427 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
428 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
429 return DI->getDef() == NDI->getDef();
430 return getLeafValue() == N->getLeafValue();
431 }
432
433 if (N->getOperator() != getOperator() ||
434 N->getNumChildren() != getNumChildren()) return false;
435 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
436 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
437 return false;
438 return true;
439}
440
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000441/// clone - Make a copy of this tree and all of its children.
442///
443TreePatternNode *TreePatternNode::clone() const {
444 TreePatternNode *New;
445 if (isLeaf()) {
446 New = new TreePatternNode(getLeafValue());
447 } else {
448 std::vector<TreePatternNode*> CChildren;
449 CChildren.reserve(Children.size());
450 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
451 CChildren.push_back(getChild(i)->clone());
452 New = new TreePatternNode(getOperator(), CChildren);
453 }
454 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000455 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000456 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000457 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000458 return New;
459}
460
Chris Lattner32707602005-09-08 23:22:48 +0000461/// SubstituteFormalArguments - Replace the formal arguments in this tree
462/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000463void TreePatternNode::
464SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
465 if (isLeaf()) return;
466
467 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
468 TreePatternNode *Child = getChild(i);
469 if (Child->isLeaf()) {
470 Init *Val = Child->getLeafValue();
471 if (dynamic_cast<DefInit*>(Val) &&
472 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
473 // We found a use of a formal argument, replace it with its value.
474 Child = ArgMap[Child->getName()];
475 assert(Child && "Couldn't find formal argument!");
476 setChild(i, Child);
477 }
478 } else {
479 getChild(i)->SubstituteFormalArguments(ArgMap);
480 }
481 }
482}
483
484
485/// InlinePatternFragments - If this pattern refers to any pattern
486/// fragments, inline them into place, giving us a pattern without any
487/// PatFrag references.
488TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
489 if (isLeaf()) return this; // nothing to do.
490 Record *Op = getOperator();
491
492 if (!Op->isSubClassOf("PatFrag")) {
493 // Just recursively inline children nodes.
494 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
495 setChild(i, getChild(i)->InlinePatternFragments(TP));
496 return this;
497 }
498
499 // Otherwise, we found a reference to a fragment. First, look up its
500 // TreePattern record.
501 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
502
503 // Verify that we are passing the right number of operands.
504 if (Frag->getNumArgs() != Children.size())
505 TP.error("'" + Op->getName() + "' fragment requires " +
506 utostr(Frag->getNumArgs()) + " operands!");
507
Chris Lattner37937092005-09-09 01:15:01 +0000508 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000509
510 // Resolve formal arguments to their actual value.
511 if (Frag->getNumArgs()) {
512 // Compute the map of formal to actual arguments.
513 std::map<std::string, TreePatternNode*> ArgMap;
514 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
515 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
516
517 FragTree->SubstituteFormalArguments(ArgMap);
518 }
519
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000520 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000521 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000522
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000523 // Get a new copy of this fragment to stitch into here.
524 //delete this; // FIXME: implement refcounting!
525 return FragTree;
526}
527
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000528/// getIntrinsicType - Check to see if the specified record has an intrinsic
529/// type which should be applied to it. This infer the type of register
530/// references from the register file information, for example.
531///
Nate Begemanb73628b2005-12-30 00:12:56 +0000532static std::vector<unsigned char> getIntrinsicType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000533 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000534 // Some common return values
535 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
536 std::vector<unsigned char> Other(1, MVT::Other);
537
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000538 // Check to see if this is a register or a register class...
539 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000540 if (NotRegisters)
541 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000542 const CodeGenRegisterClass &RC =
543 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000544 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000545 } else if (R->isSubClassOf("PatFrag")) {
546 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000547 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000548 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000549 if (NotRegisters)
550 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000551 // If the register appears in exactly one regclass, and the regclass has one
552 // value type, use it as the known type.
553 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
554 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
Nate Begemanb73628b2005-12-30 00:12:56 +0000555 return ConvertVTs(RC->getValueTypes());
556 return Unknown;
Chris Lattner1531f202005-10-26 16:59:37 +0000557 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
558 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000559 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000560 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000561 if (NotRegisters)
562 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000563 std::vector<unsigned char>
564 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
565 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000566 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000567 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000568 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000569 }
570
571 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000572 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000573}
574
Chris Lattner32707602005-09-08 23:22:48 +0000575/// ApplyTypeConstraints - Apply all of the type constraints relevent to
576/// this node and its children in the tree. This returns true if it makes a
577/// change, false otherwise. If a type contradiction is found, throw an
578/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000579bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
580 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000581 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000582 // If it's a regclass or something else known, include the type.
583 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
584 TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000585 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
586 // Int inits are always integers. :)
587 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
588
589 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000590 // At some point, it may make sense for this tree pattern to have
591 // multiple types. Assert here that it does not, so we revisit this
592 // code when appropriate.
593 assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
594
595 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
Chris Lattner465c7372005-11-03 05:46:11 +0000596 // Make sure that the value is representable for this type.
597 if (Size < 32) {
598 int Val = (II->getValue() << (32-Size)) >> (32-Size);
599 if (Val != II->getValue())
600 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
601 "' is out of range for type 'MVT::" +
Nate Begemanb73628b2005-12-30 00:12:56 +0000602 getEnumName(getTypeNum(0)) + "'!");
Chris Lattner465c7372005-11-03 05:46:11 +0000603 }
604 }
605
606 return MadeChange;
607 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000608 return false;
609 }
Chris Lattner32707602005-09-08 23:22:48 +0000610
611 // special handling for set, which isn't really an SDNode.
612 if (getOperator()->getName() == "set") {
613 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000614 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
615 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000616
617 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000618 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
619 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000620 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
621 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000622 } else if (getOperator()->isSubClassOf("SDNode")) {
623 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
624
625 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
626 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000627 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000628 // Branch, etc. do not produce results and top-level forms in instr pattern
629 // must have void types.
630 if (NI.getNumResults() == 0)
631 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000632 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000633 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000634 const DAGInstruction &Inst =
635 TP.getDAGISelEmitter().getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000636 bool MadeChange = false;
637 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000638
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000639 assert(NumResults <= 1 &&
640 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000641 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000642 if (NumResults == 0) {
643 MadeChange = UpdateNodeType(MVT::isVoid, TP);
644 } else {
645 Record *ResultNode = Inst.getResult(0);
646 assert(ResultNode->isSubClassOf("RegisterClass") &&
647 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000648
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000649 const CodeGenRegisterClass &RC =
650 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000651 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000652 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000653
654 if (getNumChildren() != Inst.getNumOperands())
655 TP.error("Instruction '" + getOperator()->getName() + " expects " +
656 utostr(Inst.getNumOperands()) + " operands, not " +
657 utostr(getNumChildren()) + " operands!");
658 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000659 Record *OperandNode = Inst.getOperand(i);
660 MVT::ValueType VT;
661 if (OperandNode->isSubClassOf("RegisterClass")) {
662 const CodeGenRegisterClass &RC =
663 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000664 //VT = RC.getValueTypeNum(0);
665 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
666 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000667 } else if (OperandNode->isSubClassOf("Operand")) {
668 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000669 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000670 } else {
671 assert(0 && "Unknown operand type!");
672 abort();
673 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000674 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000675 }
676 return MadeChange;
677 } else {
678 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
679
680 // Node transforms always take one operand, and take and return the same
681 // type.
682 if (getNumChildren() != 1)
683 TP.error("Node transform '" + getOperator()->getName() +
684 "' requires one operand!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000685 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
686 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
Chris Lattnera28aec12005-09-15 22:23:50 +0000687 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000688 }
Chris Lattner32707602005-09-08 23:22:48 +0000689}
690
Chris Lattnere97603f2005-09-28 19:27:25 +0000691/// canPatternMatch - If it is impossible for this pattern to match on this
692/// target, fill in Reason and return false. Otherwise, return true. This is
693/// used as a santity check for .td files (to prevent people from writing stuff
694/// that can never possibly work), and to prevent the pattern permuter from
695/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000696bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000697 if (isLeaf()) return true;
698
699 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
700 if (!getChild(i)->canPatternMatch(Reason, ISE))
701 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000702
Chris Lattnere97603f2005-09-28 19:27:25 +0000703 // If this node is a commutative operator, check that the LHS isn't an
704 // immediate.
705 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
706 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
707 // Scan all of the operands of the node and make sure that only the last one
708 // is a constant node.
709 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
710 if (!getChild(i)->isLeaf() &&
711 getChild(i)->getOperator()->getName() == "imm") {
712 Reason = "Immediate value must be on the RHS of commutative operators!";
713 return false;
714 }
715 }
716
717 return true;
718}
Chris Lattner32707602005-09-08 23:22:48 +0000719
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000720//===----------------------------------------------------------------------===//
721// TreePattern implementation
722//
723
Chris Lattneredbd8712005-10-21 01:19:59 +0000724TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000725 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000726 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000727 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
728 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000729}
730
Chris Lattneredbd8712005-10-21 01:19:59 +0000731TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000732 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000733 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000734 Trees.push_back(ParseTreePattern(Pat));
735}
736
Chris Lattneredbd8712005-10-21 01:19:59 +0000737TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000738 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000739 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000740 Trees.push_back(Pat);
741}
742
743
744
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000745void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000746 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000747 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000748}
749
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000750TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
751 Record *Operator = Dag->getNodeType();
752
753 if (Operator->isSubClassOf("ValueType")) {
754 // If the operator is a ValueType, then this must be "type cast" of a leaf
755 // node.
756 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000757 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000758
759 Init *Arg = Dag->getArg(0);
760 TreePatternNode *New;
761 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000762 Record *R = DI->getDef();
763 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
764 Dag->setArg(0, new DagInit(R,
765 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000766 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000767 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000768 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000769 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
770 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000771 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
772 New = new TreePatternNode(II);
773 if (!Dag->getArgName(0).empty())
774 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000775 } else {
776 Arg->dump();
777 error("Unknown leaf value for tree pattern!");
778 return 0;
779 }
780
Chris Lattner32707602005-09-08 23:22:48 +0000781 // Apply the type cast.
782 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000783 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000784 return New;
785 }
786
787 // Verify that this is something that makes sense for an operator.
788 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000789 !Operator->isSubClassOf("Instruction") &&
790 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000791 Operator->getName() != "set")
792 error("Unrecognized node '" + Operator->getName() + "'!");
793
Chris Lattneredbd8712005-10-21 01:19:59 +0000794 // Check to see if this is something that is illegal in an input pattern.
795 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
796 Operator->isSubClassOf("SDNodeXForm")))
797 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
798
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000799 std::vector<TreePatternNode*> Children;
800
801 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
802 Init *Arg = Dag->getArg(i);
803 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
804 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000805 if (Children.back()->getName().empty())
806 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000807 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
808 Record *R = DefI->getDef();
809 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
810 // TreePatternNode if its own.
811 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
812 Dag->setArg(i, new DagInit(R,
813 std::vector<std::pair<Init*, std::string> >()));
814 --i; // Revisit this node...
815 } else {
816 TreePatternNode *Node = new TreePatternNode(DefI);
817 Node->setName(Dag->getArgName(i));
818 Children.push_back(Node);
819
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000820 // Input argument?
821 if (R->getName() == "node") {
822 if (Dag->getArgName(i).empty())
823 error("'node' argument requires a name to match with operand list");
824 Args.push_back(Dag->getArgName(i));
825 }
826 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000827 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
828 TreePatternNode *Node = new TreePatternNode(II);
829 if (!Dag->getArgName(i).empty())
830 error("Constant int argument should not have a name!");
831 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000832 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000833 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000834 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000835 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000836 error("Unknown leaf value for tree pattern!");
837 }
838 }
839
840 return new TreePatternNode(Operator, Children);
841}
842
Chris Lattner32707602005-09-08 23:22:48 +0000843/// InferAllTypes - Infer/propagate as many types throughout the expression
844/// patterns as possible. Return true if all types are infered, false
845/// otherwise. Throw an exception if a type contradiction is found.
846bool TreePattern::InferAllTypes() {
847 bool MadeChange = true;
848 while (MadeChange) {
849 MadeChange = false;
850 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000851 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000852 }
853
854 bool HasUnresolvedTypes = false;
855 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
856 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
857 return !HasUnresolvedTypes;
858}
859
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000860void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000861 OS << getRecord()->getName();
862 if (!Args.empty()) {
863 OS << "(" << Args[0];
864 for (unsigned i = 1, e = Args.size(); i != e; ++i)
865 OS << ", " << Args[i];
866 OS << ")";
867 }
868 OS << ": ";
869
870 if (Trees.size() > 1)
871 OS << "[\n";
872 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
873 OS << "\t";
874 Trees[i]->print(OS);
875 OS << "\n";
876 }
877
878 if (Trees.size() > 1)
879 OS << "]\n";
880}
881
882void TreePattern::dump() const { print(std::cerr); }
883
884
885
886//===----------------------------------------------------------------------===//
887// DAGISelEmitter implementation
888//
889
Chris Lattnerca559d02005-09-08 21:03:01 +0000890// Parse all of the SDNode definitions for the target, populating SDNodes.
891void DAGISelEmitter::ParseNodeInfo() {
892 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
893 while (!Nodes.empty()) {
894 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
895 Nodes.pop_back();
896 }
897}
898
Chris Lattner24eeeb82005-09-13 21:51:00 +0000899/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
900/// map, and emit them to the file as functions.
901void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
902 OS << "\n// Node transformations.\n";
903 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
904 while (!Xforms.empty()) {
905 Record *XFormNode = Xforms.back();
906 Record *SDNode = XFormNode->getValueAsDef("Opcode");
907 std::string Code = XFormNode->getValueAsCode("XFormFunction");
908 SDNodeXForms.insert(std::make_pair(XFormNode,
909 std::make_pair(SDNode, Code)));
910
Chris Lattner1048b7a2005-09-13 22:03:37 +0000911 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000912 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
913 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
914
Chris Lattner1048b7a2005-09-13 22:03:37 +0000915 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000916 << "(SDNode *" << C2 << ") {\n";
917 if (ClassName != "SDNode")
918 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
919 OS << Code << "\n}\n";
920 }
921
922 Xforms.pop_back();
923 }
924}
925
Evan Cheng0fc71982005-12-08 02:00:36 +0000926void DAGISelEmitter::ParseComplexPatterns() {
927 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
928 while (!AMs.empty()) {
929 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
930 AMs.pop_back();
931 }
932}
Chris Lattner24eeeb82005-09-13 21:51:00 +0000933
934
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000935/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
936/// file, building up the PatternFragments map. After we've collected them all,
937/// inline fragments together as necessary, so that there are no references left
938/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000939///
940/// This also emits all of the predicate functions to the output file.
941///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000942void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000943 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
944
945 // First step, parse all of the fragments and emit predicate functions.
946 OS << "\n// Predicate functions.\n";
947 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000948 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +0000949 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000950 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000951
952 // Validate the argument list, converting it to map, to discard duplicates.
953 std::vector<std::string> &Args = P->getArgList();
954 std::set<std::string> OperandsMap(Args.begin(), Args.end());
955
956 if (OperandsMap.count(""))
957 P->error("Cannot have unnamed 'node' values in pattern fragment!");
958
959 // Parse the operands list.
960 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
961 if (OpsList->getNodeType()->getName() != "ops")
962 P->error("Operands list should start with '(ops ... '!");
963
964 // Copy over the arguments.
965 Args.clear();
966 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
967 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
968 static_cast<DefInit*>(OpsList->getArg(j))->
969 getDef()->getName() != "node")
970 P->error("Operands list should all be 'node' values.");
971 if (OpsList->getArgName(j).empty())
972 P->error("Operands list should have names for each operand!");
973 if (!OperandsMap.count(OpsList->getArgName(j)))
974 P->error("'" + OpsList->getArgName(j) +
975 "' does not occur in pattern or was multiply specified!");
976 OperandsMap.erase(OpsList->getArgName(j));
977 Args.push_back(OpsList->getArgName(j));
978 }
979
980 if (!OperandsMap.empty())
981 P->error("Operands list does not contain an entry for operand '" +
982 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000983
984 // If there is a code init for this fragment, emit the predicate code and
985 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000986 std::string Code = Fragments[i]->getValueAsCode("Predicate");
987 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000988 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000989 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000990 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000991 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
992
Chris Lattner1048b7a2005-09-13 22:03:37 +0000993 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000994 << "(SDNode *" << C2 << ") {\n";
995 if (ClassName != "SDNode")
996 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000997 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000998 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000999 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001000
1001 // If there is a node transformation corresponding to this, keep track of
1002 // it.
1003 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1004 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001005 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001006 }
1007
1008 OS << "\n\n";
1009
1010 // Now that we've parsed all of the tree fragments, do a closure on them so
1011 // that there are not references to PatFrags left inside of them.
1012 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1013 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001014 TreePattern *ThePat = I->second;
1015 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001016
Chris Lattner32707602005-09-08 23:22:48 +00001017 // Infer as many types as possible. Don't worry about it if we don't infer
1018 // all of them, some may depend on the inputs of the pattern.
1019 try {
1020 ThePat->InferAllTypes();
1021 } catch (...) {
1022 // If this pattern fragment is not supported by this target (no types can
1023 // satisfy its constraints), just ignore it. If the bogus pattern is
1024 // actually used by instructions, the type consistency error will be
1025 // reported there.
1026 }
1027
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001028 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001029 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001030 }
1031}
1032
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001033/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001034/// instruction input. Return true if this is a real use.
1035static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001036 std::map<std::string, TreePatternNode*> &InstInputs,
1037 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001038 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001039 if (Pat->getName().empty()) {
1040 if (Pat->isLeaf()) {
1041 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1042 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1043 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001044 else if (DI && DI->getDef()->isSubClassOf("Register"))
1045 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001046 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001047 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001048 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001049
1050 Record *Rec;
1051 if (Pat->isLeaf()) {
1052 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1053 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1054 Rec = DI->getDef();
1055 } else {
1056 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1057 Rec = Pat->getOperator();
1058 }
1059
Evan Cheng01f318b2005-12-14 02:21:57 +00001060 // SRCVALUE nodes are ignored.
1061 if (Rec->getName() == "srcvalue")
1062 return false;
1063
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001064 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1065 if (!Slot) {
1066 Slot = Pat;
1067 } else {
1068 Record *SlotRec;
1069 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001070 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001071 } else {
1072 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1073 SlotRec = Slot->getOperator();
1074 }
1075
1076 // Ensure that the inputs agree if we've already seen this input.
1077 if (Rec != SlotRec)
1078 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001079 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001080 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1081 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001082 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001083}
1084
1085/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1086/// part of "I", the instruction), computing the set of inputs and outputs of
1087/// the pattern. Report errors if we see anything naughty.
1088void DAGISelEmitter::
1089FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1090 std::map<std::string, TreePatternNode*> &InstInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001091 std::map<std::string, Record*> &InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001092 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001093 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001094 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001095 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001096 if (!isUse && Pat->getTransformFn())
1097 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001098 return;
1099 } else if (Pat->getOperator()->getName() != "set") {
1100 // If this is not a set, verify that the children nodes are not void typed,
1101 // and recurse.
1102 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001103 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001104 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001105 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001106 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001107 }
1108
1109 // If this is a non-leaf node with no children, treat it basically as if
1110 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001111 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001112 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001113 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001114
Chris Lattnerf1311842005-09-14 23:05:13 +00001115 if (!isUse && Pat->getTransformFn())
1116 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001117 return;
1118 }
1119
1120 // Otherwise, this is a set, validate and collect instruction results.
1121 if (Pat->getNumChildren() == 0)
1122 I->error("set requires operands!");
1123 else if (Pat->getNumChildren() & 1)
1124 I->error("set requires an even number of operands");
1125
Chris Lattnerf1311842005-09-14 23:05:13 +00001126 if (Pat->getTransformFn())
1127 I->error("Cannot specify a transform function on a set node!");
1128
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001129 // Check the set destinations.
1130 unsigned NumValues = Pat->getNumChildren()/2;
1131 for (unsigned i = 0; i != NumValues; ++i) {
1132 TreePatternNode *Dest = Pat->getChild(i);
1133 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001134 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001135
1136 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1137 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001138 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001139
Evan Chengbcecf332005-12-17 01:19:28 +00001140 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1141 if (Dest->getName().empty())
1142 I->error("set destination must have a name!");
1143 if (InstResults.count(Dest->getName()))
1144 I->error("cannot set '" + Dest->getName() +"' multiple times");
1145 InstResults[Dest->getName()] = Val->getDef();
Evan Cheng7b05bd52005-12-23 22:11:47 +00001146 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001147 InstImpResults.push_back(Val->getDef());
1148 } else {
1149 I->error("set destination should be a register!");
1150 }
1151
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001152 // Verify and collect info from the computation.
1153 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001154 InstInputs, InstResults,
1155 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001156 }
1157}
1158
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001159/// ParseInstructions - Parse all of the instructions, inlining and resolving
1160/// any fragments involved. This populates the Instructions list with fully
1161/// resolved instructions.
1162void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001163 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1164
1165 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001166 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001167
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001168 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1169 LI = Instrs[i]->getValueAsListInit("Pattern");
1170
1171 // If there is no pattern, only collect minimal information about the
1172 // instruction for its operand list. We have to assume that there is one
1173 // result, as we have no detailed info.
1174 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001175 std::vector<Record*> Results;
1176 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001177
1178 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001179
Evan Cheng3a217f32005-12-22 02:35:21 +00001180 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001181 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001182 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001183 // These produce no results
1184 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1185 Operands.push_back(InstInfo.OperandList[j].Rec);
1186 } else {
1187 // Assume the first operand is the result.
1188 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001189
Evan Cheng3a217f32005-12-22 02:35:21 +00001190 // The rest are inputs.
1191 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1192 Operands.push_back(InstInfo.OperandList[j].Rec);
1193 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001194 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001195
1196 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001197 std::vector<Record*> ImpResults;
1198 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001199 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001200 DAGInstruction(0, Results, Operands, ImpResults,
1201 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001202 continue; // no pattern.
1203 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001204
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001205 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001206 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001207 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001208 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001209
Chris Lattner95f6b762005-09-08 23:26:30 +00001210 // Infer as many types as possible. If we cannot infer all of them, we can
1211 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001212 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001213 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001214
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001215 // InstInputs - Keep track of all of the inputs of the instruction, along
1216 // with the record they are declared as.
1217 std::map<std::string, TreePatternNode*> InstInputs;
1218
1219 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001220 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001221 std::map<std::string, Record*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001222
1223 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001224 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001225
Chris Lattner1f39e292005-09-14 00:09:24 +00001226 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001227 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001228 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1229 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001230 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001231 I->error("Top-level forms in instruction pattern should have"
1232 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001233
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001234 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001235 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001236 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001237 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001238
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001239 // Now that we have inputs and outputs of the pattern, inspect the operands
1240 // list for the instruction. This determines the order that operands are
1241 // added to the machine instruction the node corresponds to.
1242 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001243
1244 // Parse the operands list from the (ops) list, validating it.
1245 std::vector<std::string> &Args = I->getArgList();
1246 assert(Args.empty() && "Args list should still be empty here!");
1247 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1248
1249 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001250 std::vector<Record*> Results;
Chris Lattner39e8af92005-09-14 18:19:25 +00001251 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001252 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001253 I->error("'" + InstResults.begin()->first +
1254 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001255 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001256
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001257 // Check that it exists in InstResults.
1258 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +00001259 if (R == 0)
1260 I->error("Operand $" + OpName + " should be a set destination: all "
1261 "outputs must occur before inputs in operand list!");
1262
1263 if (CGI.OperandList[i].Rec != R)
1264 I->error("Operand $" + OpName + " class mismatch!");
1265
Chris Lattnerae6d8282005-09-15 21:51:12 +00001266 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001267 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001268
Chris Lattner39e8af92005-09-14 18:19:25 +00001269 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001270 InstResults.erase(OpName);
1271 }
1272
Chris Lattner0b592252005-09-14 21:59:34 +00001273 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1274 // the copy while we're checking the inputs.
1275 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001276
1277 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001278 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001279 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1280 const std::string &OpName = CGI.OperandList[i].Name;
1281 if (OpName.empty())
1282 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1283
Chris Lattner0b592252005-09-14 21:59:34 +00001284 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001285 I->error("Operand $" + OpName +
1286 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001287 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001288 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001289
1290 if (InVal->isLeaf() &&
1291 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1292 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001293 if (CGI.OperandList[i].Rec != InRec &&
1294 !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001295 I->error("Operand $" + OpName + "'s register class disagrees"
1296 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001297 }
1298 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001299
Chris Lattner2175c182005-09-14 23:01:59 +00001300 // Construct the result for the dest-pattern operand list.
1301 TreePatternNode *OpNode = InVal->clone();
1302
1303 // No predicate is useful on the result.
1304 OpNode->setPredicateFn("");
1305
1306 // Promote the xform function to be an explicit node if set.
1307 if (Record *Xform = OpNode->getTransformFn()) {
1308 OpNode->setTransformFn(0);
1309 std::vector<TreePatternNode*> Children;
1310 Children.push_back(OpNode);
1311 OpNode = new TreePatternNode(Xform, Children);
1312 }
1313
1314 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001315 }
1316
Chris Lattner0b592252005-09-14 21:59:34 +00001317 if (!InstInputsCheck.empty())
1318 I->error("Input operand $" + InstInputsCheck.begin()->first +
1319 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001320
1321 TreePatternNode *ResultPattern =
1322 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +00001323
1324 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001325 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001326 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1327
1328 // Use a temporary tree pattern to infer all types and make sure that the
1329 // constructed result is correct. This depends on the instruction already
1330 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001331 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001332 Temp.InferAllTypes();
1333
1334 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1335 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001336
Chris Lattner32707602005-09-08 23:22:48 +00001337 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001338 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001339
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001340 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001341 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1342 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001343 DAGInstruction &TheInst = II->second;
1344 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001345 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001346
Chris Lattner1f39e292005-09-14 00:09:24 +00001347 if (I->getNumTrees() != 1) {
1348 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1349 continue;
1350 }
1351 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001352 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001353 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001354 if (Pattern->getNumChildren() != 2)
1355 continue; // Not a set of a single value (not handled so far)
1356
1357 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001358 } else{
1359 // Not a set (store or something?)
1360 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001361 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001362
1363 std::string Reason;
1364 if (!SrcPattern->canPatternMatch(Reason, *this))
1365 I->error("Instruction can never match: " + Reason);
1366
Evan Cheng58e84a62005-12-14 22:02:59 +00001367 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001368 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001369 PatternsToMatch.
1370 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1371 SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +00001372 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001373}
1374
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001375void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001376 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001377
Chris Lattnerabbb6052005-09-15 21:42:00 +00001378 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001379 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001380 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001381
Chris Lattnerabbb6052005-09-15 21:42:00 +00001382 // Inline pattern fragments into it.
1383 Pattern->InlinePatternFragments();
1384
1385 // Infer as many types as possible. If we cannot infer all of them, we can
1386 // never do anything with this pattern: report it to the user.
1387 if (!Pattern->InferAllTypes())
1388 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001389
1390 // Validate that the input pattern is correct.
1391 {
1392 std::map<std::string, TreePatternNode*> InstInputs;
1393 std::map<std::string, Record*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001394 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001395 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001396 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001397 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001398 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001399 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001400
1401 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1402 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001403
1404 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001405 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001406
1407 // Inline pattern fragments into it.
1408 Result->InlinePatternFragments();
1409
1410 // Infer as many types as possible. If we cannot infer all of them, we can
1411 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001412 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001413 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001414
1415 if (Result->getNumTrees() != 1)
1416 Result->error("Cannot handle instructions producing instructions "
1417 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001418
1419 std::string Reason;
1420 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1421 Pattern->error("Pattern can never match: " + Reason);
1422
Evan Cheng58e84a62005-12-14 22:02:59 +00001423 PatternsToMatch.
1424 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1425 Pattern->getOnlyTree(),
1426 Result->getOnlyTree()));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001427 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001428}
1429
Chris Lattnere46e17b2005-09-29 19:28:10 +00001430/// CombineChildVariants - Given a bunch of permutations of each child of the
1431/// 'operator' node, put them together in all possible ways.
1432static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001433 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001434 std::vector<TreePatternNode*> &OutVariants,
1435 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001436 // Make sure that each operand has at least one variant to choose from.
1437 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1438 if (ChildVariants[i].empty())
1439 return;
1440
Chris Lattnere46e17b2005-09-29 19:28:10 +00001441 // The end result is an all-pairs construction of the resultant pattern.
1442 std::vector<unsigned> Idxs;
1443 Idxs.resize(ChildVariants.size());
1444 bool NotDone = true;
1445 while (NotDone) {
1446 // Create the variant and add it to the output list.
1447 std::vector<TreePatternNode*> NewChildren;
1448 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1449 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1450 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1451
1452 // Copy over properties.
1453 R->setName(Orig->getName());
1454 R->setPredicateFn(Orig->getPredicateFn());
1455 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001456 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001457
1458 // If this pattern cannot every match, do not include it as a variant.
1459 std::string ErrString;
1460 if (!R->canPatternMatch(ErrString, ISE)) {
1461 delete R;
1462 } else {
1463 bool AlreadyExists = false;
1464
1465 // Scan to see if this pattern has already been emitted. We can get
1466 // duplication due to things like commuting:
1467 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1468 // which are the same pattern. Ignore the dups.
1469 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1470 if (R->isIsomorphicTo(OutVariants[i])) {
1471 AlreadyExists = true;
1472 break;
1473 }
1474
1475 if (AlreadyExists)
1476 delete R;
1477 else
1478 OutVariants.push_back(R);
1479 }
1480
1481 // Increment indices to the next permutation.
1482 NotDone = false;
1483 // Look for something we can increment without causing a wrap-around.
1484 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1485 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1486 NotDone = true; // Found something to increment.
1487 break;
1488 }
1489 Idxs[IdxsIdx] = 0;
1490 }
1491 }
1492}
1493
Chris Lattneraf302912005-09-29 22:36:54 +00001494/// CombineChildVariants - A helper function for binary operators.
1495///
1496static void CombineChildVariants(TreePatternNode *Orig,
1497 const std::vector<TreePatternNode*> &LHS,
1498 const std::vector<TreePatternNode*> &RHS,
1499 std::vector<TreePatternNode*> &OutVariants,
1500 DAGISelEmitter &ISE) {
1501 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1502 ChildVariants.push_back(LHS);
1503 ChildVariants.push_back(RHS);
1504 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1505}
1506
1507
1508static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1509 std::vector<TreePatternNode *> &Children) {
1510 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1511 Record *Operator = N->getOperator();
1512
1513 // Only permit raw nodes.
1514 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1515 N->getTransformFn()) {
1516 Children.push_back(N);
1517 return;
1518 }
1519
1520 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1521 Children.push_back(N->getChild(0));
1522 else
1523 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1524
1525 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1526 Children.push_back(N->getChild(1));
1527 else
1528 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1529}
1530
Chris Lattnere46e17b2005-09-29 19:28:10 +00001531/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1532/// the (potentially recursive) pattern by using algebraic laws.
1533///
1534static void GenerateVariantsOf(TreePatternNode *N,
1535 std::vector<TreePatternNode*> &OutVariants,
1536 DAGISelEmitter &ISE) {
1537 // We cannot permute leaves.
1538 if (N->isLeaf()) {
1539 OutVariants.push_back(N);
1540 return;
1541 }
1542
1543 // Look up interesting info about the node.
1544 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1545
1546 // If this node is associative, reassociate.
Chris Lattneraf302912005-09-29 22:36:54 +00001547 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1548 // Reassociate by pulling together all of the linked operators
1549 std::vector<TreePatternNode*> MaximalChildren;
1550 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1551
1552 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1553 // permutations.
1554 if (MaximalChildren.size() == 3) {
1555 // Find the variants of all of our maximal children.
1556 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1557 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1558 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1559 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1560
1561 // There are only two ways we can permute the tree:
1562 // (A op B) op C and A op (B op C)
1563 // Within these forms, we can also permute A/B/C.
1564
1565 // Generate legal pair permutations of A/B/C.
1566 std::vector<TreePatternNode*> ABVariants;
1567 std::vector<TreePatternNode*> BAVariants;
1568 std::vector<TreePatternNode*> ACVariants;
1569 std::vector<TreePatternNode*> CAVariants;
1570 std::vector<TreePatternNode*> BCVariants;
1571 std::vector<TreePatternNode*> CBVariants;
1572 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1573 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1574 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1575 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1576 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1577 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1578
1579 // Combine those into the result: (x op x) op x
1580 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1581 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1582 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1583 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1584 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1585 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1586
1587 // Combine those into the result: x op (x op x)
1588 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1589 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1590 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1591 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1592 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1593 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1594 return;
1595 }
1596 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001597
1598 // Compute permutations of all children.
1599 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1600 ChildVariants.resize(N->getNumChildren());
1601 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1602 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1603
1604 // Build all permutations based on how the children were formed.
1605 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1606
1607 // If this node is commutative, consider the commuted order.
1608 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1609 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001610 // Consider the commuted order.
1611 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1612 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001613 }
1614}
1615
1616
Chris Lattnere97603f2005-09-28 19:27:25 +00001617// GenerateVariants - Generate variants. For example, commutative patterns can
1618// match multiple ways. Add them to PatternsToMatch as well.
1619void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001620
1621 DEBUG(std::cerr << "Generating instruction variants.\n");
1622
1623 // Loop over all of the patterns we've collected, checking to see if we can
1624 // generate variants of the instruction, through the exploitation of
1625 // identities. This permits the target to provide agressive matching without
1626 // the .td file having to contain tons of variants of instructions.
1627 //
1628 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1629 // intentionally do not reconsider these. Any variants of added patterns have
1630 // already been added.
1631 //
1632 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1633 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001634 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001635
1636 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001637 Variants.erase(Variants.begin()); // Remove the original pattern.
1638
1639 if (Variants.empty()) // No variants for this pattern.
1640 continue;
1641
1642 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001643 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001644 std::cerr << "\n");
1645
1646 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1647 TreePatternNode *Variant = Variants[v];
1648
1649 DEBUG(std::cerr << " VAR#" << v << ": ";
1650 Variant->dump();
1651 std::cerr << "\n");
1652
1653 // Scan to see if an instruction or explicit pattern already matches this.
1654 bool AlreadyExists = false;
1655 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1656 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001657 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001658 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1659 AlreadyExists = true;
1660 break;
1661 }
1662 }
1663 // If we already have it, ignore the variant.
1664 if (AlreadyExists) continue;
1665
1666 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001667 PatternsToMatch.
1668 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1669 Variant, PatternsToMatch[i].getDstPattern()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001670 }
1671
1672 DEBUG(std::cerr << "\n");
1673 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001674}
1675
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001676
Evan Cheng0fc71982005-12-08 02:00:36 +00001677// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1678// ComplexPattern.
1679static bool NodeIsComplexPattern(TreePatternNode *N)
1680{
1681 return (N->isLeaf() &&
1682 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1683 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1684 isSubClassOf("ComplexPattern"));
1685}
1686
1687// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1688// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1689static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1690 DAGISelEmitter &ISE)
1691{
1692 if (N->isLeaf() &&
1693 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1694 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1695 isSubClassOf("ComplexPattern")) {
1696 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1697 ->getDef());
1698 }
1699 return NULL;
1700}
1701
Chris Lattner05814af2005-09-28 17:57:56 +00001702/// getPatternSize - Return the 'size' of this pattern. We want to match large
1703/// patterns before small ones. This is used to determine the size of a
1704/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001705static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng4a7c2842006-01-06 22:19:44 +00001706 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1707 isExtFloatingPointInVTs(P->getExtTypes()) ||
1708 P->getExtTypeNum(0) == MVT::isVoid ||
1709 P->getExtTypeNum(0) == MVT::Flag &&
1710 "Not a valid pattern node to size!");
Evan Chenge1050d62006-01-06 02:30:23 +00001711 unsigned Size = 2; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00001712 // If the root node is a ConstantSDNode, increases its size.
1713 // e.g. (set R32:$dst, 0).
1714 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1715 Size++;
Evan Cheng0fc71982005-12-08 02:00:36 +00001716
1717 // FIXME: This is a hack to statically increase the priority of patterns
1718 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1719 // Later we can allow complexity / cost for each pattern to be (optionally)
1720 // specified. To get best possible pattern match we'll need to dynamically
1721 // calculate the complexity of all patterns a dag can potentially map to.
1722 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1723 if (AM)
Evan Cheng4a7c2842006-01-06 22:19:44 +00001724 Size += AM->getNumOperands() * 2;
Chris Lattner3e179802006-02-03 18:06:02 +00001725
1726 // If this node has some predicate function that must match, it adds to the
1727 // complexity of this node.
1728 if (!P->getPredicateFn().empty())
1729 ++Size;
1730
Chris Lattner05814af2005-09-28 17:57:56 +00001731 // Count children in the count if they are also nodes.
1732 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1733 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001734 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001735 Size += getPatternSize(Child, ISE);
1736 else if (Child->isLeaf()) {
1737 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner3e179802006-02-03 18:06:02 +00001738 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
Evan Cheng4a7c2842006-01-06 22:19:44 +00001739 else if (NodeIsComplexPattern(Child))
1740 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00001741 else if (!Child->getPredicateFn().empty())
1742 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001743 }
Chris Lattner05814af2005-09-28 17:57:56 +00001744 }
1745
1746 return Size;
1747}
1748
1749/// getResultPatternCost - Compute the number of instructions for this pattern.
1750/// This is a temporary hack. We should really include the instruction
1751/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00001752static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00001753 if (P->isLeaf()) return 0;
1754
Evan Chengfbad7082006-02-18 02:33:09 +00001755 unsigned Cost = 0;
1756 Record *Op = P->getOperator();
1757 if (Op->isSubClassOf("Instruction")) {
1758 Cost++;
1759 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1760 if (II.usesCustomDAGSchedInserter)
1761 Cost += 10;
1762 }
Chris Lattner05814af2005-09-28 17:57:56 +00001763 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00001764 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001765 return Cost;
1766}
1767
1768// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1769// In particular, we want to match maximal patterns first and lowest cost within
1770// a particular complexity first.
1771struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001772 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1773 DAGISelEmitter &ISE;
1774
Evan Cheng58e84a62005-12-14 22:02:59 +00001775 bool operator()(PatternToMatch *LHS,
1776 PatternToMatch *RHS) {
1777 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1778 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001779 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1780 if (LHSSize < RHSSize) return false;
1781
1782 // If the patterns have equal complexity, compare generated instruction cost
Evan Chengfbad7082006-02-18 02:33:09 +00001783 return getResultPatternCost(LHS->getDstPattern(), ISE) <
1784 getResultPatternCost(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001785 }
1786};
1787
Nate Begeman6510b222005-12-01 04:51:06 +00001788/// getRegisterValueType - Look up and return the first ValueType of specified
1789/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001790static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001791 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1792 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001793 return MVT::Other;
1794}
1795
Chris Lattner72fe91c2005-09-24 00:40:24 +00001796
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001797/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1798/// type information from it.
1799static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001800 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001801 if (!N->isLeaf())
1802 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1803 RemoveAllTypes(N->getChild(i));
1804}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001805
Chris Lattner0614b622005-11-02 06:49:14 +00001806Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1807 Record *N = Records.getDef(Name);
1808 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1809 return N;
1810}
1811
Evan Cheng51fecc82006-01-09 18:27:06 +00001812/// NodeHasProperty - return true if TreePatternNode has the specified
1813/// property.
1814static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1815 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001816{
1817 if (N->isLeaf()) return false;
1818 Record *Operator = N->getOperator();
1819 if (!Operator->isSubClassOf("SDNode")) return false;
1820
1821 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00001822 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00001823}
1824
Evan Cheng51fecc82006-01-09 18:27:06 +00001825static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1826 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001827{
Evan Cheng51fecc82006-01-09 18:27:06 +00001828 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00001829 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00001830
1831 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1832 TreePatternNode *Child = N->getChild(i);
1833 if (PatternHasProperty(Child, Property, ISE))
1834 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001835 }
1836
1837 return false;
1838}
1839
Evan Chengb915f312005-12-09 22:45:35 +00001840class PatternCodeEmitter {
1841private:
1842 DAGISelEmitter &ISE;
1843
Evan Cheng58e84a62005-12-14 22:02:59 +00001844 // Predicates.
1845 ListInit *Predicates;
1846 // Instruction selector pattern.
1847 TreePatternNode *Pattern;
1848 // Matched instruction.
1849 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001850
Evan Chengb915f312005-12-09 22:45:35 +00001851 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00001852 std::map<std::string, std::string> VariableMap;
1853 // Node to operator mapping
1854 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00001855 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001856 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00001857 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +00001858
Chris Lattner8a0604b2006-01-28 20:31:24 +00001859 /// GeneratedCode - This is the buffer that we emit code to. The first bool
1860 /// indicates whether this is an exit predicate (something that should be
1861 /// tested, and if true, the match fails) [when true] or normal code to emit
1862 /// [when false].
1863 std::vector<std::pair<bool, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00001864 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
1865 /// the set of patterns for each top-level opcode.
Evan Chengd7805a72006-02-09 07:16:09 +00001866 std::set<std::pair<bool, std::string> > &GeneratedDecl;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001867
Evan Chenge4a8a6e2006-02-03 06:22:41 +00001868 std::string ChainName;
Evan Chenge41bf822006-02-05 06:43:12 +00001869 bool DoReplace;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001870 unsigned TmpNo;
1871
1872 void emitCheck(const std::string &S) {
1873 if (!S.empty())
1874 GeneratedCode.push_back(std::make_pair(true, S));
1875 }
1876 void emitCode(const std::string &S) {
1877 if (!S.empty())
1878 GeneratedCode.push_back(std::make_pair(false, S));
1879 }
Evan Chengd7805a72006-02-09 07:16:09 +00001880 void emitDecl(const std::string &S, bool isSDNode=false) {
Evan Cheng21ad3922006-02-07 00:37:41 +00001881 assert(!S.empty() && "Invalid declaration");
Evan Chengd7805a72006-02-09 07:16:09 +00001882 GeneratedDecl.insert(std::make_pair(isSDNode, S));
Evan Cheng21ad3922006-02-07 00:37:41 +00001883 }
Evan Chengb915f312005-12-09 22:45:35 +00001884public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001885 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1886 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng21ad3922006-02-07 00:37:41 +00001887 std::vector<std::pair<bool, std::string> > &gc,
Evan Chengd7805a72006-02-09 07:16:09 +00001888 std::set<std::pair<bool, std::string> > &gd,
Evan Cheng21ad3922006-02-07 00:37:41 +00001889 bool dorep)
Chris Lattner8a0604b2006-01-28 20:31:24 +00001890 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng21ad3922006-02-07 00:37:41 +00001891 GeneratedCode(gc), GeneratedDecl(gd), DoReplace(dorep), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00001892
1893 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1894 /// if the match fails. At this point, we already know that the opcode for N
1895 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00001896 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
1897 const std::string &RootName, const std::string &ParentName,
1898 const std::string &ChainSuffix, bool &FoundChain) {
1899 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00001900 // Emit instruction predicates. Each predicate is just a string for now.
1901 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001902 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00001903 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1904 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1905 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00001906 if (!Def->isSubClassOf("Predicate")) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001907 Def->dump();
1908 assert(0 && "Unknown predicate type!");
1909 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00001910 if (!PredicateCheck.empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00001911 PredicateCheck += " || ";
1912 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00001913 }
1914 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00001915
1916 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00001917 }
1918
Evan Chengb915f312005-12-09 22:45:35 +00001919 if (N->isLeaf()) {
1920 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001921 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00001922 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00001923 return;
1924 } else if (!NodeIsComplexPattern(N)) {
1925 assert(0 && "Cannot match this as a leaf value!");
1926 abort();
1927 }
1928 }
1929
Chris Lattner488580c2006-01-28 19:06:51 +00001930 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00001931 // we already saw this in the pattern, emit code to verify dagness.
1932 if (!N->getName().empty()) {
1933 std::string &VarMapEntry = VariableMap[N->getName()];
1934 if (VarMapEntry.empty()) {
1935 VarMapEntry = RootName;
1936 } else {
1937 // If we get here, this is a second reference to a specific name. Since
1938 // we already have checked that the first reference is valid, we don't
1939 // have to recursively match it, just check that it's the same as the
1940 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00001941 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00001942 return;
1943 }
Evan Chengf805c2e2006-01-12 19:35:54 +00001944
1945 if (!N->isLeaf())
1946 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00001947 }
1948
1949
1950 // Emit code to load the child nodes and match their contents recursively.
1951 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00001952 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
1953 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
1954 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00001955 bool EmittedUseCheck = false;
1956 bool EmittedSlctedCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00001957 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00001958 if (NodeHasChain)
1959 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00001960 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001961 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattner8a0604b2006-01-28 20:31:24 +00001962 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00001963 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00001964 EmittedUseCheck = true;
1965 // hasOneUse() check is not strong enough. If the original node has
1966 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00001967 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00001968 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00001969 "))");
1970
Evan Cheng1feeeec2006-01-26 19:13:45 +00001971 EmittedSlctedCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00001972 if (NodeHasChain) {
1973 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
1974 // has a chain use.
1975 // This a workaround for this problem:
1976 //
1977 // [ch, r : ld]
1978 // ^ ^
1979 // | |
1980 // [XX]--/ \- [flag : cmp]
1981 // ^ ^
1982 // | |
1983 // \---[br flag]-
1984 //
1985 // cmp + br should be considered as a single node as they are flagged
1986 // together. So, if the ld is folded into the cmp, the XX node in the
1987 // graph is now both an operand and a use of the ld/cmp/br node.
1988 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
1989 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
1990
1991 // If the immediate use can somehow reach this node through another
1992 // path, then can't fold it either or it will create a cycle.
1993 // e.g. In the following diagram, XX can reach ld through YY. If
1994 // ld is folded into XX, then YY is both a predecessor and a successor
1995 // of XX.
1996 //
1997 // [ld]
1998 // ^ ^
1999 // | |
2000 // / \---
2001 // / [YY]
2002 // | ^
2003 // [XX]-------|
2004 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2005 if (PInfo.getNumOperands() > 1 ||
2006 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2007 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2008 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
Evan Cheng6f8aaf22006-03-07 08:31:27 +00002009 if (PInfo.getNumOperands() > 1) {
2010 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2011 ".Val)");
2012 } else {
2013 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2014 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2015 ".Val))");
2016 }
Evan Chenge41bf822006-02-05 06:43:12 +00002017 }
Evan Chengb915f312005-12-09 22:45:35 +00002018 }
Evan Chenge41bf822006-02-05 06:43:12 +00002019
Evan Chengc15d18c2006-01-27 22:13:45 +00002020 if (NodeHasChain) {
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002021 if (FoundChain)
Chris Lattner67a202b2006-01-28 20:43:52 +00002022 emitCheck("Chain.Val == " + RootName + ".Val");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002023 else
2024 FoundChain = true;
2025 ChainName = "Chain" + ChainSuffix;
Evan Cheng21ad3922006-02-07 00:37:41 +00002026 emitDecl(ChainName);
2027 emitCode(ChainName + " = " + RootName +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002028 ".getOperand(0);");
Evan Cheng1cf6db22006-01-06 00:41:12 +00002029 }
Evan Chengb915f312005-12-09 22:45:35 +00002030 }
2031
Evan Cheng54597732006-01-26 00:22:25 +00002032 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002033 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002034 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002035 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2036 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002037 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002038 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2039 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2040 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002041 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2042 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002043 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002044 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002045 }
Evan Cheng1feeeec2006-01-26 19:13:45 +00002046 if (!EmittedSlctedCheck)
2047 // hasOneUse() check is not strong enough. If the original node has
2048 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002049 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002050 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002051 "))");
Evan Cheng54597732006-01-26 00:22:25 +00002052 }
2053
Evan Chengb915f312005-12-09 22:45:35 +00002054 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002055 emitDecl(RootName + utostr(OpNo));
2056 emitCode(RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002057 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002058 TreePatternNode *Child = N->getChild(i);
2059
2060 if (!Child->isLeaf()) {
2061 // If it's not a leaf, recursively match.
2062 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002063 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002064 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002065 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2066 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002067 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002068 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2069 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002070 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002071 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002072 // we already saw this in the pattern, emit code to verify dagness.
2073 if (!Child->getName().empty()) {
2074 std::string &VarMapEntry = VariableMap[Child->getName()];
2075 if (VarMapEntry.empty()) {
2076 VarMapEntry = RootName + utostr(OpNo);
2077 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002078 // If we get here, this is a second reference to a specific name.
2079 // Since we already have checked that the first reference is valid,
2080 // we don't have to recursively match it, just check that it's the
2081 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002082 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002083 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002084 continue;
2085 }
2086 }
2087
2088 // Handle leaves of various types.
2089 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2090 Record *LeafRec = DI->getDef();
2091 if (LeafRec->isSubClassOf("RegisterClass")) {
2092 // Handle register references. Nothing to do here.
2093 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002094 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002095 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2096 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00002097 } else if (LeafRec->getName() == "srcvalue") {
2098 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002099 } else if (LeafRec->isSubClassOf("ValueType")) {
2100 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002101 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002102 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002103 } else if (LeafRec->isSubClassOf("CondCode")) {
2104 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002105 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002106 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002107 } else {
2108 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002109 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00002110 assert(0 && "Unknown leaf type!");
2111 }
Chris Lattner488580c2006-01-28 19:06:51 +00002112 } else if (IntInit *II =
2113 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002114 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2115 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002116 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002117 RootName + utostr(OpNo) + ")->getSignExtended();");
2118
2119 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002120 } else {
2121 Child->dump();
2122 assert(0 && "Unknown leaf type!");
2123 }
2124 }
2125 }
2126
2127 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002128 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002129 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002130 }
2131
2132 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2133 /// we actually have to build a DAG!
2134 std::pair<unsigned, unsigned>
2135 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
2136 // This is something selected from the pattern we matched.
2137 if (!N->getName().empty()) {
2138 assert(!isRoot && "Root of pattern cannot be a leaf!");
2139 std::string &Val = VariableMap[N->getName()];
2140 assert(!Val.empty() &&
2141 "Variable referenced but not defined and not caught earlier!");
2142 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2143 // Already selected this operand, just return the tmpval.
2144 return std::make_pair(1, atoi(Val.c_str()+3));
2145 }
2146
2147 const ComplexPattern *CP;
2148 unsigned ResNo = TmpNo++;
2149 unsigned NumRes = 1;
2150 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002151 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002152 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002153 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002154 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002155 case MVT::i1: CastType = "bool"; break;
2156 case MVT::i8: CastType = "unsigned char"; break;
2157 case MVT::i16: CastType = "unsigned short"; break;
2158 case MVT::i32: CastType = "unsigned"; break;
2159 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002160 }
Chris Lattner78593132006-01-29 20:01:35 +00002161 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
Andrew Lenharth2cba57c2006-01-29 05:17:22 +00002162 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
Evan Cheng21ad3922006-02-07 00:37:41 +00002163 emitDecl("Tmp" + utostr(ResNo));
2164 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002165 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2166 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengbb48e332006-01-12 07:54:57 +00002167 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002168 Record *Op = OperatorMap[N->getName()];
2169 // Transform ExternalSymbol to TargetExternalSymbol
2170 if (Op && Op->getName() == "externalsym") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002171 emitDecl("Tmp" + utostr(ResNo));
2172 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002173 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2174 Val + ")->getSymbol(), MVT::" +
2175 getEnumName(N->getTypeNum(0)) + ");");
2176 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002177 emitDecl("Tmp" + utostr(ResNo));
2178 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002179 }
Evan Chengb915f312005-12-09 22:45:35 +00002180 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002181 Record *Op = OperatorMap[N->getName()];
2182 // Transform GlobalAddress to TargetGlobalAddress
2183 if (Op && Op->getName() == "globaladdr") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002184 emitDecl("Tmp" + utostr(ResNo));
2185 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002186 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2187 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2188 ");");
2189 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002190 emitDecl("Tmp" + utostr(ResNo));
2191 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002192 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002193 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng21ad3922006-02-07 00:37:41 +00002194 emitDecl("Tmp" + utostr(ResNo));
2195 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengbb48e332006-01-12 07:54:57 +00002196 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002197 emitDecl("Tmp" + utostr(ResNo));
2198 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002199 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2200 std::string Fn = CP->getSelectFunc();
2201 NumRes = CP->getNumOperands();
Evan Cheng21ad3922006-02-07 00:37:41 +00002202 for (unsigned i = 0; i < NumRes; ++i)
2203 emitDecl("Tmp" + utostr(i+ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002204
Evan Cheng21ad3922006-02-07 00:37:41 +00002205 std::string Code = Fn + "(" + Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002206 for (unsigned i = 0; i < NumRes; i++)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002207 Code += ", Tmp" + utostr(i + ResNo);
2208 emitCheck(Code + ")");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002209
Evan Cheng2216d8a2006-02-05 05:22:18 +00002210 for (unsigned i = 0; i < NumRes; ++i)
Evan Cheng34167212006-02-09 00:37:58 +00002211 emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
Evan Cheng2216d8a2006-02-05 05:22:18 +00002212 utostr(i+ResNo) + ");");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002213
Evan Chengb915f312005-12-09 22:45:35 +00002214 TmpNo = ResNo + NumRes;
2215 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002216 emitDecl("Tmp" + utostr(ResNo));
Evan Cheng34167212006-02-09 00:37:58 +00002217 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002218 }
2219 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2220 // value if used multiple times by this pattern result.
2221 Val = "Tmp"+utostr(ResNo);
2222 return std::make_pair(NumRes, ResNo);
2223 }
2224
2225 if (N->isLeaf()) {
2226 // If this is an explicit register reference, handle it.
2227 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2228 unsigned ResNo = TmpNo++;
2229 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002230 emitDecl("Tmp" + utostr(ResNo));
2231 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002232 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2233 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002234 return std::make_pair(1, ResNo);
2235 }
2236 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2237 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002238 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng21ad3922006-02-07 00:37:41 +00002239 emitDecl("Tmp" + utostr(ResNo));
2240 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002241 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2242 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002243 return std::make_pair(1, ResNo);
2244 }
2245
2246 N->dump();
2247 assert(0 && "Unknown leaf type!");
2248 return std::make_pair(1, ~0U);
2249 }
2250
2251 Record *Op = N->getOperator();
2252 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002253 const CodeGenTarget &CGT = ISE.getTargetInfo();
2254 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002255 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002256 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2257 bool HasImpResults = Inst.getNumImpResults() > 0;
Evan Cheng54597732006-01-26 00:22:25 +00002258 bool HasOptInFlag = isRoot &&
2259 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002260 bool HasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002261 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2262 bool NodeHasOutFlag = HasImpResults ||
Evan Cheng51fecc82006-01-09 18:27:06 +00002263 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
Evan Cheng823b7522006-01-19 21:57:10 +00002264 bool NodeHasChain =
2265 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002266 bool HasChain = II.hasCtrlDep ||
2267 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
Evan Cheng4fba2812005-12-20 07:37:41 +00002268
Evan Cheng54597732006-01-26 00:22:25 +00002269 if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
Evan Cheng21ad3922006-02-07 00:37:41 +00002270 emitDecl("InFlag");
Evan Cheng54597732006-01-26 00:22:25 +00002271 if (HasOptInFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002272 emitCode("bool HasOptInFlag = false;");
Evan Cheng4fba2812005-12-20 07:37:41 +00002273
Evan Cheng823b7522006-01-19 21:57:10 +00002274 // How many results is this pattern expected to produce?
2275 unsigned NumExpectedResults = 0;
2276 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2277 MVT::ValueType VT = Pattern->getTypeNum(i);
2278 if (VT != MVT::isVoid && VT != MVT::Flag)
2279 NumExpectedResults++;
2280 }
2281
Evan Chengb915f312005-12-09 22:45:35 +00002282 // Determine operand emission order. Complex pattern first.
2283 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2284 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2285 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2286 TreePatternNode *Child = N->getChild(i);
2287 if (i == 0) {
2288 EmitOrder.push_back(std::make_pair(i, Child));
2289 OI = EmitOrder.begin();
2290 } else if (NodeIsComplexPattern(Child)) {
2291 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2292 } else {
2293 EmitOrder.push_back(std::make_pair(i, Child));
2294 }
2295 }
2296
2297 // Emit all of the operands.
2298 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2299 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2300 unsigned OpOrder = EmitOrder[i].first;
2301 TreePatternNode *Child = EmitOrder[i].second;
2302 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2303 NumTemps[OpOrder] = NumTemp;
2304 }
2305
2306 // List all the operands in the right order.
2307 std::vector<unsigned> Ops;
2308 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2309 for (unsigned j = 0; j < NumTemps[i].first; j++)
2310 Ops.push_back(NumTemps[i].second + j);
2311 }
2312
Evan Chengb915f312005-12-09 22:45:35 +00002313 // Emit all the chain and CopyToReg stuff.
Evan Chengb2c6d492006-01-11 22:16:13 +00002314 bool ChainEmitted = HasChain;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002315 if (HasChain)
Evan Cheng34167212006-02-09 00:37:58 +00002316 emitCode("Select(" + ChainName + ", " + ChainName + ");");
Evan Cheng54597732006-01-26 00:22:25 +00002317 if (HasInFlag || HasOptInFlag || HasImpInputs)
2318 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
Evan Chengb915f312005-12-09 22:45:35 +00002319
Evan Chengb915f312005-12-09 22:45:35 +00002320 unsigned NumResults = Inst.getNumResults();
2321 unsigned ResNo = TmpNo++;
2322 if (!isRoot) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002323 emitDecl("Tmp" + utostr(ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002324 std::string Code =
Evan Chengd7805a72006-02-09 07:16:09 +00002325 "Tmp" + utostr(ResNo) + " = SDOperand(CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002326 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002327 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002328 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002329 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002330 Code += ", MVT::Flag";
Evan Chengbcecf332005-12-17 01:19:28 +00002331
Evan Chengb915f312005-12-09 22:45:35 +00002332 unsigned LastOp = 0;
2333 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2334 LastOp = Ops[i];
Chris Lattner8a0604b2006-01-28 20:31:24 +00002335 Code += ", Tmp" + utostr(LastOp);
Evan Chengb915f312005-12-09 22:45:35 +00002336 }
Evan Chengd7805a72006-02-09 07:16:09 +00002337 emitCode(Code + "), 0);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002338 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002339 // Must have at least one result
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002340 emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002341 utostr(NumResults) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002342 }
Evan Cheng54597732006-01-26 00:22:25 +00002343 } else if (HasChain || NodeHasOutFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002344 if (HasOptInFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002345 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
Evan Chengd7805a72006-02-09 07:16:09 +00002346 emitDecl("ResNode", true);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002347 emitCode("if (HasOptInFlag)");
Evan Chengd7805a72006-02-09 07:16:09 +00002348 std::string Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002349 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002350
Evan Cheng9789aaa2006-01-24 20:46:50 +00002351 // Output order: results, chain, flags
2352 // Result types.
2353 if (NumResults > 0) {
2354 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002355 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002356 }
2357 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002358 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002359 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002360 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002361
2362 // Inputs.
2363 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002364 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002365 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002366 emitCode(Code + ", InFlag);");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002367
Chris Lattner8a0604b2006-01-28 20:31:24 +00002368 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002369 Code = " ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002370 II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002371
2372 // Output order: results, chain, flags
2373 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002374 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2375 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002376 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002377 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002378 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002379 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002380
2381 // Inputs.
2382 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002383 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002384 if (HasChain) Code += ", " + ChainName + ");";
Chris Lattner8a0604b2006-01-28 20:31:24 +00002385 emitCode(Code);
Evan Cheng9789aaa2006-01-24 20:46:50 +00002386 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002387 emitDecl("ResNode", true);
2388 std::string Code = "ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002389 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002390
2391 // Output order: results, chain, flags
2392 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002393 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2394 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002395 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002396 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002397 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002398 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002399
2400 // Inputs.
2401 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002402 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002403 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002404 if (HasInFlag || HasImpInputs) Code += ", InFlag";
2405 emitCode(Code + ");");
Evan Chengbcecf332005-12-17 01:19:28 +00002406 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002407
2408 unsigned ValNo = 0;
Evan Chengf9fc25d2005-12-19 22:40:04 +00002409 for (unsigned i = 0; i < NumResults; i++) {
Evan Cheng67212a02006-02-09 22:12:27 +00002410 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2411 utostr(ValNo) + ", ResNode, " + utostr(ValNo) + ");");
Evan Chengf9fc25d2005-12-19 22:40:04 +00002412 ValNo++;
2413 }
2414
Evan Cheng54597732006-01-26 00:22:25 +00002415 if (NodeHasOutFlag)
Evan Chengd7805a72006-02-09 07:16:09 +00002416 emitCode("InFlag = SDOperand(ResNode, " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002417 utostr(ValNo + (unsigned)HasChain) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002418
Chris Lattner8a0604b2006-01-28 20:31:24 +00002419 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
Evan Cheng67212a02006-02-09 22:12:27 +00002420 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2421 utostr(ValNo) + ", ResNode, " + utostr(ValNo) + ");");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002422 ValNo++;
Evan Cheng97938882005-12-22 02:24:50 +00002423 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002424
Evan Chengd7805a72006-02-09 07:16:09 +00002425 // User does not expect the instruction would produce a chain!
Evan Cheng51fecc82006-01-09 18:27:06 +00002426 bool AddedChain = HasChain && !NodeHasChain;
Evan Chenge41bf822006-02-05 06:43:12 +00002427 if (NodeHasChain) {
Evan Cheng67212a02006-02-09 22:12:27 +00002428 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2429 utostr(ValNo) + ", ResNode, " + utostr(ValNo) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002430 if (DoReplace)
Evan Cheng67212a02006-02-09 22:12:27 +00002431 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, "
2432 + utostr(ValNo) + ", " + "ResNode, " + utostr(ValNo) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002433 ValNo++;
2434 }
2435
Evan Cheng97938882005-12-22 02:24:50 +00002436
2437 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002438 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002439 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng67212a02006-02-09 22:12:27 +00002440 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2441 FoldedChains[j].first + ".Val, " +
2442 utostr(FoldedChains[j].second) + ", ResNode, " +
2443 utostr(ValNo) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002444
2445 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2446 std::string Code =
Evan Cheng67212a02006-02-09 22:12:27 +00002447 FoldedChains[j].first + ".Val, " +
2448 utostr(FoldedChains[j].second) + ", ";
2449 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2450 utostr(ValNo) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002451 }
Evan Chengb915f312005-12-09 22:45:35 +00002452 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002453
Evan Cheng54597732006-01-26 00:22:25 +00002454 if (NodeHasOutFlag)
Evan Cheng67212a02006-02-09 22:12:27 +00002455 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2456 utostr(ValNo) + ", InFlag.Val, InFlag.ResNo);");
Evan Cheng97938882005-12-22 02:24:50 +00002457
Evan Cheng54597732006-01-26 00:22:25 +00002458 if (AddedChain && NodeHasOutFlag) {
Evan Cheng823b7522006-01-19 21:57:10 +00002459 if (NumExpectedResults == 0) {
Evan Chengd7805a72006-02-09 07:16:09 +00002460 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002461 } else {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002462 emitCode("if (N.ResNo < " + utostr(NumExpectedResults) + ")");
Evan Chengd7805a72006-02-09 07:16:09 +00002463 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002464 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002465 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002466 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002467 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002468 emitCode("Result = SDOperand(ResNode, N.ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002469 }
Evan Chengb915f312005-12-09 22:45:35 +00002470 } else {
2471 // If this instruction is the root, and if there is only one use of it,
2472 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002473 emitCode("if (N.Val->hasOneUse()) {");
Evan Cheng34167212006-02-09 00:37:58 +00002474 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002475 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002476 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002477 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002478 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002479 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002480 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002481 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002482 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002483 Code += ", InFlag";
2484 emitCode(Code + ");");
2485 emitCode("} else {");
Evan Chengd7805a72006-02-09 07:16:09 +00002486 emitDecl("ResNode", true);
2487 Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002488 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002489 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002490 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002491 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002492 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002493 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002494 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002495 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002496 Code += ", InFlag";
2497 emitCode(Code + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002498 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2499 "ResNode, 0);");
2500 emitCode(" Result = SDOperand(ResNode, 0);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002501 emitCode("}");
Evan Chengb915f312005-12-09 22:45:35 +00002502 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002503
Evan Cheng34167212006-02-09 00:37:58 +00002504 if (isRoot)
2505 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002506 return std::make_pair(1, ResNo);
2507 } else if (Op->isSubClassOf("SDNodeXForm")) {
2508 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002509 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002510 unsigned ResNo = TmpNo++;
Evan Cheng21ad3922006-02-07 00:37:41 +00002511 emitDecl("Tmp" + utostr(ResNo));
2512 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Chris Lattner8a0604b2006-01-28 20:31:24 +00002513 + "(Tmp" + utostr(OpVal) + ".Val);");
Evan Chengb915f312005-12-09 22:45:35 +00002514 if (isRoot) {
Evan Cheng67212a02006-02-09 22:12:27 +00002515 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2516 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2517 utostr(ResNo) + ".ResNo);");
Evan Cheng34167212006-02-09 00:37:58 +00002518 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2519 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002520 }
2521 return std::make_pair(1, ResNo);
2522 } else {
2523 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002524 std::cerr << "\n";
2525 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002526 }
2527 }
2528
Chris Lattner488580c2006-01-28 19:06:51 +00002529 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2530 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002531 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2532 /// for, this returns true otherwise false if Pat has all types.
2533 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2534 const std::string &Prefix) {
2535 // Did we find one?
2536 if (!Pat->hasTypeSet()) {
2537 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002538 Pat->setTypes(Other->getExtTypes());
Chris Lattner67a202b2006-01-28 20:43:52 +00002539 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002540 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002541 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002542 }
2543
Evan Cheng51fecc82006-01-09 18:27:06 +00002544 unsigned OpNo =
2545 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002546 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2547 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2548 Prefix + utostr(OpNo)))
2549 return true;
2550 return false;
2551 }
2552
2553private:
Evan Cheng54597732006-01-26 00:22:25 +00002554 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002555 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002556 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2557 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002558 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002559 unsigned OpNo =
2560 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002561 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2562 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002563 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2564 TreePatternNode *Child = N->getChild(i);
2565 if (!Child->isLeaf()) {
Evan Cheng54597732006-01-26 00:22:25 +00002566 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002567 } else {
2568 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002569 if (!Child->getName().empty()) {
2570 std::string Name = RootName + utostr(OpNo);
2571 if (Duplicates.find(Name) != Duplicates.end())
2572 // A duplicate! Do not emit a copy for this node.
2573 continue;
2574 }
2575
Evan Chengb915f312005-12-09 22:45:35 +00002576 Record *RR = DI->getDef();
2577 if (RR->isSubClassOf("Register")) {
2578 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002579 if (RVT == MVT::Flag) {
Evan Cheng34167212006-02-09 00:37:58 +00002580 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
Evan Chengb2c6d492006-01-11 22:16:13 +00002581 } else {
2582 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002583 emitDecl("Chain");
2584 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002585 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002586 ChainEmitted = true;
2587 }
Evan Cheng34167212006-02-09 00:37:58 +00002588 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2589 RootName + utostr(OpNo) + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002590 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002591 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
Evan Cheng34167212006-02-09 00:37:58 +00002592 ", MVT::" + getEnumName(RVT) + "), " +
Evan Chengd7805a72006-02-09 07:16:09 +00002593 RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng67212a02006-02-09 22:12:27 +00002594 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2595 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00002596 }
2597 }
2598 }
2599 }
2600 }
Evan Cheng54597732006-01-26 00:22:25 +00002601
2602 if (HasInFlag || HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002603 std::string Code;
Evan Cheng54597732006-01-26 00:22:25 +00002604 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002605 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2606 ") {");
2607 Code = " ";
Evan Cheng54597732006-01-26 00:22:25 +00002608 }
Evan Cheng34167212006-02-09 00:37:58 +00002609 emitCode(Code + "Select(InFlag, " + RootName +
2610 ".getOperand(" + utostr(OpNo) + "));");
Evan Cheng54597732006-01-26 00:22:25 +00002611 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002612 emitCode(" HasOptInFlag = true;");
2613 emitCode("}");
Evan Cheng54597732006-01-26 00:22:25 +00002614 }
2615 }
Evan Chengb915f312005-12-09 22:45:35 +00002616 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002617
2618 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002619 /// as specified by the instruction. It returns true if any copy is
2620 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002621 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002622 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002623 Record *Op = N->getOperator();
2624 if (Op->isSubClassOf("Instruction")) {
2625 const DAGInstruction &Inst = ISE.getInstruction(Op);
2626 const CodeGenTarget &CGT = ISE.getTargetInfo();
2627 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2628 unsigned NumImpResults = Inst.getNumImpResults();
2629 for (unsigned i = 0; i < NumImpResults; i++) {
2630 Record *RR = Inst.getImpResult(i);
2631 if (RR->isSubClassOf("Register")) {
2632 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2633 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002634 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002635 emitDecl("Chain");
2636 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002637 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002638 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002639 }
Evan Chengd7805a72006-02-09 07:16:09 +00002640 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002641 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00002642 ", InFlag).Val;");
2643 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2644 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002645 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002646 }
2647 }
2648 }
2649 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002650 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002651 }
Evan Chengb915f312005-12-09 22:45:35 +00002652};
2653
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002654/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2655/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00002656/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00002657void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Chenge41bf822006-02-05 06:43:12 +00002658 std::vector<std::pair<bool, std::string> > &GeneratedCode,
Evan Chengd7805a72006-02-09 07:16:09 +00002659 std::set<std::pair<bool, std::string> > &GeneratedDecl,
Evan Chenge41bf822006-02-05 06:43:12 +00002660 bool DoReplace) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002661 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2662 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Cheng21ad3922006-02-07 00:37:41 +00002663 GeneratedCode, GeneratedDecl, DoReplace);
Evan Chengb915f312005-12-09 22:45:35 +00002664
Chris Lattner8fc35682005-09-23 23:16:51 +00002665 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002666 bool FoundChain = false;
Evan Chenge41bf822006-02-05 06:43:12 +00002667 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002668
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002669 // TP - Get *SOME* tree pattern, we don't care which.
2670 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002671
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002672 // At this point, we know that we structurally match the pattern, but the
2673 // types of the nodes may not match. Figure out the fewest number of type
2674 // comparisons we need to emit. For example, if there is only one integer
2675 // type supported by a target, there should be no type comparisons at all for
2676 // integer patterns!
2677 //
2678 // To figure out the fewest number of type checks needed, clone the pattern,
2679 // remove the types, then perform type inference on the pattern as a whole.
2680 // If there are unresolved types, emit an explicit check for those types,
2681 // apply the type to the tree, then rerun type inference. Iterate until all
2682 // types are resolved.
2683 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002684 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002685 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002686
2687 do {
2688 // Resolve/propagate as many types as possible.
2689 try {
2690 bool MadeChange = true;
2691 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00002692 MadeChange = Pat->ApplyTypeConstraints(TP,
2693 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00002694 } catch (...) {
2695 assert(0 && "Error: could not find consistent types for something we"
2696 " already decided was ok!");
2697 abort();
2698 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002699
Chris Lattner7e82f132005-10-15 21:34:21 +00002700 // Insert a check for an unresolved type and add it to the tree. If we find
2701 // an unresolved type to add a check for, this returns true and we iterate,
2702 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002703 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002704
Evan Cheng58e84a62005-12-14 22:02:59 +00002705 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002706 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00002707}
2708
Chris Lattner24e00a42006-01-29 04:41:05 +00002709/// EraseCodeLine - Erase one code line from all of the patterns. If removing
2710/// a line causes any of them to be empty, remove them and return true when
2711/// done.
2712static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2713 std::vector<std::pair<bool, std::string> > > >
2714 &Patterns) {
2715 bool ErasedPatterns = false;
2716 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2717 Patterns[i].second.pop_back();
2718 if (Patterns[i].second.empty()) {
2719 Patterns.erase(Patterns.begin()+i);
2720 --i; --e;
2721 ErasedPatterns = true;
2722 }
2723 }
2724 return ErasedPatterns;
2725}
2726
Chris Lattner8bc74722006-01-29 04:25:26 +00002727/// EmitPatterns - Emit code for at least one pattern, but try to group common
2728/// code together between the patterns.
2729void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
2730 std::vector<std::pair<bool, std::string> > > >
2731 &Patterns, unsigned Indent,
2732 std::ostream &OS) {
2733 typedef std::pair<bool, std::string> CodeLine;
2734 typedef std::vector<CodeLine> CodeList;
2735 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2736
2737 if (Patterns.empty()) return;
2738
Chris Lattner24e00a42006-01-29 04:41:05 +00002739 // Figure out how many patterns share the next code line. Explicitly copy
2740 // FirstCodeLine so that we don't invalidate a reference when changing
2741 // Patterns.
2742 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00002743 unsigned LastMatch = Patterns.size()-1;
2744 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2745 --LastMatch;
2746
2747 // If not all patterns share this line, split the list into two pieces. The
2748 // first chunk will use this line, the second chunk won't.
2749 if (LastMatch != 0) {
2750 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2751 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2752
2753 // FIXME: Emit braces?
2754 if (Shared.size() == 1) {
2755 PatternToMatch &Pattern = *Shared.back().first;
2756 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2757 Pattern.getSrcPattern()->print(OS);
2758 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2759 Pattern.getDstPattern()->print(OS);
2760 OS << "\n";
2761 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2762 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00002763 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00002764 }
2765 if (!FirstCodeLine.first) {
2766 OS << std::string(Indent, ' ') << "{\n";
2767 Indent += 2;
2768 }
2769 EmitPatterns(Shared, Indent, OS);
2770 if (!FirstCodeLine.first) {
2771 Indent -= 2;
2772 OS << std::string(Indent, ' ') << "}\n";
2773 }
2774
2775 if (Other.size() == 1) {
2776 PatternToMatch &Pattern = *Other.back().first;
2777 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2778 Pattern.getSrcPattern()->print(OS);
2779 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2780 Pattern.getDstPattern()->print(OS);
2781 OS << "\n";
2782 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2783 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00002784 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00002785 }
2786 EmitPatterns(Other, Indent, OS);
2787 return;
2788 }
2789
Chris Lattner24e00a42006-01-29 04:41:05 +00002790 // Remove this code from all of the patterns that share it.
2791 bool ErasedPatterns = EraseCodeLine(Patterns);
2792
Chris Lattner8bc74722006-01-29 04:25:26 +00002793 bool isPredicate = FirstCodeLine.first;
2794
2795 // Otherwise, every pattern in the list has this line. Emit it.
2796 if (!isPredicate) {
2797 // Normal code.
2798 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2799 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00002800 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2801
2802 // If the next code line is another predicate, and if all of the pattern
2803 // in this group share the same next line, emit it inline now. Do this
2804 // until we run out of common predicates.
2805 while (!ErasedPatterns && Patterns.back().second.back().first) {
2806 // Check that all of fhe patterns in Patterns end with the same predicate.
2807 bool AllEndWithSamePredicate = true;
2808 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2809 if (Patterns[i].second.back() != Patterns.back().second.back()) {
2810 AllEndWithSamePredicate = false;
2811 break;
2812 }
2813 // If all of the predicates aren't the same, we can't share them.
2814 if (!AllEndWithSamePredicate) break;
2815
2816 // Otherwise we can. Emit it shared now.
2817 OS << " &&\n" << std::string(Indent+4, ' ')
2818 << Patterns.back().second.back().second;
2819 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00002820 }
Chris Lattner24e00a42006-01-29 04:41:05 +00002821
2822 OS << ") {\n";
2823 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00002824 }
2825
2826 EmitPatterns(Patterns, Indent, OS);
2827
2828 if (isPredicate)
2829 OS << std::string(Indent-2, ' ') << "}\n";
2830}
2831
2832
Chris Lattner37481472005-09-26 21:59:35 +00002833
2834namespace {
2835 /// CompareByRecordName - An ordering predicate that implements less-than by
2836 /// comparing the names records.
2837 struct CompareByRecordName {
2838 bool operator()(const Record *LHS, const Record *RHS) const {
2839 // Sort by name first.
2840 if (LHS->getName() < RHS->getName()) return true;
2841 // If both names are equal, sort by pointer.
2842 return LHS->getName() == RHS->getName() && LHS < RHS;
2843 }
2844 };
2845}
2846
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002847void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002848 std::string InstNS = Target.inst_begin()->second.Namespace;
2849 if (!InstNS.empty()) InstNS += "::";
2850
Chris Lattner602f6922006-01-04 00:25:00 +00002851 // Group the patterns by their top-level opcodes.
2852 std::map<Record*, std::vector<PatternToMatch*>,
2853 CompareByRecordName> PatternsByOpcode;
2854 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2855 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2856 if (!Node->isLeaf()) {
2857 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2858 } else {
2859 const ComplexPattern *CP;
2860 if (IntInit *II =
2861 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2862 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2863 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2864 std::vector<Record*> OpNodes = CP->getRootNodes();
2865 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00002866 PatternsByOpcode[OpNodes[j]]
2867 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00002868 }
2869 } else {
2870 std::cerr << "Unrecognized opcode '";
2871 Node->dump();
2872 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00002873 std::cerr <<
2874 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00002875 std::cerr << "'!\n";
2876 exit(1);
2877 }
2878 }
2879 }
2880
2881 // Emit one Select_* method for each top-level opcode. We do this instead of
2882 // emitting one giant switch statement to support compilers where this will
2883 // result in the recursive functions taking less stack space.
2884 for (std::map<Record*, std::vector<PatternToMatch*>,
2885 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2886 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00002887 const std::string &OpName = PBOI->first->getName();
Evan Cheng34167212006-02-09 00:37:58 +00002888 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
Chris Lattner602f6922006-01-04 00:25:00 +00002889
2890 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Evan Chenge41bf822006-02-05 06:43:12 +00002891 bool OptSlctOrder =
2892 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
2893 OpcodeInfo.getNumResults() > 0);
2894
2895 if (OptSlctOrder) {
Evan Chenge41bf822006-02-05 06:43:12 +00002896 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
2897 << " && N.getValue(0).hasOneUse()) {\n"
2898 << " SDOperand Dummy = "
2899 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00002900 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2901 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
2902 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
2903 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00002904 << " Result = Dummy;\n"
2905 << " return;\n"
Evan Chenge41bf822006-02-05 06:43:12 +00002906 << " }\n";
2907 }
2908
Chris Lattner602f6922006-01-04 00:25:00 +00002909 std::vector<PatternToMatch*> &Patterns = PBOI->second;
Chris Lattner355408b2006-01-29 02:43:35 +00002910 assert(!Patterns.empty() && "No patterns but map has entry?");
Chris Lattner602f6922006-01-04 00:25:00 +00002911
2912 // We want to emit all of the matching code now. However, we want to emit
2913 // the matches in order of minimal cost. Sort the patterns so the least
2914 // cost one is at the start.
2915 std::stable_sort(Patterns.begin(), Patterns.end(),
2916 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00002917
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002918 typedef std::vector<std::pair<bool, std::string> > CodeList;
Evan Cheng21ad3922006-02-07 00:37:41 +00002919 typedef std::set<std::string> DeclSet;
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002920
2921 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
Evan Chengd7805a72006-02-09 07:16:09 +00002922 std::set<std::pair<bool, std::string> > GeneratedDecl;
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002923 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002924 CodeList GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002925 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
2926 OptSlctOrder);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002927 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
2928 }
2929
2930 // Scan the code to see if all of the patterns are reachable and if it is
2931 // possible that the last one might not match.
2932 bool mightNotMatch = true;
2933 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2934 CodeList &GeneratedCode = CodeForPatterns[i].second;
2935 mightNotMatch = false;
Chris Lattner355408b2006-01-29 02:43:35 +00002936
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002937 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
2938 if (GeneratedCode[j].first) { // predicate.
2939 mightNotMatch = true;
2940 break;
2941 }
2942 }
Chris Lattner355408b2006-01-29 02:43:35 +00002943
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002944 // If this pattern definitely matches, and if it isn't the last one, the
2945 // patterns after it CANNOT ever match. Error out.
2946 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
2947 std::cerr << "Pattern '";
2948 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
2949 std::cerr << "' is impossible to select!\n";
2950 exit(1);
2951 }
2952 }
Evan Cheng21ad3922006-02-07 00:37:41 +00002953
2954 // Print all declarations.
Evan Chengd7805a72006-02-09 07:16:09 +00002955 for (std::set<std::pair<bool, std::string> >::iterator I = GeneratedDecl.begin(),
Evan Cheng21ad3922006-02-07 00:37:41 +00002956 E = GeneratedDecl.end(); I != E; ++I)
Evan Chengd7805a72006-02-09 07:16:09 +00002957 if (I->first)
2958 OS << " SDNode *" << I->second << ";\n";
2959 else
2960 OS << " SDOperand " << I->second << "(0, 0);\n";
Evan Cheng21ad3922006-02-07 00:37:41 +00002961
Chris Lattner8bc74722006-01-29 04:25:26 +00002962 // Loop through and reverse all of the CodeList vectors, as we will be
2963 // accessing them from their logical front, but accessing the end of a
2964 // vector is more efficient.
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002965 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2966 CodeList &GeneratedCode = CodeForPatterns[i].second;
Chris Lattner8bc74722006-01-29 04:25:26 +00002967 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002968 }
Chris Lattner602f6922006-01-04 00:25:00 +00002969
Chris Lattner8bc74722006-01-29 04:25:26 +00002970 // Next, reverse the list of patterns itself for the same reason.
2971 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
2972
2973 // Emit all of the patterns now, grouped together to share code.
2974 EmitPatterns(CodeForPatterns, 2, OS);
2975
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002976 // If the last pattern has predicates (which could fail) emit code to catch
2977 // the case where nothing handles a pattern.
Chris Lattner355408b2006-01-29 02:43:35 +00002978 if (mightNotMatch)
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002979 OS << " std::cerr << \"Cannot yet select: \";\n"
2980 << " N.Val->dump(CurDAG);\n"
2981 << " std::cerr << '\\n';\n"
2982 << " abort();\n";
2983
2984 OS << "}\n\n";
Chris Lattner602f6922006-01-04 00:25:00 +00002985 }
2986
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002987 // Emit boilerplate.
Evan Cheng34167212006-02-09 00:37:58 +00002988 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00002989 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng34167212006-02-09 00:37:58 +00002990 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00002991 << " // Select the flag operand.\n"
2992 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng34167212006-02-09 00:37:58 +00002993 << " Select(Ops.back(), Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00002994 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00002995 << " std::vector<MVT::ValueType> VTs;\n"
2996 << " VTs.push_back(MVT::Other);\n"
2997 << " VTs.push_back(MVT::Flag);\n"
2998 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00002999 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3000 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003001 << " Result = New.getValue(N.ResNo);\n"
3002 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003003 << "}\n\n";
3004
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003005 OS << "// The main instruction selector code.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003006 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003007 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003008 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003009 << "INSTRUCTION_LIST_END)) {\n"
3010 << " Result = N;\n"
3011 << " return; // Already selected.\n"
3012 << " }\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003013 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003014 << " if (CGMI != CodeGenMap.end()) {\n"
3015 << " Result = CGMI->second;\n"
3016 << " return;\n"
3017 << " }\n\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003018 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003019 << " default: break;\n"
3020 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003021 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003022 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003023 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003024 << " case ISD::TargetConstant:\n"
3025 << " case ISD::TargetConstantPool:\n"
3026 << " case ISD::TargetFrameIndex:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003027 << " case ISD::TargetGlobalAddress: {\n"
3028 << " Result = N;\n"
3029 << " return;\n"
3030 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003031 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003032 << " case ISD::AssertZext: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003033 << " SDOperand Tmp0;\n"
3034 << " Select(Tmp0, N.getOperand(0));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003035 << " if (!N.Val->hasOneUse())\n"
3036 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3037 << "Tmp0.Val, Tmp0.ResNo);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003038 << " Result = Tmp0;\n"
3039 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003040 << " }\n"
3041 << " case ISD::TokenFactor:\n"
3042 << " if (N.getNumOperands() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003043 << " SDOperand Op0, Op1;\n"
3044 << " Select(Op0, N.getOperand(0));\n"
3045 << " Select(Op1, N.getOperand(1));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003046 << " Result = \n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003047 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003048 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3049 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003050 << " } else {\n"
3051 << " std::vector<SDOperand> Ops;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003052 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3053 << " SDOperand Val;\n"
3054 << " Select(Val, N.getOperand(i));\n"
3055 << " Ops.push_back(Val);\n"
3056 << " }\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003057 << " Result = \n"
3058 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3059 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3060 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003061 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003062 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003063 << " case ISD::CopyFromReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003064 << " SDOperand Chain;\n"
3065 << " Select(Chain, N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003066 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3067 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003068 << " if (N.Val->getNumValues() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003069 << " if (Chain == N.getOperand(0)) {\n"
3070 << " Result = N; // No change\n"
3071 << " return;\n"
3072 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003073 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003074 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3075 << "New.Val, 0);\n"
3076 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3077 << "New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003078 << " Result = New.getValue(N.ResNo);\n"
3079 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003080 << " } else {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003081 << " SDOperand Flag;\n"
3082 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003083 << " if (Chain == N.getOperand(0) &&\n"
Evan Cheng34167212006-02-09 00:37:58 +00003084 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3085 << " Result = N; // No change\n"
3086 << " return;\n"
3087 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003088 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003089 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3090 << "New.Val, 0);\n"
3091 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3092 << "New.Val, 1);\n"
3093 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3094 << "New.Val, 2);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003095 << " Result = New.getValue(N.ResNo);\n"
3096 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003097 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003098 << " }\n"
3099 << " case ISD::CopyToReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003100 << " SDOperand Chain;\n"
3101 << " Select(Chain, N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003102 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Evan Cheng34167212006-02-09 00:37:58 +00003103 << " SDOperand Val;\n"
3104 << " Select(Val, N.getOperand(2));\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003105 << " Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003106 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003107 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003108 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003109 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3110 << "Result.Val, 0);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003111 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003112 << " SDOperand Flag(0, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003113 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003114 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003115 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003116 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003117 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3118 << "Result.Val, 0);\n"
3119 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3120 << "Result.Val, 1);\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003121 << " Result = Result.getValue(N.ResNo);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003122 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003123 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003124 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003125 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003126
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003127
Chris Lattner602f6922006-01-04 00:25:00 +00003128 // Loop over all of the case statements, emiting a call to each method we
3129 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003130 for (std::map<Record*, std::vector<PatternToMatch*>,
3131 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3132 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003133 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00003134 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00003135 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Evan Cheng34167212006-02-09 00:37:58 +00003136 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
Chris Lattner81303322005-09-23 19:36:15 +00003137 }
Chris Lattner81303322005-09-23 19:36:15 +00003138
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003139 OS << " } // end of big switch.\n\n"
3140 << " std::cerr << \"Cannot yet select: \";\n"
Evan Cheng97938882005-12-22 02:24:50 +00003141 << " N.Val->dump(CurDAG);\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003142 << " std::cerr << '\\n';\n"
3143 << " abort();\n"
3144 << "}\n";
3145}
3146
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003147void DAGISelEmitter::run(std::ostream &OS) {
3148 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3149 " target", OS);
3150
Chris Lattner1f39e292005-09-14 00:09:24 +00003151 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3152 << "// *** instruction selector class. These functions are really "
3153 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003154
Chris Lattner296dfe32005-09-24 00:50:51 +00003155 OS << "// Instance var to keep track of multiply used nodes that have \n"
3156 << "// already been selected.\n"
3157 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003158
3159 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003160 << "// and their place handle nodes.\n";
3161 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3162 OS << "// Instance var to keep track of mapping of place handle nodes\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003163 << "// and their replacement nodes.\n";
3164 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3165
3166 OS << "\n";
3167 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3168 << "std::set<SDNode *> &Visited) {\n";
3169 OS << " if (found || !Visited.insert(Use).second) return;\n";
3170 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3171 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3172 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3173 OS << " if (N != Def) {\n";
3174 OS << " findNonImmUse(N, Def, found, Visited);\n";
3175 OS << " } else {\n";
3176 OS << " found = true;\n";
3177 OS << " break;\n";
3178 OS << " }\n";
3179 OS << " }\n";
3180 OS << " }\n";
3181 OS << "}\n";
3182
3183 OS << "\n";
3184 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3185 OS << " std::set<SDNode *> Visited;\n";
3186 OS << " bool found = false;\n";
3187 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3188 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3189 OS << " if (N != Def) {\n";
3190 OS << " findNonImmUse(N, Def, found, Visited);\n";
3191 OS << " if (found) break;\n";
3192 OS << " }\n";
3193 OS << " }\n";
3194 OS << " return found;\n";
3195 OS << "}\n";
3196
3197 OS << "\n";
Evan Cheng024524f2006-02-06 06:03:35 +00003198 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003199 << "// handle node in ReplaceMap.\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003200 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3201 << "unsigned RNum) {\n";
3202 OS << " SDOperand N(H, HNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003203 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3204 OS << " if (HMI != HandleMap.end()) {\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003205 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003206 OS << " HandleMap.erase(N);\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003207 OS << " }\n";
3208 OS << "}\n";
3209
3210 OS << "\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003211 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3212 OS << "// handles.Some handles do not yet have replacements because the\n";
3213 OS << "// nodes they replacements have only dead readers.\n";
3214 OS << "void SelectDanglingHandles() {\n";
3215 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3216 << "HandleMap.begin(),\n"
3217 << " E = HandleMap.end(); I != E; ++I) {\n";
3218 OS << " SDOperand N = I->first;\n";
Evan Cheng34167212006-02-09 00:37:58 +00003219 OS << " SDOperand R;\n";
3220 OS << " Select(R, N.getValue(0));\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003221 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003222 OS << " }\n";
3223 OS << "}\n";
3224 OS << "\n";
3225 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003226 OS << "// specific nodes.\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003227 OS << "void ReplaceHandles() {\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003228 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3229 << "ReplaceMap.begin(),\n"
3230 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3231 OS << " SDOperand From = I->first;\n";
3232 OS << " SDOperand To = I->second;\n";
3233 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3234 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3235 OS << " SDNode *Use = *UI;\n";
3236 OS << " std::vector<SDOperand> Ops;\n";
3237 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3238 OS << " SDOperand O = Use->getOperand(i);\n";
3239 OS << " if (O.Val == From.Val)\n";
3240 OS << " Ops.push_back(To);\n";
3241 OS << " else\n";
3242 OS << " Ops.push_back(O);\n";
3243 OS << " }\n";
3244 OS << " SDOperand U = SDOperand(Use, 0);\n";
3245 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3246 OS << " }\n";
3247 OS << " }\n";
3248 OS << "}\n";
3249
3250 OS << "\n";
3251 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3252 OS << "SDOperand SelectRoot(SDOperand N) {\n";
Evan Cheng34167212006-02-09 00:37:58 +00003253 OS << " SDOperand ResNode;\n";
3254 OS << " Select(ResNode, N);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003255 OS << " SelectDanglingHandles();\n";
3256 OS << " ReplaceHandles();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003257 OS << " ReplaceMap.clear();\n";
Evan Cheng34167212006-02-09 00:37:58 +00003258 OS << " return ResNode;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003259 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003260
Chris Lattnerca559d02005-09-08 21:03:01 +00003261 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003262 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003263 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003264 ParsePatternFragments(OS);
3265 ParseInstructions();
3266 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003267
Chris Lattnere97603f2005-09-28 19:27:25 +00003268 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003269 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003270 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003271
Chris Lattnere46e17b2005-09-29 19:28:10 +00003272
3273 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3274 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003275 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3276 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003277 std::cerr << "\n";
3278 });
3279
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003280 // At this point, we have full information about the 'Patterns' we need to
3281 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003282 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003283 EmitInstructionSelector(OS);
3284
3285 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3286 E = PatternFragments.end(); I != E; ++I)
3287 delete I->second;
3288 PatternFragments.clear();
3289
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003290 Instructions.clear();
3291}