blob: b03d7522af6549904435d793ed02cfe32662fdd2 [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;
1857
Evan Chenge4a8a6e2006-02-03 06:22:41 +00001858 std::string ChainName;
Evan Chenge41bf822006-02-05 06:43:12 +00001859 bool DoReplace;
Chris Lattner8a0604b2006-01-28 20:31:24 +00001860 unsigned TmpNo;
1861
1862 void emitCheck(const std::string &S) {
1863 if (!S.empty())
1864 GeneratedCode.push_back(std::make_pair(true, S));
1865 }
1866 void emitCode(const std::string &S) {
1867 if (!S.empty())
1868 GeneratedCode.push_back(std::make_pair(false, S));
1869 }
Evan Chengb915f312005-12-09 22:45:35 +00001870public:
Evan Cheng58e84a62005-12-14 22:02:59 +00001871 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
1872 TreePatternNode *pattern, TreePatternNode *instr,
Evan Chenge41bf822006-02-05 06:43:12 +00001873 std::vector<std::pair<bool, std::string> > &gc, bool dorep)
Chris Lattner8a0604b2006-01-28 20:31:24 +00001874 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Chenge41bf822006-02-05 06:43:12 +00001875 GeneratedCode(gc), DoReplace(dorep), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00001876
1877 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
1878 /// if the match fails. At this point, we already know that the opcode for N
1879 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00001880 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
1881 const std::string &RootName, const std::string &ParentName,
1882 const std::string &ChainSuffix, bool &FoundChain) {
1883 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00001884 // Emit instruction predicates. Each predicate is just a string for now.
1885 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001886 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00001887 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
1888 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
1889 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00001890 if (!Def->isSubClassOf("Predicate")) {
Evan Cheng58e84a62005-12-14 22:02:59 +00001891 Def->dump();
1892 assert(0 && "Unknown predicate type!");
1893 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00001894 if (!PredicateCheck.empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00001895 PredicateCheck += " || ";
1896 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00001897 }
1898 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00001899
1900 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00001901 }
1902
Evan Chengb915f312005-12-09 22:45:35 +00001903 if (N->isLeaf()) {
1904 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001905 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00001906 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00001907 return;
1908 } else if (!NodeIsComplexPattern(N)) {
1909 assert(0 && "Cannot match this as a leaf value!");
1910 abort();
1911 }
1912 }
1913
Chris Lattner488580c2006-01-28 19:06:51 +00001914 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00001915 // we already saw this in the pattern, emit code to verify dagness.
1916 if (!N->getName().empty()) {
1917 std::string &VarMapEntry = VariableMap[N->getName()];
1918 if (VarMapEntry.empty()) {
1919 VarMapEntry = RootName;
1920 } else {
1921 // If we get here, this is a second reference to a specific name. Since
1922 // we already have checked that the first reference is valid, we don't
1923 // have to recursively match it, just check that it's the same as the
1924 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00001925 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00001926 return;
1927 }
Evan Chengf805c2e2006-01-12 19:35:54 +00001928
1929 if (!N->isLeaf())
1930 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00001931 }
1932
1933
1934 // Emit code to load the child nodes and match their contents recursively.
1935 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00001936 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
1937 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
1938 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00001939 bool EmittedUseCheck = false;
1940 bool EmittedSlctedCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00001941 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00001942 if (NodeHasChain)
1943 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00001944 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00001945 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattner8a0604b2006-01-28 20:31:24 +00001946 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00001947 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00001948 EmittedUseCheck = true;
1949 // hasOneUse() check is not strong enough. If the original node has
1950 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00001951 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00001952 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00001953 "))");
1954
Evan Cheng1feeeec2006-01-26 19:13:45 +00001955 EmittedSlctedCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00001956 if (NodeHasChain) {
1957 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
1958 // has a chain use.
1959 // This a workaround for this problem:
1960 //
1961 // [ch, r : ld]
1962 // ^ ^
1963 // | |
1964 // [XX]--/ \- [flag : cmp]
1965 // ^ ^
1966 // | |
1967 // \---[br flag]-
1968 //
1969 // cmp + br should be considered as a single node as they are flagged
1970 // together. So, if the ld is folded into the cmp, the XX node in the
1971 // graph is now both an operand and a use of the ld/cmp/br node.
1972 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
1973 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
1974
1975 // If the immediate use can somehow reach this node through another
1976 // path, then can't fold it either or it will create a cycle.
1977 // e.g. In the following diagram, XX can reach ld through YY. If
1978 // ld is folded into XX, then YY is both a predecessor and a successor
1979 // of XX.
1980 //
1981 // [ld]
1982 // ^ ^
1983 // | |
1984 // / \---
1985 // / [YY]
1986 // | ^
1987 // [XX]-------|
1988 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
1989 if (PInfo.getNumOperands() > 1 ||
1990 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
1991 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
1992 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
1993 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
1994 "isNonImmUse(" + ParentName + ".Val, " + RootName +
1995 ".Val))");
1996 }
Evan Chengb915f312005-12-09 22:45:35 +00001997 }
Evan Chenge41bf822006-02-05 06:43:12 +00001998
Evan Chengc15d18c2006-01-27 22:13:45 +00001999 if (NodeHasChain) {
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002000 if (FoundChain)
Chris Lattner67a202b2006-01-28 20:43:52 +00002001 emitCheck("Chain.Val == " + RootName + ".Val");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002002 else
2003 FoundChain = true;
2004 ChainName = "Chain" + ChainSuffix;
2005 emitCode("SDOperand " + ChainName + " = " + RootName +
2006 ".getOperand(0);");
Evan Cheng1cf6db22006-01-06 00:41:12 +00002007 }
Evan Chengb915f312005-12-09 22:45:35 +00002008 }
2009
Evan Cheng54597732006-01-26 00:22:25 +00002010 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002011 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002012 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002013 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2014 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002015 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002016 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2017 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2018 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002019 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2020 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002021 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002022 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002023 }
Evan Cheng1feeeec2006-01-26 19:13:45 +00002024 if (!EmittedSlctedCheck)
2025 // hasOneUse() check is not strong enough. If the original node has
2026 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002027 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002028 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002029 "))");
Evan Cheng54597732006-01-26 00:22:25 +00002030 }
2031
Evan Chengb915f312005-12-09 22:45:35 +00002032 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002033 emitCode("SDOperand " + RootName + utostr(OpNo) + " = " +
2034 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002035 TreePatternNode *Child = N->getChild(i);
2036
2037 if (!Child->isLeaf()) {
2038 // If it's not a leaf, recursively match.
2039 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002040 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002041 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002042 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2043 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002044 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002045 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2046 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002047 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002048 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002049 // we already saw this in the pattern, emit code to verify dagness.
2050 if (!Child->getName().empty()) {
2051 std::string &VarMapEntry = VariableMap[Child->getName()];
2052 if (VarMapEntry.empty()) {
2053 VarMapEntry = RootName + utostr(OpNo);
2054 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002055 // If we get here, this is a second reference to a specific name.
2056 // Since we already have checked that the first reference is valid,
2057 // we don't have to recursively match it, just check that it's the
2058 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002059 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002060 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002061 continue;
2062 }
2063 }
2064
2065 // Handle leaves of various types.
2066 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2067 Record *LeafRec = DI->getDef();
2068 if (LeafRec->isSubClassOf("RegisterClass")) {
2069 // Handle register references. Nothing to do here.
2070 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002071 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002072 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2073 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00002074 } else if (LeafRec->getName() == "srcvalue") {
2075 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002076 } else if (LeafRec->isSubClassOf("ValueType")) {
2077 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002078 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002079 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002080 } else if (LeafRec->isSubClassOf("CondCode")) {
2081 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002082 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002083 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002084 } else {
2085 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002086 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00002087 assert(0 && "Unknown leaf type!");
2088 }
Chris Lattner488580c2006-01-28 19:06:51 +00002089 } else if (IntInit *II =
2090 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002091 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2092 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002093 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002094 RootName + utostr(OpNo) + ")->getSignExtended();");
2095
2096 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002097 } else {
2098 Child->dump();
2099 assert(0 && "Unknown leaf type!");
2100 }
2101 }
2102 }
2103
2104 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002105 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002106 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002107 }
2108
2109 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2110 /// we actually have to build a DAG!
2111 std::pair<unsigned, unsigned>
2112 EmitResultCode(TreePatternNode *N, bool isRoot = false) {
2113 // This is something selected from the pattern we matched.
2114 if (!N->getName().empty()) {
2115 assert(!isRoot && "Root of pattern cannot be a leaf!");
2116 std::string &Val = VariableMap[N->getName()];
2117 assert(!Val.empty() &&
2118 "Variable referenced but not defined and not caught earlier!");
2119 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2120 // Already selected this operand, just return the tmpval.
2121 return std::make_pair(1, atoi(Val.c_str()+3));
2122 }
2123
2124 const ComplexPattern *CP;
2125 unsigned ResNo = TmpNo++;
2126 unsigned NumRes = 1;
2127 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002128 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002129 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002130 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002131 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002132 case MVT::i1: CastType = "bool"; break;
2133 case MVT::i8: CastType = "unsigned char"; break;
2134 case MVT::i16: CastType = "unsigned short"; break;
2135 case MVT::i32: CastType = "unsigned"; break;
2136 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002137 }
Chris Lattner78593132006-01-29 20:01:35 +00002138 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
Andrew Lenharth2cba57c2006-01-29 05:17:22 +00002139 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002140 emitCode("SDOperand Tmp" + utostr(ResNo) +
2141 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2142 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengbb48e332006-01-12 07:54:57 +00002143 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002144 Record *Op = OperatorMap[N->getName()];
2145 // Transform ExternalSymbol to TargetExternalSymbol
2146 if (Op && Op->getName() == "externalsym") {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002147 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2148 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2149 Val + ")->getSymbol(), MVT::" +
2150 getEnumName(N->getTypeNum(0)) + ");");
2151 } else {
2152 emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
2153 }
Evan Chengb915f312005-12-09 22:45:35 +00002154 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002155 Record *Op = OperatorMap[N->getName()];
2156 // Transform GlobalAddress to TargetGlobalAddress
2157 if (Op && Op->getName() == "globaladdr") {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002158 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2159 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2160 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2161 ");");
2162 } else {
2163 emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
2164 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002165 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Chris Lattner8a0604b2006-01-28 20:31:24 +00002166 emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengbb48e332006-01-12 07:54:57 +00002167 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002168 emitCode("SDOperand Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002169 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2170 std::string Fn = CP->getSelectFunc();
2171 NumRes = CP->getNumOperands();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002172 std::string Code = "SDOperand ";
Jeff Cohen60e91872006-01-04 03:23:30 +00002173 for (unsigned i = 0; i < NumRes - 1; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002174 Code += "Tmp" + utostr(i+ResNo) + ", ";
2175 emitCode(Code + "Tmp" + utostr(NumRes - 1 + ResNo) + ";");
2176
Chris Lattner67a202b2006-01-28 20:43:52 +00002177 Code = Fn + "(" + Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002178 for (unsigned i = 0; i < NumRes; i++)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002179 Code += ", Tmp" + utostr(i + ResNo);
2180 emitCheck(Code + ")");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002181
Evan Cheng2216d8a2006-02-05 05:22:18 +00002182 for (unsigned i = 0; i < NumRes; ++i)
2183 emitCode("Tmp" + utostr(i+ResNo) + " = Select(Tmp" +
2184 utostr(i+ResNo) + ");");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002185
Evan Chengb915f312005-12-09 22:45:35 +00002186 TmpNo = ResNo + NumRes;
2187 } else {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002188 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Select(" + Val + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002189 }
2190 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2191 // value if used multiple times by this pattern result.
2192 Val = "Tmp"+utostr(ResNo);
2193 return std::make_pair(NumRes, ResNo);
2194 }
2195
2196 if (N->isLeaf()) {
2197 // If this is an explicit register reference, handle it.
2198 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2199 unsigned ResNo = TmpNo++;
2200 if (DI->getDef()->isSubClassOf("Register")) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002201 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2202 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2203 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002204 return std::make_pair(1, ResNo);
2205 }
2206 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2207 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002208 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002209 emitCode("SDOperand Tmp" + utostr(ResNo) +
2210 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2211 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002212 return std::make_pair(1, ResNo);
2213 }
2214
2215 N->dump();
2216 assert(0 && "Unknown leaf type!");
2217 return std::make_pair(1, ~0U);
2218 }
2219
2220 Record *Op = N->getOperator();
2221 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002222 const CodeGenTarget &CGT = ISE.getTargetInfo();
2223 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002224 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng7b05bd52005-12-23 22:11:47 +00002225 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2226 bool HasImpResults = Inst.getNumImpResults() > 0;
Evan Cheng54597732006-01-26 00:22:25 +00002227 bool HasOptInFlag = isRoot &&
2228 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002229 bool HasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002230 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2231 bool NodeHasOutFlag = HasImpResults ||
Evan Cheng51fecc82006-01-09 18:27:06 +00002232 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
Evan Cheng823b7522006-01-19 21:57:10 +00002233 bool NodeHasChain =
2234 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng51fecc82006-01-09 18:27:06 +00002235 bool HasChain = II.hasCtrlDep ||
2236 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
Evan Cheng4fba2812005-12-20 07:37:41 +00002237
Evan Cheng54597732006-01-26 00:22:25 +00002238 if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002239 emitCode("SDOperand InFlag = SDOperand(0, 0);");
Evan Cheng54597732006-01-26 00:22:25 +00002240 if (HasOptInFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002241 emitCode("bool HasOptInFlag = false;");
Evan Cheng4fba2812005-12-20 07:37:41 +00002242
Evan Cheng823b7522006-01-19 21:57:10 +00002243 // How many results is this pattern expected to produce?
2244 unsigned NumExpectedResults = 0;
2245 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2246 MVT::ValueType VT = Pattern->getTypeNum(i);
2247 if (VT != MVT::isVoid && VT != MVT::Flag)
2248 NumExpectedResults++;
2249 }
2250
Evan Chengb915f312005-12-09 22:45:35 +00002251 // Determine operand emission order. Complex pattern first.
2252 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2253 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2254 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2255 TreePatternNode *Child = N->getChild(i);
2256 if (i == 0) {
2257 EmitOrder.push_back(std::make_pair(i, Child));
2258 OI = EmitOrder.begin();
2259 } else if (NodeIsComplexPattern(Child)) {
2260 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2261 } else {
2262 EmitOrder.push_back(std::make_pair(i, Child));
2263 }
2264 }
2265
2266 // Emit all of the operands.
2267 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2268 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2269 unsigned OpOrder = EmitOrder[i].first;
2270 TreePatternNode *Child = EmitOrder[i].second;
2271 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2272 NumTemps[OpOrder] = NumTemp;
2273 }
2274
2275 // List all the operands in the right order.
2276 std::vector<unsigned> Ops;
2277 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2278 for (unsigned j = 0; j < NumTemps[i].first; j++)
2279 Ops.push_back(NumTemps[i].second + j);
2280 }
2281
Evan Chengb915f312005-12-09 22:45:35 +00002282 // Emit all the chain and CopyToReg stuff.
Evan Chengb2c6d492006-01-11 22:16:13 +00002283 bool ChainEmitted = HasChain;
Evan Cheng7b05bd52005-12-23 22:11:47 +00002284 if (HasChain)
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002285 emitCode(ChainName + " = Select(" + ChainName + ");");
Evan Cheng54597732006-01-26 00:22:25 +00002286 if (HasInFlag || HasOptInFlag || HasImpInputs)
2287 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
Evan Chengb915f312005-12-09 22:45:35 +00002288
Evan Chengb915f312005-12-09 22:45:35 +00002289 unsigned NumResults = Inst.getNumResults();
2290 unsigned ResNo = TmpNo++;
2291 if (!isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002292 std::string Code =
2293 "SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTargetNode(" +
2294 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002295 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002296 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002297 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002298 Code += ", MVT::Flag";
Evan Chengbcecf332005-12-17 01:19:28 +00002299
Evan Chengb915f312005-12-09 22:45:35 +00002300 unsigned LastOp = 0;
2301 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2302 LastOp = Ops[i];
Chris Lattner8a0604b2006-01-28 20:31:24 +00002303 Code += ", Tmp" + utostr(LastOp);
Evan Chengb915f312005-12-09 22:45:35 +00002304 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002305 emitCode(Code + ");");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002306 if (HasChain) {
Evan Chengb915f312005-12-09 22:45:35 +00002307 // Must have at least one result
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002308 emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002309 utostr(NumResults) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002310 }
Evan Cheng54597732006-01-26 00:22:25 +00002311 } else if (HasChain || NodeHasOutFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002312 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002313 emitCode("SDOperand Result = SDOperand(0, 0);");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002314 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002315 emitCode("if (HasOptInFlag)");
2316 std::string Code = " Result = CurDAG->getTargetNode(" +
2317 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002318
Evan Cheng9789aaa2006-01-24 20:46:50 +00002319 // Output order: results, chain, flags
2320 // Result types.
2321 if (NumResults > 0) {
2322 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002323 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002324 }
2325 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002326 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002327 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002328 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002329
2330 // Inputs.
2331 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002332 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002333 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002334 emitCode(Code + ", InFlag);");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002335
Chris Lattner8a0604b2006-01-28 20:31:24 +00002336 emitCode("else");
2337 Code = " Result = CurDAG->getTargetNode(" + II.Namespace + "::" +
2338 II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002339
2340 // Output order: results, chain, flags
2341 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002342 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2343 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002344 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002345 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002346 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002347 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002348
2349 // Inputs.
2350 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002351 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002352 if (HasChain) Code += ", " + ChainName + ");";
Chris Lattner8a0604b2006-01-28 20:31:24 +00002353 emitCode(Code);
Evan Cheng9789aaa2006-01-24 20:46:50 +00002354 } else {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002355 std::string Code = "SDOperand Result = CurDAG->getTargetNode(" +
2356 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002357
2358 // Output order: results, chain, flags
2359 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002360 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2361 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002362 if (HasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002363 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002364 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002365 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002366
2367 // Inputs.
2368 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002369 Code += ", Tmp" + utostr(Ops[i]);
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002370 if (HasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002371 if (HasInFlag || HasImpInputs) Code += ", InFlag";
2372 emitCode(Code + ");");
Evan Chengbcecf332005-12-17 01:19:28 +00002373 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002374
2375 unsigned ValNo = 0;
Evan Chengf9fc25d2005-12-19 22:40:04 +00002376 for (unsigned i = 0; i < NumResults; i++) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002377 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = Result"
2378 ".getValue(" + utostr(ValNo) + ");");
Evan Chengf9fc25d2005-12-19 22:40:04 +00002379 ValNo++;
2380 }
2381
Evan Cheng7b05bd52005-12-23 22:11:47 +00002382 if (HasChain)
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002383 emitCode(ChainName + " = Result.getValue(" + utostr(ValNo) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002384
Evan Cheng54597732006-01-26 00:22:25 +00002385 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002386 emitCode("InFlag = Result.getValue(" +
2387 utostr(ValNo + (unsigned)HasChain) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002388
Chris Lattner8a0604b2006-01-28 20:31:24 +00002389 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2390 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = "
2391 "Result.getValue(" + utostr(ValNo) + ");");
2392 ValNo++;
Evan Cheng97938882005-12-22 02:24:50 +00002393 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002394
Evan Cheng7b05bd52005-12-23 22:11:47 +00002395 // User does not expect that the instruction produces a chain!
Evan Cheng51fecc82006-01-09 18:27:06 +00002396 bool AddedChain = HasChain && !NodeHasChain;
Evan Chenge41bf822006-02-05 06:43:12 +00002397 if (NodeHasChain) {
2398 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = " +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002399 ChainName + ";");
Evan Chenge41bf822006-02-05 06:43:12 +00002400 if (DoReplace)
2401 emitCode("if (N.ResNo == 0) AddReplacement(N.getValue("
2402 + utostr(ValNo) + "), " + ChainName + ");");
2403 ValNo++;
2404 }
2405
Evan Cheng97938882005-12-22 02:24:50 +00002406
2407 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002408 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002409 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002410 Code += "CodeGenMap[" + FoldedChains[j].first + ".getValue(" +
2411 utostr(FoldedChains[j].second) + ")] = ";
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002412 emitCode(Code + ChainName + ";");
Evan Chenge41bf822006-02-05 06:43:12 +00002413
2414 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2415 std::string Code =
2416 FoldedChains[j].first + ".getValue(" +
2417 utostr(FoldedChains[j].second) + ")";
2418 emitCode("AddReplacement(" + Code + ", " + ChainName + ");");
2419 }
Evan Chengb915f312005-12-09 22:45:35 +00002420 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002421
Evan Cheng54597732006-01-26 00:22:25 +00002422 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002423 emitCode("CodeGenMap[N.getValue(" + utostr(ValNo) + ")] = InFlag;");
Evan Cheng97938882005-12-22 02:24:50 +00002424
Evan Cheng54597732006-01-26 00:22:25 +00002425 if (AddedChain && NodeHasOutFlag) {
Evan Cheng823b7522006-01-19 21:57:10 +00002426 if (NumExpectedResults == 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002427 emitCode("return Result.getValue(N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002428 } else {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002429 emitCode("if (N.ResNo < " + utostr(NumExpectedResults) + ")");
2430 emitCode(" return Result.getValue(N.ResNo);");
2431 emitCode("else");
2432 emitCode(" return Result.getValue(N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002433 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002434 } else {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002435 emitCode("return Result.getValue(N.ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002436 }
Evan Chengb915f312005-12-09 22:45:35 +00002437 } else {
2438 // If this instruction is the root, and if there is only one use of it,
2439 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002440 emitCode("if (N.Val->hasOneUse()) {");
2441 std::string Code = " return CurDAG->SelectNodeTo(N.Val, " +
2442 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002443 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002444 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002445 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002446 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002447 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002448 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002449 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002450 Code += ", InFlag";
2451 emitCode(Code + ");");
2452 emitCode("} else {");
2453 Code = " return CodeGenMap[N] = CurDAG->getTargetNode(" +
2454 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002455 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002456 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002457 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002458 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002459 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002460 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng51fecc82006-01-09 18:27:06 +00002461 if (HasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002462 Code += ", InFlag";
2463 emitCode(Code + ");");
2464 emitCode("}");
Evan Chengb915f312005-12-09 22:45:35 +00002465 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002466
Evan Chengb915f312005-12-09 22:45:35 +00002467 return std::make_pair(1, ResNo);
2468 } else if (Op->isSubClassOf("SDNodeXForm")) {
2469 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng58e84a62005-12-14 22:02:59 +00002470 unsigned OpVal = EmitResultCode(N->getChild(0)).second;
Evan Chengb915f312005-12-09 22:45:35 +00002471 unsigned ResNo = TmpNo++;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002472 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2473 + "(Tmp" + utostr(OpVal) + ".Val);");
Evan Chengb915f312005-12-09 22:45:35 +00002474 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002475 emitCode("CodeGenMap[N] = Tmp" +utostr(ResNo) + ";");
2476 emitCode("return Tmp" + utostr(ResNo) + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002477 }
2478 return std::make_pair(1, ResNo);
2479 } else {
2480 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002481 std::cerr << "\n";
2482 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002483 }
2484 }
2485
Chris Lattner488580c2006-01-28 19:06:51 +00002486 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2487 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002488 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2489 /// for, this returns true otherwise false if Pat has all types.
2490 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2491 const std::string &Prefix) {
2492 // Did we find one?
2493 if (!Pat->hasTypeSet()) {
2494 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002495 Pat->setTypes(Other->getExtTypes());
Chris Lattner67a202b2006-01-28 20:43:52 +00002496 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002497 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002498 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002499 }
2500
Evan Cheng51fecc82006-01-09 18:27:06 +00002501 unsigned OpNo =
2502 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002503 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2504 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2505 Prefix + utostr(OpNo)))
2506 return true;
2507 return false;
2508 }
2509
2510private:
Evan Cheng54597732006-01-26 00:22:25 +00002511 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002512 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002513 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2514 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002515 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002516 unsigned OpNo =
2517 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002518 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2519 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002520 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2521 TreePatternNode *Child = N->getChild(i);
2522 if (!Child->isLeaf()) {
Evan Cheng54597732006-01-26 00:22:25 +00002523 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002524 } else {
2525 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002526 if (!Child->getName().empty()) {
2527 std::string Name = RootName + utostr(OpNo);
2528 if (Duplicates.find(Name) != Duplicates.end())
2529 // A duplicate! Do not emit a copy for this node.
2530 continue;
2531 }
2532
Evan Chengb915f312005-12-09 22:45:35 +00002533 Record *RR = DI->getDef();
2534 if (RR->isSubClassOf("Register")) {
2535 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002536 if (RVT == MVT::Flag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002537 emitCode("InFlag = Select(" + RootName + utostr(OpNo) + ");");
Evan Chengb2c6d492006-01-11 22:16:13 +00002538 } else {
2539 if (!ChainEmitted) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002540 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002541 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002542 ChainEmitted = true;
2543 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002544 emitCode("SDOperand " + RootName + "CR" + utostr(i) + ";");
2545 emitCode(RootName + "CR" + utostr(i) +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002546 " = CurDAG->getCopyToReg(" + ChainName +
2547 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2548 ", MVT::" + getEnumName(RVT) + "), Select(" + RootName +
2549 utostr(OpNo) + "), InFlag);");
2550 emitCode(ChainName + " = " + RootName + "CR" + utostr(i) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002551 ".getValue(0);");
2552 emitCode("InFlag = " + RootName + "CR" + utostr(i) +
2553 ".getValue(1);");
Evan Chengb915f312005-12-09 22:45:35 +00002554 }
2555 }
2556 }
2557 }
2558 }
Evan Cheng54597732006-01-26 00:22:25 +00002559
2560 if (HasInFlag || HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002561 std::string Code;
Evan Cheng54597732006-01-26 00:22:25 +00002562 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002563 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2564 ") {");
2565 Code = " ";
Evan Cheng54597732006-01-26 00:22:25 +00002566 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002567 emitCode(Code + "InFlag = Select(" + RootName + ".getOperand(" +
2568 utostr(OpNo) + "));");
Evan Cheng54597732006-01-26 00:22:25 +00002569 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002570 emitCode(" HasOptInFlag = true;");
2571 emitCode("}");
Evan Cheng54597732006-01-26 00:22:25 +00002572 }
2573 }
Evan Chengb915f312005-12-09 22:45:35 +00002574 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002575
2576 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002577 /// as specified by the instruction. It returns true if any copy is
2578 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002579 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002580 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002581 Record *Op = N->getOperator();
2582 if (Op->isSubClassOf("Instruction")) {
2583 const DAGInstruction &Inst = ISE.getInstruction(Op);
2584 const CodeGenTarget &CGT = ISE.getTargetInfo();
2585 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2586 unsigned NumImpResults = Inst.getNumImpResults();
2587 for (unsigned i = 0; i < NumImpResults; i++) {
2588 Record *RR = Inst.getImpResult(i);
2589 if (RR->isSubClassOf("Register")) {
2590 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2591 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002592 if (!ChainEmitted) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002593 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002594 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002595 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002596 }
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002597 emitCode("Result = CurDAG->getCopyFromReg(" + ChainName + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002598 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
2599 ", InFlag);");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002600 emitCode(ChainName + " = Result.getValue(1);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002601 emitCode("InFlag = Result.getValue(2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002602 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002603 }
2604 }
2605 }
2606 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002607 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002608 }
Evan Chengb915f312005-12-09 22:45:35 +00002609};
2610
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002611/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2612/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00002613/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00002614void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Chenge41bf822006-02-05 06:43:12 +00002615 std::vector<std::pair<bool, std::string> > &GeneratedCode,
2616 bool DoReplace) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002617 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2618 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chenge41bf822006-02-05 06:43:12 +00002619 GeneratedCode, DoReplace);
Evan Chengb915f312005-12-09 22:45:35 +00002620
Chris Lattner8fc35682005-09-23 23:16:51 +00002621 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002622 bool FoundChain = false;
Evan Chenge41bf822006-02-05 06:43:12 +00002623 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002624
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002625 // TP - Get *SOME* tree pattern, we don't care which.
2626 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002627
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002628 // At this point, we know that we structurally match the pattern, but the
2629 // types of the nodes may not match. Figure out the fewest number of type
2630 // comparisons we need to emit. For example, if there is only one integer
2631 // type supported by a target, there should be no type comparisons at all for
2632 // integer patterns!
2633 //
2634 // To figure out the fewest number of type checks needed, clone the pattern,
2635 // remove the types, then perform type inference on the pattern as a whole.
2636 // If there are unresolved types, emit an explicit check for those types,
2637 // apply the type to the tree, then rerun type inference. Iterate until all
2638 // types are resolved.
2639 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002640 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002641 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002642
2643 do {
2644 // Resolve/propagate as many types as possible.
2645 try {
2646 bool MadeChange = true;
2647 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00002648 MadeChange = Pat->ApplyTypeConstraints(TP,
2649 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00002650 } catch (...) {
2651 assert(0 && "Error: could not find consistent types for something we"
2652 " already decided was ok!");
2653 abort();
2654 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002655
Chris Lattner7e82f132005-10-15 21:34:21 +00002656 // Insert a check for an unresolved type and add it to the tree. If we find
2657 // an unresolved type to add a check for, this returns true and we iterate,
2658 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002659 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002660
Evan Cheng58e84a62005-12-14 22:02:59 +00002661 Emitter.EmitResultCode(Pattern.getDstPattern(), true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002662 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00002663}
2664
Chris Lattner24e00a42006-01-29 04:41:05 +00002665/// EraseCodeLine - Erase one code line from all of the patterns. If removing
2666/// a line causes any of them to be empty, remove them and return true when
2667/// done.
2668static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2669 std::vector<std::pair<bool, std::string> > > >
2670 &Patterns) {
2671 bool ErasedPatterns = false;
2672 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2673 Patterns[i].second.pop_back();
2674 if (Patterns[i].second.empty()) {
2675 Patterns.erase(Patterns.begin()+i);
2676 --i; --e;
2677 ErasedPatterns = true;
2678 }
2679 }
2680 return ErasedPatterns;
2681}
2682
Chris Lattner8bc74722006-01-29 04:25:26 +00002683/// EmitPatterns - Emit code for at least one pattern, but try to group common
2684/// code together between the patterns.
2685void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
2686 std::vector<std::pair<bool, std::string> > > >
2687 &Patterns, unsigned Indent,
2688 std::ostream &OS) {
2689 typedef std::pair<bool, std::string> CodeLine;
2690 typedef std::vector<CodeLine> CodeList;
2691 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2692
2693 if (Patterns.empty()) return;
2694
Chris Lattner24e00a42006-01-29 04:41:05 +00002695 // Figure out how many patterns share the next code line. Explicitly copy
2696 // FirstCodeLine so that we don't invalidate a reference when changing
2697 // Patterns.
2698 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00002699 unsigned LastMatch = Patterns.size()-1;
2700 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2701 --LastMatch;
2702
2703 // If not all patterns share this line, split the list into two pieces. The
2704 // first chunk will use this line, the second chunk won't.
2705 if (LastMatch != 0) {
2706 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2707 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2708
2709 // FIXME: Emit braces?
2710 if (Shared.size() == 1) {
2711 PatternToMatch &Pattern = *Shared.back().first;
2712 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2713 Pattern.getSrcPattern()->print(OS);
2714 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2715 Pattern.getDstPattern()->print(OS);
2716 OS << "\n";
2717 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2718 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
2719 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2720 }
2721 if (!FirstCodeLine.first) {
2722 OS << std::string(Indent, ' ') << "{\n";
2723 Indent += 2;
2724 }
2725 EmitPatterns(Shared, Indent, OS);
2726 if (!FirstCodeLine.first) {
2727 Indent -= 2;
2728 OS << std::string(Indent, ' ') << "}\n";
2729 }
2730
2731 if (Other.size() == 1) {
2732 PatternToMatch &Pattern = *Other.back().first;
2733 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2734 Pattern.getSrcPattern()->print(OS);
2735 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2736 Pattern.getDstPattern()->print(OS);
2737 OS << "\n";
2738 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2739 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
2740 << getResultPatternCost(Pattern.getDstPattern()) << "\n";
2741 }
2742 EmitPatterns(Other, Indent, OS);
2743 return;
2744 }
2745
Chris Lattner24e00a42006-01-29 04:41:05 +00002746 // Remove this code from all of the patterns that share it.
2747 bool ErasedPatterns = EraseCodeLine(Patterns);
2748
Chris Lattner8bc74722006-01-29 04:25:26 +00002749 bool isPredicate = FirstCodeLine.first;
2750
2751 // Otherwise, every pattern in the list has this line. Emit it.
2752 if (!isPredicate) {
2753 // Normal code.
2754 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2755 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00002756 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2757
2758 // If the next code line is another predicate, and if all of the pattern
2759 // in this group share the same next line, emit it inline now. Do this
2760 // until we run out of common predicates.
2761 while (!ErasedPatterns && Patterns.back().second.back().first) {
2762 // Check that all of fhe patterns in Patterns end with the same predicate.
2763 bool AllEndWithSamePredicate = true;
2764 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2765 if (Patterns[i].second.back() != Patterns.back().second.back()) {
2766 AllEndWithSamePredicate = false;
2767 break;
2768 }
2769 // If all of the predicates aren't the same, we can't share them.
2770 if (!AllEndWithSamePredicate) break;
2771
2772 // Otherwise we can. Emit it shared now.
2773 OS << " &&\n" << std::string(Indent+4, ' ')
2774 << Patterns.back().second.back().second;
2775 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00002776 }
Chris Lattner24e00a42006-01-29 04:41:05 +00002777
2778 OS << ") {\n";
2779 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00002780 }
2781
2782 EmitPatterns(Patterns, Indent, OS);
2783
2784 if (isPredicate)
2785 OS << std::string(Indent-2, ' ') << "}\n";
2786}
2787
2788
Chris Lattner37481472005-09-26 21:59:35 +00002789
2790namespace {
2791 /// CompareByRecordName - An ordering predicate that implements less-than by
2792 /// comparing the names records.
2793 struct CompareByRecordName {
2794 bool operator()(const Record *LHS, const Record *RHS) const {
2795 // Sort by name first.
2796 if (LHS->getName() < RHS->getName()) return true;
2797 // If both names are equal, sort by pointer.
2798 return LHS->getName() == RHS->getName() && LHS < RHS;
2799 }
2800 };
2801}
2802
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002803void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002804 std::string InstNS = Target.inst_begin()->second.Namespace;
2805 if (!InstNS.empty()) InstNS += "::";
2806
Chris Lattner602f6922006-01-04 00:25:00 +00002807 // Group the patterns by their top-level opcodes.
2808 std::map<Record*, std::vector<PatternToMatch*>,
2809 CompareByRecordName> PatternsByOpcode;
2810 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2811 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
2812 if (!Node->isLeaf()) {
2813 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
2814 } else {
2815 const ComplexPattern *CP;
2816 if (IntInit *II =
2817 dynamic_cast<IntInit*>(Node->getLeafValue())) {
2818 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
2819 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
2820 std::vector<Record*> OpNodes = CP->getRootNodes();
2821 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00002822 PatternsByOpcode[OpNodes[j]]
2823 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00002824 }
2825 } else {
2826 std::cerr << "Unrecognized opcode '";
2827 Node->dump();
2828 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00002829 std::cerr <<
2830 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00002831 std::cerr << "'!\n";
2832 exit(1);
2833 }
2834 }
2835 }
2836
2837 // Emit one Select_* method for each top-level opcode. We do this instead of
2838 // emitting one giant switch statement to support compilers where this will
2839 // result in the recursive functions taking less stack space.
2840 for (std::map<Record*, std::vector<PatternToMatch*>,
2841 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
2842 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00002843 const std::string &OpName = PBOI->first->getName();
2844 OS << "SDOperand Select_" << OpName << "(SDOperand N) {\n";
Chris Lattner602f6922006-01-04 00:25:00 +00002845
2846 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Evan Chenge41bf822006-02-05 06:43:12 +00002847 bool OptSlctOrder =
2848 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
2849 OpcodeInfo.getNumResults() > 0);
2850
2851 if (OptSlctOrder) {
2852 OS << " SDOperand RetVal;\n";
2853 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
2854 << " && N.getValue(0).hasOneUse()) {\n"
2855 << " SDOperand Dummy = "
2856 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
2857 << " CodeGenMap[N.getValue(" << OpcodeInfo.getNumResults()
2858 << ")] = Dummy;\n"
2859 << " HolderMap[N.getValue(" << OpcodeInfo.getNumResults()
2860 << ")] = Dummy;\n"
2861 << " return Dummy;\n"
2862 << " }\n";
2863 }
2864
Chris Lattner602f6922006-01-04 00:25:00 +00002865 std::vector<PatternToMatch*> &Patterns = PBOI->second;
Chris Lattner355408b2006-01-29 02:43:35 +00002866 assert(!Patterns.empty() && "No patterns but map has entry?");
Chris Lattner602f6922006-01-04 00:25:00 +00002867
2868 // We want to emit all of the matching code now. However, we want to emit
2869 // the matches in order of minimal cost. Sort the patterns so the least
2870 // cost one is at the start.
2871 std::stable_sort(Patterns.begin(), Patterns.end(),
2872 PatternSortingPredicate(*this));
2873
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002874 typedef std::vector<std::pair<bool, std::string> > CodeList;
2875
2876 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002877 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002878 CodeList GeneratedCode;
Evan Chenge41bf822006-02-05 06:43:12 +00002879 GenerateCodeForPattern(*Patterns[i], GeneratedCode, OptSlctOrder);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002880 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
2881 }
2882
2883 // Scan the code to see if all of the patterns are reachable and if it is
2884 // possible that the last one might not match.
2885 bool mightNotMatch = true;
2886 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2887 CodeList &GeneratedCode = CodeForPatterns[i].second;
2888 mightNotMatch = false;
Chris Lattner355408b2006-01-29 02:43:35 +00002889
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002890 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
2891 if (GeneratedCode[j].first) { // predicate.
2892 mightNotMatch = true;
2893 break;
2894 }
2895 }
Chris Lattner355408b2006-01-29 02:43:35 +00002896
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002897 // If this pattern definitely matches, and if it isn't the last one, the
2898 // patterns after it CANNOT ever match. Error out.
2899 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
2900 std::cerr << "Pattern '";
2901 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
2902 std::cerr << "' is impossible to select!\n";
2903 exit(1);
2904 }
2905 }
Chris Lattner8bc74722006-01-29 04:25:26 +00002906
2907 // Loop through and reverse all of the CodeList vectors, as we will be
2908 // accessing them from their logical front, but accessing the end of a
2909 // vector is more efficient.
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002910 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
2911 CodeList &GeneratedCode = CodeForPatterns[i].second;
Chris Lattner8bc74722006-01-29 04:25:26 +00002912 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002913 }
Chris Lattner602f6922006-01-04 00:25:00 +00002914
Chris Lattner8bc74722006-01-29 04:25:26 +00002915 // Next, reverse the list of patterns itself for the same reason.
2916 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
2917
2918 // Emit all of the patterns now, grouped together to share code.
2919 EmitPatterns(CodeForPatterns, 2, OS);
2920
Chris Lattner2bd4dd72006-01-29 02:57:39 +00002921 // If the last pattern has predicates (which could fail) emit code to catch
2922 // the case where nothing handles a pattern.
Chris Lattner355408b2006-01-29 02:43:35 +00002923 if (mightNotMatch)
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002924 OS << " std::cerr << \"Cannot yet select: \";\n"
2925 << " N.Val->dump(CurDAG);\n"
2926 << " std::cerr << '\\n';\n"
2927 << " abort();\n";
2928
2929 OS << "}\n\n";
Chris Lattner602f6922006-01-04 00:25:00 +00002930 }
2931
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002932 // Emit boilerplate.
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00002933 OS << "SDOperand Select_INLINEASM(SDOperand N) {\n"
2934 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
2935 << " Ops[0] = Select(N.getOperand(0)); // Select the chain.\n\n"
2936 << " // Select the flag operand.\n"
2937 << " if (Ops.back().getValueType() == MVT::Flag)\n"
2938 << " Ops.back() = Select(Ops.back());\n"
2939 << " std::vector<MVT::ValueType> VTs;\n"
2940 << " VTs.push_back(MVT::Other);\n"
2941 << " VTs.push_back(MVT::Flag);\n"
2942 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
2943 << " CodeGenMap[N.getValue(0)] = New;\n"
2944 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2945 << " return New.getValue(N.ResNo);\n"
2946 << "}\n\n";
2947
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002948 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002949 << "SDOperand SelectCode(SDOperand N) {\n"
2950 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00002951 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
2952 << "INSTRUCTION_LIST_END))\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002953 << " return N; // Already selected.\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002954 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng481c8e02005-12-12 23:22:48 +00002955 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002956 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002957 << " default: break;\n"
2958 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00002959 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00002960 << " case ISD::Register:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00002961 << " case ISD::TargetConstant:\n"
2962 << " case ISD::TargetConstantPool:\n"
2963 << " case ISD::TargetFrameIndex:\n"
2964 << " case ISD::TargetGlobalAddress:\n"
Chris Lattner547394c2005-09-23 21:53:45 +00002965 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002966 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00002967 << " case ISD::AssertZext: {\n"
2968 << " SDOperand Tmp0 = Select(N.getOperand(0));\n"
2969 << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp0;\n"
2970 << " return Tmp0;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00002971 << " }\n"
2972 << " case ISD::TokenFactor:\n"
2973 << " if (N.getNumOperands() == 2) {\n"
2974 << " SDOperand Op0 = Select(N.getOperand(0));\n"
2975 << " SDOperand Op1 = Select(N.getOperand(1));\n"
2976 << " return CodeGenMap[N] =\n"
2977 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
2978 << " } else {\n"
2979 << " std::vector<SDOperand> Ops;\n"
2980 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2981 << " Ops.push_back(Select(N.getOperand(i)));\n"
2982 << " return CodeGenMap[N] = \n"
2983 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
2984 << " }\n"
2985 << " case ISD::CopyFromReg: {\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002986 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002987 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
2988 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002989 << " if (N.Val->getNumValues() == 2) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00002990 << " if (Chain == N.getOperand(0)) return N; // No change\n"
2991 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
2992 << " CodeGenMap[N.getValue(0)] = New;\n"
2993 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
2994 << " return New.getValue(N.ResNo);\n"
2995 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00002996 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00002997 << " if (N.getNumOperands() == 3) Flag = Select(N.getOperand(2));\n"
2998 << " if (Chain == N.getOperand(0) &&\n"
2999 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2)))\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003000 << " return N; // No change\n"
3001 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3002 << " CodeGenMap[N.getValue(0)] = New;\n"
3003 << " CodeGenMap[N.getValue(1)] = New.getValue(1);\n"
3004 << " CodeGenMap[N.getValue(2)] = New.getValue(2);\n"
3005 << " return New.getValue(N.ResNo);\n"
3006 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003007 << " }\n"
3008 << " case ISD::CopyToReg: {\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00003009 << " SDOperand Chain = Select(N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003010 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003011 << " SDOperand Val = Select(N.getOperand(2));\n"
Chris Lattner4e3c8e512006-01-03 22:55:16 +00003012 << " SDOperand Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003013 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003014 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003015 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003016 << " return CodeGenMap[N] = Result;\n"
3017 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003018 << " SDOperand Flag(0, 0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003019 << " if (N.getNumOperands() == 4) Flag = Select(N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003020 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003021 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3022 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003023 << " CodeGenMap[N.getValue(0)] = Result;\n"
3024 << " CodeGenMap[N.getValue(1)] = Result.getValue(1);\n"
3025 << " return Result.getValue(N.ResNo);\n"
3026 << " }\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003027 << " }\n"
3028 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n";
3029
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003030
Chris Lattner602f6922006-01-04 00:25:00 +00003031 // Loop over all of the case statements, emiting a call to each method we
3032 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003033 for (std::map<Record*, std::vector<PatternToMatch*>,
3034 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3035 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003036 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00003037 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00003038 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Chris Lattner602f6922006-01-04 00:25:00 +00003039 << "return Select_" << PBOI->first->getName() << "(N);\n";
Chris Lattner81303322005-09-23 19:36:15 +00003040 }
Chris Lattner81303322005-09-23 19:36:15 +00003041
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003042 OS << " } // end of big switch.\n\n"
3043 << " std::cerr << \"Cannot yet select: \";\n"
Evan Cheng97938882005-12-22 02:24:50 +00003044 << " N.Val->dump(CurDAG);\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003045 << " std::cerr << '\\n';\n"
3046 << " abort();\n"
3047 << "}\n";
3048}
3049
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003050void DAGISelEmitter::run(std::ostream &OS) {
3051 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3052 " target", OS);
3053
Chris Lattner1f39e292005-09-14 00:09:24 +00003054 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3055 << "// *** instruction selector class. These functions are really "
3056 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003057
Chris Lattner296dfe32005-09-24 00:50:51 +00003058 OS << "// Instance var to keep track of multiply used nodes that have \n"
3059 << "// already been selected.\n"
3060 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003061
3062 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3063 << "// and their place holder nodes.\n";
3064 OS << "std::map<SDOperand, SDOperand> HolderMap;\n";
3065 OS << "// Instance var to keep track of mapping of place holder nodes\n"
3066 << "// and their replacement nodes.\n";
3067 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3068
3069 OS << "\n";
3070 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3071 << "std::set<SDNode *> &Visited) {\n";
3072 OS << " if (found || !Visited.insert(Use).second) return;\n";
3073 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3074 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3075 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3076 OS << " if (N != Def) {\n";
3077 OS << " findNonImmUse(N, Def, found, Visited);\n";
3078 OS << " } else {\n";
3079 OS << " found = true;\n";
3080 OS << " break;\n";
3081 OS << " }\n";
3082 OS << " }\n";
3083 OS << " }\n";
3084 OS << "}\n";
3085
3086 OS << "\n";
3087 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3088 OS << " std::set<SDNode *> Visited;\n";
3089 OS << " bool found = false;\n";
3090 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3091 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3092 OS << " if (N != Def) {\n";
3093 OS << " findNonImmUse(N, Def, found, Visited);\n";
3094 OS << " if (found) break;\n";
3095 OS << " }\n";
3096 OS << " }\n";
3097 OS << " return found;\n";
3098 OS << "}\n";
3099
3100 OS << "\n";
3101 OS << "// AddReplacement - Note the pending replacement node for a\n"
3102 << "// holder node in ReplaceMap.\n";
3103 OS << "void AddReplacement(SDOperand N, SDOperand R) {\n";
3104 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HolderMap.find(N);\n";
3105 OS << " if (HMI != HolderMap.end()) {\n";
3106 OS << " ReplaceMap[HMI->second] = R;\n";
3107 OS << " HolderMap.erase(N);\n";
3108 OS << " }\n";
3109 OS << "}\n";
3110
3111 OS << "\n";
3112 OS << "// ReplaceHolders - Replace all the holders with the real target\n";
3113 OS << "// specific nodes.\n";
3114 OS << "void ReplaceHolders() {\n";
3115 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3116 << "ReplaceMap.begin(),\n"
3117 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3118 OS << " SDOperand From = I->first;\n";
3119 OS << " SDOperand To = I->second;\n";
3120 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3121 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3122 OS << " SDNode *Use = *UI;\n";
3123 OS << " std::vector<SDOperand> Ops;\n";
3124 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3125 OS << " SDOperand O = Use->getOperand(i);\n";
3126 OS << " if (O.Val == From.Val)\n";
3127 OS << " Ops.push_back(To);\n";
3128 OS << " else\n";
3129 OS << " Ops.push_back(O);\n";
3130 OS << " }\n";
3131 OS << " SDOperand U = SDOperand(Use, 0);\n";
3132 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3133 OS << " }\n";
3134 OS << " }\n";
3135 OS << "}\n";
3136
3137 OS << "\n";
3138 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3139 OS << "SDOperand SelectRoot(SDOperand N) {\n";
3140 OS << " SDOperand RetVal = Select(N);\n";
3141 OS << " ReplaceHolders();\n";
3142 OS << " ReplaceMap.clear();\n";
3143 OS << " return RetVal;\n";
3144 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003145
Chris Lattnerca559d02005-09-08 21:03:01 +00003146 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003147 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003148 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003149 ParsePatternFragments(OS);
3150 ParseInstructions();
3151 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003152
Chris Lattnere97603f2005-09-28 19:27:25 +00003153 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003154 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003155 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003156
Chris Lattnere46e17b2005-09-29 19:28:10 +00003157
3158 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3159 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003160 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3161 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003162 std::cerr << "\n";
3163 });
3164
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003165 // At this point, we have full information about the 'Patterns' we need to
3166 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003167 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003168 EmitInstructionSelector(OS);
3169
3170 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3171 E = PatternFragments.end(); I != E; ++I)
3172 delete I->second;
3173 PatternFragments.clear();
3174
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003175 Instructions.clear();
3176}