blob: 8b19d04b3d34e0d323827869b6da908718c9421a [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.
1752static unsigned getResultPatternCost(TreePatternNode *P) {
1753 if (P->isLeaf()) return 0;
1754
1755 unsigned Cost = P->getOperator()->isSubClassOf("Instruction");
1756 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1757 Cost += getResultPatternCost(P->getChild(i));
1758 return Cost;
1759}
1760
1761// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1762// In particular, we want to match maximal patterns first and lowest cost within
1763// a particular complexity first.
1764struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001765 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1766 DAGISelEmitter &ISE;
1767
Evan Cheng58e84a62005-12-14 22:02:59 +00001768 bool operator()(PatternToMatch *LHS,
1769 PatternToMatch *RHS) {
1770 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1771 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001772 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1773 if (LHSSize < RHSSize) return false;
1774
1775 // If the patterns have equal complexity, compare generated instruction cost
Evan Cheng58e84a62005-12-14 22:02:59 +00001776 return getResultPatternCost(LHS->getDstPattern()) <
1777 getResultPatternCost(RHS->getDstPattern());
Chris Lattner05814af2005-09-28 17:57:56 +00001778 }
1779};
1780
Nate Begeman6510b222005-12-01 04:51:06 +00001781/// getRegisterValueType - Look up and return the first ValueType of specified
1782/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001783static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001784 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1785 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001786 return MVT::Other;
1787}
1788
Chris Lattner72fe91c2005-09-24 00:40:24 +00001789
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001790/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1791/// type information from it.
1792static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001793 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001794 if (!N->isLeaf())
1795 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1796 RemoveAllTypes(N->getChild(i));
1797}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001798
Chris Lattner0614b622005-11-02 06:49:14 +00001799Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1800 Record *N = Records.getDef(Name);
1801 assert(N && N->isSubClassOf("SDNode") && "Bad argument");
1802 return N;
1803}
1804
Evan Cheng51fecc82006-01-09 18:27:06 +00001805/// NodeHasProperty - return true if TreePatternNode has the specified
1806/// property.
1807static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1808 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001809{
1810 if (N->isLeaf()) return false;
1811 Record *Operator = N->getOperator();
1812 if (!Operator->isSubClassOf("SDNode")) return false;
1813
1814 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00001815 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00001816}
1817
Evan Cheng51fecc82006-01-09 18:27:06 +00001818static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1819 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001820{
Evan Cheng51fecc82006-01-09 18:27:06 +00001821 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00001822 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00001823
1824 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1825 TreePatternNode *Child = N->getChild(i);
1826 if (PatternHasProperty(Child, Property, ISE))
1827 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001828 }
1829
1830 return false;
1831}
1832
Evan Chengb915f312005-12-09 22:45:35 +00001833class PatternCodeEmitter {
1834private:
1835 DAGISelEmitter &ISE;
1836
Evan Cheng58e84a62005-12-14 22:02:59 +00001837 // Predicates.
1838 ListInit *Predicates;
1839 // Instruction selector pattern.
1840 TreePatternNode *Pattern;
1841 // Matched instruction.
1842 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001843
Evan Chengb915f312005-12-09 22:45:35 +00001844 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00001845 std::map<std::string, std::string> VariableMap;
1846 // Node to operator mapping
1847 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00001848 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001849 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00001850 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +00001851
Chris Lattner8a0604b2006-01-28 20:31:24 +00001852 /// GeneratedCode - This is the buffer that we emit code to. The first bool
1853 /// indicates whether this is an exit predicate (something that should be
1854 /// tested, and if true, the match fails) [when true] or normal code to emit
1855 /// [when false].
1856 std::vector<std::pair<bool, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00001857 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
1858 /// the set of patterns for each top-level opcode.
1859 std::set<std::string> &GeneratedDecl;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001860
Evan Chenge4a8a6e2006-02-03 06:22:41 +00001861 std::string ChainName;
Evan Chenge41bf822006-02-05 06:43:12 +00001862 bool DoReplace;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001863 unsigned TmpNo;
1864
1865 void emitCheck(const std::string &S) {
1866 if (!S.empty())
1867 GeneratedCode.push_back(std::make_pair(true, S));
1868 }
1869 void emitCode(const std::string &S) {
1870 if (!S.empty())
1871 GeneratedCode.push_back(std::make_pair(false, S));
1872 }
Evan Cheng21ad3922006-02-07 00:37:41 +00001873 void emitDecl(const std::string &S) {
1874 assert(!S.empty() && "Invalid declaration");
1875 GeneratedDecl.insert(S);
1876 }
Evan Chengb915f312005-12-09 22:45:35 +00001877public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001878 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1879 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng21ad3922006-02-07 00:37:41 +00001880 std::vector<std::pair<bool, std::string> > &gc,
1881 std::set<std::string> &gd,
1882 bool dorep)
Chris Lattner8a0604b2006-01-28 20:31:24 +00001883 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng21ad3922006-02-07 00:37:41 +00001884 GeneratedCode(gc), GeneratedDecl(gd), DoReplace(dorep), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00001885
1886 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1887 /// if the match fails. At this point, we already know that the opcode for N
1888 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00001889 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
1890 const std::string &RootName, const std::string &ParentName,
1891 const std::string &ChainSuffix, bool &FoundChain) {
1892 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00001893 // Emit instruction predicates. Each predicate is just a string for now.
1894 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001895 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00001896 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1897 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1898 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00001899 if (!Def->isSubClassOf("Predicate")) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001900 Def->dump();
1901 assert(0 && "Unknown predicate type!");
1902 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00001903 if (!PredicateCheck.empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00001904 PredicateCheck += " || ";
1905 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00001906 }
1907 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00001908
1909 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00001910 }
1911
Evan Chengb915f312005-12-09 22:45:35 +00001912 if (N->isLeaf()) {
1913 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001914 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00001915 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00001916 return;
1917 } else if (!NodeIsComplexPattern(N)) {
1918 assert(0 && "Cannot match this as a leaf value!");
1919 abort();
1920 }
1921 }
1922
Chris Lattner488580c2006-01-28 19:06:51 +00001923 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00001924 // we already saw this in the pattern, emit code to verify dagness.
1925 if (!N->getName().empty()) {
1926 std::string &VarMapEntry = VariableMap[N->getName()];
1927 if (VarMapEntry.empty()) {
1928 VarMapEntry = RootName;
1929 } else {
1930 // If we get here, this is a second reference to a specific name. Since
1931 // we already have checked that the first reference is valid, we don't
1932 // have to recursively match it, just check that it's the same as the
1933 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00001934 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00001935 return;
1936 }
Evan Chengf805c2e2006-01-12 19:35:54 +00001937
1938 if (!N->isLeaf())
1939 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00001940 }
1941
1942
1943 // Emit code to load the child nodes and match their contents recursively.
1944 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00001945 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
1946 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
1947 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00001948 bool EmittedUseCheck = false;
1949 bool EmittedSlctedCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00001950 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00001951 if (NodeHasChain)
1952 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00001953 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001954 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattner8a0604b2006-01-28 20:31:24 +00001955 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00001956 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00001957 EmittedUseCheck = true;
1958 // hasOneUse() check is not strong enough. If the original node has
1959 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00001960 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00001961 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00001962 "))");
1963
Evan Cheng1feeeec2006-01-26 19:13:45 +00001964 EmittedSlctedCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00001965 if (NodeHasChain) {
1966 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
1967 // has a chain use.
1968 // This a workaround for this problem:
1969 //
1970 // [ch, r : ld]
1971 // ^ ^
1972 // | |
1973 // [XX]--/ \- [flag : cmp]
1974 // ^ ^
1975 // | |
1976 // \---[br flag]-
1977 //
1978 // cmp + br should be considered as a single node as they are flagged
1979 // together. So, if the ld is folded into the cmp, the XX node in the
1980 // graph is now both an operand and a use of the ld/cmp/br node.
1981 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
1982 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
1983
1984 // If the immediate use can somehow reach this node through another
1985 // path, then can't fold it either or it will create a cycle.
1986 // e.g. In the following diagram, XX can reach ld through YY. If
1987 // ld is folded into XX, then YY is both a predecessor and a successor
1988 // of XX.
1989 //
1990 // [ld]
1991 // ^ ^
1992 // | |
1993 // / \---
1994 // / [YY]
1995 // | ^
1996 // [XX]-------|
1997 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
1998 if (PInfo.getNumOperands() > 1 ||
1999 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2000 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2001 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2002 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2003 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2004 ".Val))");
2005 }
Evan Chengb915f312005-12-09 22:45:35 +00002006 }
Evan Chenge41bf822006-02-05 06:43:12 +00002007
Evan Chengc15d18c2006-01-27 22:13:45 +00002008 if (NodeHasChain) {
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002009 if (FoundChain)
Chris Lattner67a202b2006-01-28 20:43:52 +00002010 emitCheck("Chain.Val == " + RootName + ".Val");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002011 else
2012 FoundChain = true;
2013 ChainName = "Chain" + ChainSuffix;
Evan Cheng21ad3922006-02-07 00:37:41 +00002014 emitDecl(ChainName);
2015 emitCode(ChainName + " = " + RootName +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002016 ".getOperand(0);");
Evan Cheng1cf6db22006-01-06 00:41:12 +00002017 }
Evan Chengb915f312005-12-09 22:45:35 +00002018 }
2019
Evan Cheng54597732006-01-26 00:22:25 +00002020 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002021 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002022 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002023 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2024 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002025 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002026 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2027 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2028 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002029 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2030 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002031 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002032 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002033 }
Evan Cheng1feeeec2006-01-26 19:13:45 +00002034 if (!EmittedSlctedCheck)
2035 // hasOneUse() check is not strong enough. If the original node has
2036 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002037 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002038 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002039 "))");
Evan Cheng54597732006-01-26 00:22:25 +00002040 }
2041
Evan Chengb915f312005-12-09 22:45:35 +00002042 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002043 emitDecl(RootName + utostr(OpNo));
2044 emitCode(RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002045 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002046 TreePatternNode *Child = N->getChild(i);
2047
2048 if (!Child->isLeaf()) {
2049 // If it's not a leaf, recursively match.
2050 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002051 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002052 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002053 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2054 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002055 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002056 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2057 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002058 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002059 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002060 // we already saw this in the pattern, emit code to verify dagness.
2061 if (!Child->getName().empty()) {
2062 std::string &VarMapEntry = VariableMap[Child->getName()];
2063 if (VarMapEntry.empty()) {
2064 VarMapEntry = RootName + utostr(OpNo);
2065 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002066 // If we get here, this is a second reference to a specific name.
2067 // Since we already have checked that the first reference is valid,
2068 // we don't have to recursively match it, just check that it's the
2069 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002070 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002071 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002072 continue;
2073 }
2074 }
2075
2076 // Handle leaves of various types.
2077 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2078 Record *LeafRec = DI->getDef();
2079 if (LeafRec->isSubClassOf("RegisterClass")) {
2080 // Handle register references. Nothing to do here.
2081 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002082 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002083 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2084 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00002085 } else if (LeafRec->getName() == "srcvalue") {
2086 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002087 } else if (LeafRec->isSubClassOf("ValueType")) {
2088 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002089 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002090 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002091 } else if (LeafRec->isSubClassOf("CondCode")) {
2092 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002093 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002094 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002095 } else {
2096 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002097 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00002098 assert(0 && "Unknown leaf type!");
2099 }
Chris Lattner488580c2006-01-28 19:06:51 +00002100 } else if (IntInit *II =
2101 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002102 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2103 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002104 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002105 RootName + utostr(OpNo) + ")->getSignExtended();");
2106
2107 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002108 } else {
2109 Child->dump();
2110 assert(0 && "Unknown leaf type!");
2111 }
2112 }
2113 }
2114
2115 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002116 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002117 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002118 }
2119
2120 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2121 /// we actually have to build a DAG!
2122 std::pair<unsigned, unsigned>
2123 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
2124 // This is something selected from the pattern we matched.
2125 if (!N->getName().empty()) {
2126 assert(!isRoot && "Root of pattern cannot be a leaf!");
2127 std::string &Val = VariableMap[N->getName()];
2128 assert(!Val.empty() &&
2129 "Variable referenced but not defined and not caught earlier!");
2130 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2131 // Already selected this operand, just return the tmpval.
2132 return std::make_pair(1, atoi(Val.c_str()+3));
2133 }
2134
2135 const ComplexPattern *CP;
2136 unsigned ResNo = TmpNo++;
2137 unsigned NumRes = 1;
2138 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002139 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002140 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002141 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002142 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002143 case MVT::i1: CastType = "bool"; break;
2144 case MVT::i8: CastType = "unsigned char"; break;
2145 case MVT::i16: CastType = "unsigned short"; break;
2146 case MVT::i32: CastType = "unsigned"; break;
2147 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002148 }
Chris Lattner78593132006-01-29 20:01:35 +00002149 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
Andrew Lenharth2cba57c2006-01-29 05:17:22 +00002150 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
Evan Cheng21ad3922006-02-07 00:37:41 +00002151 emitDecl("Tmp" + utostr(ResNo));
2152 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002153 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2154 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengbb48e332006-01-12 07:54:57 +00002155 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002156 Record *Op = OperatorMap[N->getName()];
2157 // Transform ExternalSymbol to TargetExternalSymbol
2158 if (Op && Op->getName() == "externalsym") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002159 emitDecl("Tmp" + utostr(ResNo));
2160 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002161 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2162 Val + ")->getSymbol(), MVT::" +
2163 getEnumName(N->getTypeNum(0)) + ");");
2164 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002165 emitDecl("Tmp" + utostr(ResNo));
2166 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002167 }
Evan Chengb915f312005-12-09 22:45:35 +00002168 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002169 Record *Op = OperatorMap[N->getName()];
2170 // Transform GlobalAddress to TargetGlobalAddress
2171 if (Op && Op->getName() == "globaladdr") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002172 emitDecl("Tmp" + utostr(ResNo));
2173 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002174 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2175 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2176 ");");
2177 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002178 emitDecl("Tmp" + utostr(ResNo));
2179 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002180 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002181 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng21ad3922006-02-07 00:37:41 +00002182 emitDecl("Tmp" + utostr(ResNo));
2183 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengbb48e332006-01-12 07:54:57 +00002184 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002185 emitDecl("Tmp" + utostr(ResNo));
2186 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002187 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2188 std::string Fn = CP->getSelectFunc();
2189 NumRes = CP->getNumOperands();
Evan Cheng21ad3922006-02-07 00:37:41 +00002190 for (unsigned i = 0; i < NumRes; ++i)
2191 emitDecl("Tmp" + utostr(i+ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002192
Evan Cheng21ad3922006-02-07 00:37:41 +00002193 std::string Code = Fn + "(" + Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002194 for (unsigned i = 0; i < NumRes; i++)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002195 Code += ", Tmp" + utostr(i + ResNo);
2196 emitCheck(Code + ")");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002197
Evan Cheng2216d8a2006-02-05 05:22:18 +00002198 for (unsigned i = 0; i < NumRes; ++i)
2199 emitCode("Tmp" + utostr(i+ResNo) + " = Select(Tmp" +
2200 utostr(i+ResNo) + ");");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002201
Evan Chengb915f312005-12-09 22:45:35 +00002202 TmpNo = ResNo + NumRes;
2203 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002204 emitDecl("Tmp" + utostr(ResNo));
2205 emitCode("Tmp" + utostr(ResNo) + " = Select(" + Val + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002206 }
2207 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2208 // value if used multiple times by this pattern result.
2209 Val = "Tmp"+utostr(ResNo);
2210 return std::make_pair(NumRes, ResNo);
2211 }
2212
2213 if (N->isLeaf()) {
2214 // If this is an explicit register reference, handle it.
2215 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2216 unsigned ResNo = TmpNo++;
2217 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002218 emitDecl("Tmp" + utostr(ResNo));
2219 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002220 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2221 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002222 return std::make_pair(1, ResNo);
2223 }
2224 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2225 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002226 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng21ad3922006-02-07 00:37:41 +00002227 emitDecl("Tmp" + utostr(ResNo));
2228 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002229 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2230 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002231 return std::make_pair(1, ResNo);
2232 }
2233
2234 N->dump();
2235 assert(0 && "Unknown leaf type!");
2236 return std::make_pair(1, ~0U);
2237 }
2238
2239 Record *Op = N->getOperator();
2240 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002241 const CodeGenTarget &CGT = ISE.getTargetInfo();
2242 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002243 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002244 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2245 bool HasImpResults = Inst.getNumImpResults() > 0;
Evan Cheng54597732006-01-26 00:22:25 +00002246 bool HasOptInFlag = isRoot &&
2247 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002248 bool HasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002249 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2250 bool NodeHasOutFlag = HasImpResults ||
Evan Cheng51fecc82006-01-09 18:27:06 +00002251 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
Evan Cheng823b7522006-01-19 21:57:10 +00002252 bool NodeHasChain =
2253 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002254 bool HasChain = II.hasCtrlDep ||
2255 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
Evan Cheng4fba2812005-12-20 07:37:41 +00002256
Evan Cheng54597732006-01-26 00:22:25 +00002257 if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
Evan Cheng21ad3922006-02-07 00:37:41 +00002258 emitDecl("InFlag");
Evan Cheng54597732006-01-26 00:22:25 +00002259 if (HasOptInFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002260 emitCode("bool HasOptInFlag = false;");
Evan Cheng4fba2812005-12-20 07:37:41 +00002261
Evan Cheng823b7522006-01-19 21:57:10 +00002262 // How many results is this pattern expected to produce?
2263 unsigned NumExpectedResults = 0;
2264 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2265 MVT::ValueType VT = Pattern->getTypeNum(i);
2266 if (VT != MVT::isVoid && VT != MVT::Flag)
2267 NumExpectedResults++;
2268 }
2269
Evan Chengb915f312005-12-09 22:45:35 +00002270 // Determine operand emission order. Complex pattern first.
2271 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2272 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2273 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2274 TreePatternNode *Child = N->getChild(i);
2275 if (i == 0) {
2276 EmitOrder.push_back(std::make_pair(i, Child));
2277 OI = EmitOrder.begin();
2278 } else if (NodeIsComplexPattern(Child)) {
2279 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2280 } else {
2281 EmitOrder.push_back(std::make_pair(i, Child));
2282 }
2283 }
2284
2285 // Emit all of the operands.
2286 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2287 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2288 unsigned OpOrder = EmitOrder[i].first;
2289 TreePatternNode *Child = EmitOrder[i].second;
2290 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2291 NumTemps[OpOrder] = NumTemp;
2292 }
2293
2294 // List all the operands in the right order.
2295 std::vector<unsigned> Ops;
2296 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2297 for (unsigned j = 0; j < NumTemps[i].first; j++)
2298 Ops.push_back(NumTemps[i].second + j);
2299 }
2300
Evan Chengb915f312005-12-09 22:45:35 +00002301 // Emit all the chain and CopyToReg stuff.
Evan Chengb2c6d492006-01-11 22:16:13 +00002302 bool ChainEmitted = HasChain;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002303 if (HasChain)
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002304 emitCode(ChainName + " = Select(" + ChainName + ");");
Evan Cheng54597732006-01-26 00:22:25 +00002305 if (HasInFlag || HasOptInFlag || HasImpInputs)
2306 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
Evan Chengb915f312005-12-09 22:45:35 +00002307
Evan Chengb915f312005-12-09 22:45:35 +00002308 unsigned NumResults = Inst.getNumResults();
2309 unsigned ResNo = TmpNo++;
2310 if (!isRoot) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002311 emitDecl("Tmp" + utostr(ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002312 std::string Code =
Evan Cheng21ad3922006-02-07 00:37:41 +00002313 "Tmp" + utostr(ResNo) + " = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002314 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002315 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002316 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002317 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002318 Code += ", MVT::Flag";
Evan Chengbcecf332005-12-17 01:19:28 +00002319
Evan Chengb915f312005-12-09 22:45:35 +00002320 unsigned LastOp = 0;
2321 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2322 LastOp = Ops[i];
Chris Lattner8a0604b2006-01-28 20:31:24 +00002323 Code += ", Tmp" + utostr(LastOp);
Evan Chengb915f312005-12-09 22:45:35 +00002324 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002325 emitCode(Code + ");");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002326 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002327 // Must have at least one result
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002328 emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002329 utostr(NumResults) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002330 }
Evan Cheng54597732006-01-26 00:22:25 +00002331 } else if (HasChain || NodeHasOutFlag) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002332 emitDecl("Result");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002333 if (HasOptInFlag) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002334 emitCode("Result = SDOperand(0, 0);");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002335 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002336 emitCode("if (HasOptInFlag)");
2337 std::string Code = " Result = CurDAG->getTargetNode(" +
2338 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002339
Evan Cheng9789aaa2006-01-24 20:46:50 +00002340 // Output order: results, chain, flags
2341 // Result types.
2342 if (NumResults > 0) {
2343 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002344 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002345 }
2346 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002347 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002348 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002349 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002350
2351 // Inputs.
2352 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002353 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002354 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002355 emitCode(Code + ", InFlag);");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002356
Chris Lattner8a0604b2006-01-28 20:31:24 +00002357 emitCode("else");
2358 Code = " Result = CurDAG->getTargetNode(" + II.Namespace + "::" +
2359 II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002360
2361 // Output order: results, chain, flags
2362 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002363 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2364 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002365 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002366 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002367 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002368 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002369
2370 // Inputs.
2371 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002372 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002373 if (HasChain) Code += ", " + ChainName + ");";
Chris Lattner8a0604b2006-01-28 20:31:24 +00002374 emitCode(Code);
Evan Cheng9789aaa2006-01-24 20:46:50 +00002375 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002376 std::string Code = "Result = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002377 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002378
2379 // Output order: results, chain, flags
2380 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002381 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2382 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002383 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002384 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002385 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002386 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002387
2388 // Inputs.
2389 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002390 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002391 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002392 if (HasInFlag || HasImpInputs) Code += ", InFlag";
2393 emitCode(Code + ");");
Evan Chengbcecf332005-12-17 01:19:28 +00002394 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002395
2396 unsigned ValNo = 0;
Evan Chengf9fc25d2005-12-19 22:40:04 +00002397 for (unsigned i = 0; i < NumResults; i++) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002398 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = Result"
2399 ".getValue(" + utostr(ValNo) + ");");
Evan Chengf9fc25d2005-12-19 22:40:04 +00002400 ValNo++;
2401 }
2402
Evan Cheng7b05bd52005-12-23 22:11:47 +00002403 if (HasChain)
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002404 emitCode(ChainName + " = Result.getValue(" + utostr(ValNo) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002405
Evan Cheng54597732006-01-26 00:22:25 +00002406 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002407 emitCode("InFlag = Result.getValue(" +
2408 utostr(ValNo + (unsigned)HasChain) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002409
Chris Lattner8a0604b2006-01-28 20:31:24 +00002410 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2411 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = "
2412 "Result.getValue(" + utostr(ValNo) + ");");
2413 ValNo++;
Evan Cheng97938882005-12-22 02:24:50 +00002414 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002415
Evan Cheng7b05bd52005-12-23 22:11:47 +00002416 // User does not expect that the instruction produces a chain!
Evan Cheng51fecc82006-01-09 18:27:06 +00002417 bool AddedChain = HasChain && !NodeHasChain;
Evan Chenge41bf822006-02-05 06:43:12 +00002418 if (NodeHasChain) {
2419 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = " +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002420 ChainName + ";");
Evan Chenge41bf822006-02-05 06:43:12 +00002421 if (DoReplace)
Evan Cheng024524f2006-02-06 06:03:35 +00002422 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.getValue("
Evan Chenge41bf822006-02-05 06:43:12 +00002423 + utostr(ValNo) + "), " + ChainName + ");");
2424 ValNo++;
2425 }
2426
Evan Cheng97938882005-12-22 02:24:50 +00002427
2428 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002429 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002430 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002431 Code += "CodeGenMap[" + FoldedChains[j].first + ".getValue(" +
2432 utostr(FoldedChains[j].second) + ")] = ";
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002433 emitCode(Code + ChainName + ";");
Evan Chenge41bf822006-02-05 06:43:12 +00002434
2435 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2436 std::string Code =
2437 FoldedChains[j].first + ".getValue(" +
2438 utostr(FoldedChains[j].second) + ")";
Evan Cheng024524f2006-02-06 06:03:35 +00002439 emitCode("AddHandleReplacement(" + Code + ", " + ChainName + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002440 }
Evan Chengb915f312005-12-09 22:45:35 +00002441 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002442
Evan Cheng54597732006-01-26 00:22:25 +00002443 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002444 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = InFlag;");
Evan Cheng97938882005-12-22 02:24:50 +00002445
Evan Cheng54597732006-01-26 00:22:25 +00002446 if (AddedChain && NodeHasOutFlag) {
Evan Cheng823b7522006-01-19 21:57:10 +00002447 if (NumExpectedResults == 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002448 emitCode("return Result.getValue(N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002449 } else {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002450 emitCode("if (N.ResNo < " + utostr(NumExpectedResults) + ")");
2451 emitCode(" return Result.getValue(N.ResNo);");
2452 emitCode("else");
2453 emitCode(" return Result.getValue(N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002454 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002455 } else {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002456 emitCode("return Result.getValue(N.ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002457 }
Evan Chengb915f312005-12-09 22:45:35 +00002458 } else {
2459 // If this instruction is the root, and if there is only one use of it,
2460 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002461 emitCode("if (N.Val->hasOneUse()) {");
2462 std::string Code = " return CurDAG->SelectNodeTo(N.Val, " +
2463 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002464 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002465 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002466 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002467 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002468 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002469 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002470 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002471 Code += ", InFlag";
2472 emitCode(Code + ");");
2473 emitCode("} else {");
2474 Code = " return CodeGenMap[N] = CurDAG->getTargetNode(" +
2475 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("}");
Evan Chengb915f312005-12-09 22:45:35 +00002486 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002487
Evan Chengb915f312005-12-09 22:45:35 +00002488 return std::make_pair(1, ResNo);
2489 } else if (Op->isSubClassOf("SDNodeXForm")) {
2490 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002491 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002492 unsigned ResNo = TmpNo++;
Evan Cheng21ad3922006-02-07 00:37:41 +00002493 emitDecl("Tmp" + utostr(ResNo));
2494 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Chris Lattner8a0604b2006-01-28 20:31:24 +00002495 + "(Tmp" + utostr(OpVal) + ".Val);");
Evan Chengb915f312005-12-09 22:45:35 +00002496 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002497 emitCode("CodeGenMap[N] = Tmp" +utostr(ResNo) + ";");
2498 emitCode("return Tmp" + utostr(ResNo) + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002499 }
2500 return std::make_pair(1, ResNo);
2501 } else {
2502 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002503 std::cerr << "\n";
2504 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002505 }
2506 }
2507
Chris Lattner488580c2006-01-28 19:06:51 +00002508 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2509 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002510 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2511 /// for, this returns true otherwise false if Pat has all types.
2512 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2513 const std::string &Prefix) {
2514 // Did we find one?
2515 if (!Pat->hasTypeSet()) {
2516 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002517 Pat->setTypes(Other->getExtTypes());
Chris Lattner67a202b2006-01-28 20:43:52 +00002518 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002519 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002520 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002521 }
2522
Evan Cheng51fecc82006-01-09 18:27:06 +00002523 unsigned OpNo =
2524 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002525 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2526 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2527 Prefix + utostr(OpNo)))
2528 return true;
2529 return false;
2530 }
2531
2532private:
Evan Cheng54597732006-01-26 00:22:25 +00002533 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002534 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002535 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2536 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002537 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002538 unsigned OpNo =
2539 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002540 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2541 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002542 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2543 TreePatternNode *Child = N->getChild(i);
2544 if (!Child->isLeaf()) {
Evan Cheng54597732006-01-26 00:22:25 +00002545 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002546 } else {
2547 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002548 if (!Child->getName().empty()) {
2549 std::string Name = RootName + utostr(OpNo);
2550 if (Duplicates.find(Name) != Duplicates.end())
2551 // A duplicate! Do not emit a copy for this node.
2552 continue;
2553 }
2554
Evan Chengb915f312005-12-09 22:45:35 +00002555 Record *RR = DI->getDef();
2556 if (RR->isSubClassOf("Register")) {
2557 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002558 if (RVT == MVT::Flag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002559 emitCode("InFlag = Select(" + RootName + utostr(OpNo) + ");");
Evan Chengb2c6d492006-01-11 22:16:13 +00002560 } else {
2561 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002562 emitDecl("Chain");
2563 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002564 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002565 ChainEmitted = true;
2566 }
Evan Cheng21ad3922006-02-07 00:37:41 +00002567 emitDecl(RootName + "CR" + utostr(i));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002568 emitCode(RootName + "CR" + utostr(i) +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002569 " = CurDAG->getCopyToReg(" + ChainName +
2570 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2571 ", MVT::" + getEnumName(RVT) + "), Select(" + RootName +
2572 utostr(OpNo) + "), InFlag);");
2573 emitCode(ChainName + " = " + RootName + "CR" + utostr(i) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002574 ".getValue(0);");
2575 emitCode("InFlag = " + RootName + "CR" + utostr(i) +
2576 ".getValue(1);");
Evan Chengb915f312005-12-09 22:45:35 +00002577 }
2578 }
2579 }
2580 }
2581 }
Evan Cheng54597732006-01-26 00:22:25 +00002582
2583 if (HasInFlag || HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002584 std::string Code;
Evan Cheng54597732006-01-26 00:22:25 +00002585 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002586 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2587 ") {");
2588 Code = " ";
Evan Cheng54597732006-01-26 00:22:25 +00002589 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002590 emitCode(Code + "InFlag = Select(" + RootName + ".getOperand(" +
2591 utostr(OpNo) + "));");
Evan Cheng54597732006-01-26 00:22:25 +00002592 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002593 emitCode(" HasOptInFlag = true;");
2594 emitCode("}");
Evan Cheng54597732006-01-26 00:22:25 +00002595 }
2596 }
Evan Chengb915f312005-12-09 22:45:35 +00002597 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002598
2599 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002600 /// as specified by the instruction. It returns true if any copy is
2601 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002602 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002603 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002604 Record *Op = N->getOperator();
2605 if (Op->isSubClassOf("Instruction")) {
2606 const DAGInstruction &Inst = ISE.getInstruction(Op);
2607 const CodeGenTarget &CGT = ISE.getTargetInfo();
2608 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2609 unsigned NumImpResults = Inst.getNumImpResults();
2610 for (unsigned i = 0; i < NumImpResults; i++) {
2611 Record *RR = Inst.getImpResult(i);
2612 if (RR->isSubClassOf("Register")) {
2613 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2614 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002615 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002616 emitDecl("Chain");
2617 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002618 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002619 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002620 }
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002621 emitCode("Result = CurDAG->getCopyFromReg(" + ChainName + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002622 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
2623 ", InFlag);");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002624 emitCode(ChainName + " = Result.getValue(1);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002625 emitCode("InFlag = Result.getValue(2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002626 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002627 }
2628 }
2629 }
2630 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002631 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002632 }
Evan Chengb915f312005-12-09 22:45:35 +00002633};
2634
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002635/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2636/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00002637/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00002638void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Chenge41bf822006-02-05 06:43:12 +00002639 std::vector<std::pair<bool, std::string> > &GeneratedCode,
Evan Cheng21ad3922006-02-07 00:37:41 +00002640 std::set<std::string> &GeneratedDecl,
Evan Chenge41bf822006-02-05 06:43:12 +00002641 bool DoReplace) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002642 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2643 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Cheng21ad3922006-02-07 00:37:41 +00002644 GeneratedCode, GeneratedDecl, DoReplace);
Evan Chengb915f312005-12-09 22:45:35 +00002645
Chris Lattner8fc35682005-09-23 23:16:51 +00002646 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002647 bool FoundChain = false;
Evan Chenge41bf822006-02-05 06:43:12 +00002648 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002649
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002650 // TP - Get *SOME* tree pattern, we don't care which.
2651 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002652
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002653 // At this point, we know that we structurally match the pattern, but the
2654 // types of the nodes may not match. Figure out the fewest number of type
2655 // comparisons we need to emit. For example, if there is only one integer
2656 // type supported by a target, there should be no type comparisons at all for
2657 // integer patterns!
2658 //
2659 // To figure out the fewest number of type checks needed, clone the pattern,
2660 // remove the types, then perform type inference on the pattern as a whole.
2661 // If there are unresolved types, emit an explicit check for those types,
2662 // apply the type to the tree, then rerun type inference. Iterate until all
2663 // types are resolved.
2664 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002665 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002666 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002667
2668 do {
2669 // Resolve/propagate as many types as possible.
2670 try {
2671 bool MadeChange = true;
2672 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00002673 MadeChange = Pat->ApplyTypeConstraints(TP,
2674 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00002675 } catch (...) {
2676 assert(0 && "Error: could not find consistent types for something we"
2677 " already decided was ok!");
2678 abort();
2679 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002680
Chris Lattner7e82f132005-10-15 21:34:21 +00002681 // Insert a check for an unresolved type and add it to the tree. If we find
2682 // an unresolved type to add a check for, this returns true and we iterate,
2683 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002684 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002685
Evan Cheng58e84a62005-12-14 22:02:59 +00002686 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002687 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00002688}
2689
Chris Lattner24e00a42006-01-29 04:41:05 +00002690/// EraseCodeLine - Erase one code line from all of the patterns. If removing
2691/// a line causes any of them to be empty, remove them and return true when
2692/// done.
2693static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2694 std::vector<std::pair<bool, std::string> > > >
2695 &Patterns) {
2696 bool ErasedPatterns = false;
2697 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2698 Patterns[i].second.pop_back();
2699 if (Patterns[i].second.empty()) {
2700 Patterns.erase(Patterns.begin()+i);
2701 --i; --e;
2702 ErasedPatterns = true;
2703 }
2704 }
2705 return ErasedPatterns;
2706}
2707
Chris Lattner8bc74722006-01-29 04:25:26 +00002708/// EmitPatterns - Emit code for at least one pattern, but try to group common
2709/// code together between the patterns.
2710void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
2711 std::vector<std::pair<bool, std::string> > > >
2712 &Patterns, unsigned Indent,
2713 std::ostream &OS) {
2714 typedef std::pair<bool, std::string> CodeLine;
2715 typedef std::vector<CodeLine> CodeList;
2716 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2717
2718 if (Patterns.empty()) return;
2719
Chris Lattner24e00a42006-01-29 04:41:05 +00002720 // Figure out how many patterns share the next code line. Explicitly copy
2721 // FirstCodeLine so that we don't invalidate a reference when changing
2722 // Patterns.
2723 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00002724 unsigned LastMatch = Patterns.size()-1;
2725 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2726 --LastMatch;
2727
2728 // If not all patterns share this line, split the list into two pieces. The
2729 // first chunk will use this line, the second chunk won't.
2730 if (LastMatch != 0) {
2731 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2732 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2733
2734 // FIXME: Emit braces?
2735 if (Shared.size() == 1) {
2736 PatternToMatch &Pattern = *Shared.back().first;
2737 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2738 Pattern.getSrcPattern()->print(OS);
2739 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2740 Pattern.getDstPattern()->print(OS);
2741 OS << "\n";
2742 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2743 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
2744 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2745 }
2746 if (!FirstCodeLine.first) {
2747 OS << std::string(Indent, ' ') << "{\n";
2748 Indent += 2;
2749 }
2750 EmitPatterns(Shared, Indent, OS);
2751 if (!FirstCodeLine.first) {
2752 Indent -= 2;
2753 OS << std::string(Indent, ' ') << "}\n";
2754 }
2755
2756 if (Other.size() == 1) {
2757 PatternToMatch &Pattern = *Other.back().first;
2758 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2759 Pattern.getSrcPattern()->print(OS);
2760 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2761 Pattern.getDstPattern()->print(OS);
2762 OS << "\n";
2763 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2764 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
2765 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2766 }
2767 EmitPatterns(Other, Indent, OS);
2768 return;
2769 }
2770
Chris Lattner24e00a42006-01-29 04:41:05 +00002771 // Remove this code from all of the patterns that share it.
2772 bool ErasedPatterns = EraseCodeLine(Patterns);
2773
Chris Lattner8bc74722006-01-29 04:25:26 +00002774 bool isPredicate = FirstCodeLine.first;
2775
2776 // Otherwise, every pattern in the list has this line. Emit it.
2777 if (!isPredicate) {
2778 // Normal code.
2779 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2780 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00002781 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2782
2783 // If the next code line is another predicate, and if all of the pattern
2784 // in this group share the same next line, emit it inline now. Do this
2785 // until we run out of common predicates.
2786 while (!ErasedPatterns && Patterns.back().second.back().first) {
2787 // Check that all of fhe patterns in Patterns end with the same predicate.
2788 bool AllEndWithSamePredicate = true;
2789 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2790 if (Patterns[i].second.back() != Patterns.back().second.back()) {
2791 AllEndWithSamePredicate = false;
2792 break;
2793 }
2794 // If all of the predicates aren't the same, we can't share them.
2795 if (!AllEndWithSamePredicate) break;
2796
2797 // Otherwise we can. Emit it shared now.
2798 OS << " &&\n" << std::string(Indent+4, ' ')
2799 << Patterns.back().second.back().second;
2800 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00002801 }
Chris Lattner24e00a42006-01-29 04:41:05 +00002802
2803 OS << ") {\n";
2804 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00002805 }
2806
2807 EmitPatterns(Patterns, Indent, OS);
2808
2809 if (isPredicate)
2810 OS << std::string(Indent-2, ' ') << "}\n";
2811}
2812
2813
Chris Lattner37481472005-09-26 21:59:35 +00002814
2815namespace {
2816 /// CompareByRecordName - An ordering predicate that implements less-than by
2817 /// comparing the names records.
2818 struct CompareByRecordName {
2819 bool operator()(const Record *LHS, const Record *RHS) const {
2820 // Sort by name first.
2821 if (LHS->getName() < RHS->getName()) return true;
2822 // If both names are equal, sort by pointer.
2823 return LHS->getName() == RHS->getName() && LHS < RHS;
2824 }
2825 };
2826}
2827
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002828void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002829 std::string InstNS = Target.inst_begin()->second.Namespace;
2830 if (!InstNS.empty()) InstNS += "::";
2831
Chris Lattner602f6922006-01-04 00:25:00 +00002832 // Group the patterns by their top-level opcodes.
2833 std::map<Record*, std::vector<PatternToMatch*>,
2834 CompareByRecordName> PatternsByOpcode;
2835 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2836 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2837 if (!Node->isLeaf()) {
2838 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2839 } else {
2840 const ComplexPattern *CP;
2841 if (IntInit *II =
2842 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2843 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2844 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2845 std::vector<Record*> OpNodes = CP->getRootNodes();
2846 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00002847 PatternsByOpcode[OpNodes[j]]
2848 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00002849 }
2850 } else {
2851 std::cerr << "Unrecognized opcode '";
2852 Node->dump();
2853 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00002854 std::cerr <<
2855 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00002856 std::cerr << "'!\n";
2857 exit(1);
2858 }
2859 }
2860 }
2861
2862 // Emit one Select_* method for each top-level opcode. We do this instead of
2863 // emitting one giant switch statement to support compilers where this will
2864 // result in the recursive functions taking less stack space.
2865 for (std::map<Record*, std::vector<PatternToMatch*>,
2866 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2867 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00002868 const std::string &OpName = PBOI->first->getName();
2869 OS << "SDOperand Select_" << OpName << "(SDOperand N) {\n";
Chris Lattner602f6922006-01-04 00:25:00 +00002870
2871 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Evan Chenge41bf822006-02-05 06:43:12 +00002872 bool OptSlctOrder =
2873 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
2874 OpcodeInfo.getNumResults() > 0);
2875
2876 if (OptSlctOrder) {
2877 OS << " SDOperand RetVal;\n";
2878 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
2879 << " && N.getValue(0).hasOneUse()) {\n"
2880 << " SDOperand Dummy = "
2881 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
2882 << " CodeGenMap[N.getValue(" << OpcodeInfo.getNumResults()
2883 << ")] = Dummy;\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00002884 << " HandleMap[N.getValue(" << OpcodeInfo.getNumResults()
Evan Chenge41bf822006-02-05 06:43:12 +00002885 << ")] = Dummy;\n"
2886 << " return Dummy;\n"
2887 << " }\n";
2888 }
2889
Chris Lattner602f6922006-01-04 00:25:00 +00002890 std::vector<PatternToMatch*> &Patterns = PBOI->second;
Chris Lattner355408b2006-01-29 02:43:35 +00002891 assert(!Patterns.empty() && "No patterns but map has entry?");
Chris Lattner602f6922006-01-04 00:25:00 +00002892
2893 // We want to emit all of the matching code now. However, we want to emit
2894 // the matches in order of minimal cost. Sort the patterns so the least
2895 // cost one is at the start.
2896 std::stable_sort(Patterns.begin(), Patterns.end(),
2897 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00002898
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002899 typedef std::vector<std::pair<bool, std::string> > CodeList;
Evan Cheng21ad3922006-02-07 00:37:41 +00002900 typedef std::set<std::string> DeclSet;
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002901
2902 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
Evan Cheng21ad3922006-02-07 00:37:41 +00002903 std::set<std::string> GeneratedDecl;
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002904 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002905 CodeList GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002906 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
2907 OptSlctOrder);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002908 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
2909 }
2910
2911 // Scan the code to see if all of the patterns are reachable and if it is
2912 // possible that the last one might not match.
2913 bool mightNotMatch = true;
2914 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2915 CodeList &GeneratedCode = CodeForPatterns[i].second;
2916 mightNotMatch = false;
Chris Lattner355408b2006-01-29 02:43:35 +00002917
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002918 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
2919 if (GeneratedCode[j].first) { // predicate.
2920 mightNotMatch = true;
2921 break;
2922 }
2923 }
Chris Lattner355408b2006-01-29 02:43:35 +00002924
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002925 // If this pattern definitely matches, and if it isn't the last one, the
2926 // patterns after it CANNOT ever match. Error out.
2927 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
2928 std::cerr << "Pattern '";
2929 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
2930 std::cerr << "' is impossible to select!\n";
2931 exit(1);
2932 }
2933 }
Evan Cheng21ad3922006-02-07 00:37:41 +00002934
2935 // Print all declarations.
2936 for (std::set<std::string>::iterator I = GeneratedDecl.begin(),
2937 E = GeneratedDecl.end(); I != E; ++I)
2938 OS << " SDOperand " << *I << ";\n";
2939
Chris Lattner8bc74722006-01-29 04:25:26 +00002940 // Loop through and reverse all of the CodeList vectors, as we will be
2941 // accessing them from their logical front, but accessing the end of a
2942 // vector is more efficient.
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002943 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2944 CodeList &GeneratedCode = CodeForPatterns[i].second;
Chris Lattner8bc74722006-01-29 04:25:26 +00002945 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002946 }
Chris Lattner602f6922006-01-04 00:25:00 +00002947
Chris Lattner8bc74722006-01-29 04:25:26 +00002948 // Next, reverse the list of patterns itself for the same reason.
2949 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
2950
2951 // Emit all of the patterns now, grouped together to share code.
2952 EmitPatterns(CodeForPatterns, 2, OS);
2953
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002954 // If the last pattern has predicates (which could fail) emit code to catch
2955 // the case where nothing handles a pattern.
Chris Lattner355408b2006-01-29 02:43:35 +00002956 if (mightNotMatch)
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002957 OS << " std::cerr << \"Cannot yet select: \";\n"
2958 << " N.Val->dump(CurDAG);\n"
2959 << " std::cerr << '\\n';\n"
2960 << " abort();\n";
2961
2962 OS << "}\n\n";
Chris Lattner602f6922006-01-04 00:25:00 +00002963 }
2964
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002965 // Emit boilerplate.
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00002966 OS << "SDOperand Select_INLINEASM(SDOperand N) {\n"
2967 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
2968 << " Ops[0] = Select(N.getOperand(0)); // Select the chain.\n\n"
2969 << " // Select the flag operand.\n"
2970 << " if (Ops.back().getValueType() == MVT::Flag)\n"
2971 << " Ops.back() = Select(Ops.back());\n"
2972 << " std::vector<MVT::ValueType> VTs;\n"
2973 << " VTs.push_back(MVT::Other);\n"
2974 << " VTs.push_back(MVT::Flag);\n"
2975 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
2976 << " CodeGenMap[N.getValue(0)] = New;\n"
2977 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2978 << " return New.getValue(N.ResNo);\n"
2979 << "}\n\n";
2980
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002981 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002982 << "SDOperand SelectCode(SDOperand N) {\n"
2983 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002984 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2985 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002986 << " return N; // Already selected.\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002987 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng481c8e02005-12-12 23:22:48 +00002988 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002989 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002990 << " default: break;\n"
2991 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00002992 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00002993 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00002994 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00002995 << " case ISD::TargetConstant:\n"
2996 << " case ISD::TargetConstantPool:\n"
2997 << " case ISD::TargetFrameIndex:\n"
2998 << " case ISD::TargetGlobalAddress:\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002999 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003000 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003001 << " case ISD::AssertZext: {\n"
3002 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
3003 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
3004 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003005 << " }\n"
3006 << " case ISD::TokenFactor:\n"
3007 << " if (N.getNumOperands() == 2) {\n"
3008 << " SDOperand Op0 = Select(N.getOperand(0));\n"
3009 << " SDOperand Op1 = Select(N.getOperand(1));\n"
3010 << " return CodeGenMap[N] =\n"
3011 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3012 << " } else {\n"
3013 << " std::vector<SDOperand> Ops;\n"
3014 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
3015 << " Ops.push_back(Select(N.getOperand(i)));\n"
3016 << " return CodeGenMap[N] = \n"
3017 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3018 << " }\n"
3019 << " case ISD::CopyFromReg: {\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00003020 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003021 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3022 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003023 << " if (N.Val->getNumValues() == 2) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003024 << " if (Chain == N.getOperand(0)) return N; // No change\n"
3025 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3026 << " CodeGenMap[N.getValue(0)] = New;\n"
3027 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
3028 << " return New.getValue(N.ResNo);\n"
3029 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003030 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003031 << " if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
3032 << " if (Chain == N.getOperand(0) &&\n"
3033 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003034 << " return N; // No change\n"
3035 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3036 << " CodeGenMap[N.getValue(0)] = New;\n"
3037 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
3038 << " CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
3039 << " return New.getValue(N.ResNo);\n"
3040 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003041 << " }\n"
3042 << " case ISD::CopyToReg: {\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00003043 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003044 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003045 << " SDOperand Val = Select(N.getOperand(2));\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00003046 << " SDOperand Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003047 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003048 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003049 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003050 << " return CodeGenMap[N] = Result;\n"
3051 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003052 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003053 << " if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003054 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003055 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3056 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003057 << " CodeGenMap[N.getValue(0)] = Result;\n"
3058 << " CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
3059 << " return Result.getValue(N.ResNo);\n"
3060 << " }\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003061 << " }\n"
3062 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n";
3063
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003064
Chris Lattner602f6922006-01-04 00:25:00 +00003065 // Loop over all of the case statements, emiting a call to each method we
3066 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003067 for (std::map<Record*, std::vector<PatternToMatch*>,
3068 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3069 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003070 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00003071 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00003072 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Chris Lattner602f6922006-01-04 00:25:00 +00003073 << "return Select_" << PBOI->first->getName() << "(N);\n";
Chris Lattner81303322005-09-23 19:36:15 +00003074 }
Chris Lattner81303322005-09-23 19:36:15 +00003075
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003076 OS << " } // end of big switch.\n\n"
3077 << " std::cerr << \"Cannot yet select: \";\n"
Evan Cheng97938882005-12-22 02:24:50 +00003078 << " N.Val->dump(CurDAG);\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003079 << " std::cerr << '\\n';\n"
3080 << " abort();\n"
3081 << "}\n";
3082}
3083
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003084void DAGISelEmitter::run(std::ostream &OS) {
3085 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3086 " target", OS);
3087
Chris Lattner1f39e292005-09-14 00:09:24 +00003088 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3089 << "// *** instruction selector class. These functions are really "
3090 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003091
Chris Lattner296dfe32005-09-24 00:50:51 +00003092 OS << "// Instance var to keep track of multiply used nodes that have \n"
3093 << "// already been selected.\n"
3094 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003095
3096 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003097 << "// and their place handle nodes.\n";
3098 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3099 OS << "// Instance var to keep track of mapping of place handle nodes\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003100 << "// and their replacement nodes.\n";
3101 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3102
3103 OS << "\n";
3104 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3105 << "std::set<SDNode *> &Visited) {\n";
3106 OS << " if (found || !Visited.insert(Use).second) return;\n";
3107 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3108 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3109 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3110 OS << " if (N != Def) {\n";
3111 OS << " findNonImmUse(N, Def, found, Visited);\n";
3112 OS << " } else {\n";
3113 OS << " found = true;\n";
3114 OS << " break;\n";
3115 OS << " }\n";
3116 OS << " }\n";
3117 OS << " }\n";
3118 OS << "}\n";
3119
3120 OS << "\n";
3121 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3122 OS << " std::set<SDNode *> Visited;\n";
3123 OS << " bool found = false;\n";
3124 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3125 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3126 OS << " if (N != Def) {\n";
3127 OS << " findNonImmUse(N, Def, found, Visited);\n";
3128 OS << " if (found) break;\n";
3129 OS << " }\n";
3130 OS << " }\n";
3131 OS << " return found;\n";
3132 OS << "}\n";
3133
3134 OS << "\n";
Evan Cheng024524f2006-02-06 06:03:35 +00003135 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003136 << "// handle node in ReplaceMap.\n";
Evan Cheng024524f2006-02-06 06:03:35 +00003137 OS << "void AddHandleReplacement(SDOperand N, SDOperand R) {\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003138 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3139 OS << " if (HMI != HandleMap.end()) {\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003140 OS << " ReplaceMap[HMI->second] = R;\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003141 OS << " HandleMap.erase(N);\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003142 OS << " }\n";
3143 OS << "}\n";
3144
3145 OS << "\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003146 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3147 OS << "// handles.Some handles do not yet have replacements because the\n";
3148 OS << "// nodes they replacements have only dead readers.\n";
3149 OS << "void SelectDanglingHandles() {\n";
3150 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3151 << "HandleMap.begin(),\n"
3152 << " E = HandleMap.end(); I != E; ++I) {\n";
3153 OS << " SDOperand N = I->first;\n";
3154 OS << " AddHandleReplacement(N, Select(N.getValue(0)));\n";
3155 OS << " }\n";
3156 OS << "}\n";
3157 OS << "\n";
3158 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003159 OS << "// specific nodes.\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003160 OS << "void ReplaceHandles() {\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003161 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3162 << "ReplaceMap.begin(),\n"
3163 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3164 OS << " SDOperand From = I->first;\n";
3165 OS << " SDOperand To = I->second;\n";
3166 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3167 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3168 OS << " SDNode *Use = *UI;\n";
3169 OS << " std::vector<SDOperand> Ops;\n";
3170 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3171 OS << " SDOperand O = Use->getOperand(i);\n";
3172 OS << " if (O.Val == From.Val)\n";
3173 OS << " Ops.push_back(To);\n";
3174 OS << " else\n";
3175 OS << " Ops.push_back(O);\n";
3176 OS << " }\n";
3177 OS << " SDOperand U = SDOperand(Use, 0);\n";
3178 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3179 OS << " }\n";
3180 OS << " }\n";
3181 OS << "}\n";
3182
3183 OS << "\n";
3184 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3185 OS << "SDOperand SelectRoot(SDOperand N) {\n";
3186 OS << " SDOperand RetVal = Select(N);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003187 OS << " SelectDanglingHandles();\n";
3188 OS << " ReplaceHandles();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003189 OS << " ReplaceMap.clear();\n";
3190 OS << " return RetVal;\n";
3191 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003192
Chris Lattnerca559d02005-09-08 21:03:01 +00003193 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003194 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003195 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003196 ParsePatternFragments(OS);
3197 ParseInstructions();
3198 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003199
Chris Lattnere97603f2005-09-28 19:27:25 +00003200 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003201 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003202 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003203
Chris Lattnere46e17b2005-09-29 19:28:10 +00003204
3205 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3206 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003207 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3208 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003209 std::cerr << "\n";
3210 });
3211
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003212 // At this point, we have full information about the 'Patterns' we need to
3213 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003214 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003215 EmitInstructionSelector(OS);
3216
3217 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3218 E = PatternFragments.end(); I != E; ++I)
3219 delete I->second;
3220 PatternFragments.clear();
3221
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003222 Instructions.clear();
3223}