blob: 58f217e8f2a17244d19f1679cdc65d696366259a [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000018#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000019#include <set>
20using namespace llvm;
21
Chris Lattnerca559d02005-09-08 21:03:01 +000022//===----------------------------------------------------------------------===//
Chris Lattner3c7e18d2005-10-14 06:12:03 +000023// Helpers for working with extended types.
24
25/// FilterVTs - Filter a list of VT's according to a predicate.
26///
27template<typename T>
28static std::vector<MVT::ValueType>
29FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
32 if (Filter(InVTs[i]))
33 Result.push_back(InVTs[i]);
34 return Result;
35}
36
Nate Begemanb73628b2005-12-30 00:12:56 +000037template<typename T>
38static std::vector<unsigned char>
39FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40 std::vector<unsigned char> Result;
41 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42 if (Filter((MVT::ValueType)InVTs[i]))
43 Result.push_back(InVTs[i]);
44 return Result;
Chris Lattner3c7e18d2005-10-14 06:12:03 +000045}
46
Nate Begemanb73628b2005-12-30 00:12:56 +000047static std::vector<unsigned char>
48ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49 std::vector<unsigned char> Result;
50 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51 Result.push_back(InVTs[i]);
52 return Result;
53}
54
55static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56 const std::vector<unsigned char> &RHS) {
57 if (LHS.size() > RHS.size()) return false;
58 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
Duraid Madinad47ae092005-12-30 16:41:48 +000059 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
Nate Begemanb73628b2005-12-30 00:12:56 +000060 return false;
61 return true;
62}
63
64/// isExtIntegerVT - Return true if the specified extended value type vector
65/// contains isInt or an integer value type.
Chris Lattner697f8842006-03-20 05:39:48 +000066static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000067 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
69}
70
71/// isExtFloatingPointVT - Return true if the specified extended value type
72/// vector contains isFP or a FP value type.
Chris Lattner697f8842006-03-20 05:39:48 +000073static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
Nate Begemanb73628b2005-12-30 00:12:56 +000074 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
Chris Lattner488580c2006-01-28 19:06:51 +000075 return EVTs[0] == MVT::isFP ||
76 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
Chris Lattner3c7e18d2005-10-14 06:12:03 +000077}
78
79//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000080// SDTypeConstraint implementation
81//
82
83SDTypeConstraint::SDTypeConstraint(Record *R) {
84 OperandNo = R->getValueAsInt("OperandNum");
85
86 if (R->isSubClassOf("SDTCisVT")) {
87 ConstraintType = SDTCisVT;
88 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattner5b21be72005-12-09 22:57:42 +000089 } else if (R->isSubClassOf("SDTCisPtrTy")) {
90 ConstraintType = SDTCisPtrTy;
Chris Lattner33c92e92005-09-08 21:27:15 +000091 } else if (R->isSubClassOf("SDTCisInt")) {
92 ConstraintType = SDTCisInt;
93 } else if (R->isSubClassOf("SDTCisFP")) {
94 ConstraintType = SDTCisFP;
95 } else if (R->isSubClassOf("SDTCisSameAs")) {
96 ConstraintType = SDTCisSameAs;
97 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99 ConstraintType = SDTCisVTSmallerThanOp;
100 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
101 R->getValueAsInt("OtherOperandNum");
Chris Lattner03ebd802005-10-14 04:53:53 +0000102 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103 ConstraintType = SDTCisOpSmallerThanOp;
104 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
105 R->getValueAsInt("BigOperandNum");
Chris Lattner697f8842006-03-20 05:39:48 +0000106 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107 ConstraintType = SDTCisIntVectorOfSameSize;
108 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109 R->getValueAsInt("OtherOpNum");
Chris Lattner33c92e92005-09-08 21:27:15 +0000110 } else {
111 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
112 exit(1);
113 }
114}
115
Chris Lattner32707602005-09-08 23:22:48 +0000116/// getOperandNum - Return the node corresponding to operand #OpNo in tree
117/// N, which has NumResults results.
118TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
119 TreePatternNode *N,
120 unsigned NumResults) const {
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000121 assert(NumResults <= 1 &&
122 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000123
124 if (OpNo < NumResults)
125 return N; // FIXME: need value #
126 else
127 return N->getChild(OpNo-NumResults);
128}
129
130/// ApplyTypeConstraint - Given a node in a pattern, apply this type
131/// constraint to the nodes operands. This returns true if it makes a
132/// change, false otherwise. If a type contradiction is found, throw an
133/// exception.
134bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
135 const SDNodeInfo &NodeInfo,
136 TreePattern &TP) const {
137 unsigned NumResults = NodeInfo.getNumResults();
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000138 assert(NumResults <= 1 &&
139 "We only work with nodes with zero or one result so far!");
Chris Lattner32707602005-09-08 23:22:48 +0000140
141 // Check that the number of operands is sane.
142 if (NodeInfo.getNumOperands() >= 0) {
143 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
144 TP.error(N->getOperator()->getName() + " node requires exactly " +
145 itostr(NodeInfo.getNumOperands()) + " operands!");
146 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000147
148 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
Chris Lattner32707602005-09-08 23:22:48 +0000149
150 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
151
152 switch (ConstraintType) {
153 default: assert(0 && "Unknown constraint type!");
154 case SDTCisVT:
155 // Operand must be a particular type.
156 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
Chris Lattner5b21be72005-12-09 22:57:42 +0000157 case SDTCisPtrTy: {
158 // Operand must be same as target pointer type.
159 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
160 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000161 case SDTCisInt: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000162 // If there is only one integer type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000163 std::vector<MVT::ValueType> IntVTs =
164 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000165
166 // If we found exactly one supported integer type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000167 if (IntVTs.size() == 1)
168 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000169 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000170 }
171 case SDTCisFP: {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000172 // If there is only one FP type supported, this must be it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000173 std::vector<MVT::ValueType> FPVTs =
174 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000175
176 // If we found exactly one supported FP type, apply it.
Chris Lattnere0583b12005-10-14 05:08:37 +0000177 if (FPVTs.size() == 1)
178 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000179 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000180 }
Chris Lattner32707602005-09-08 23:22:48 +0000181 case SDTCisSameAs: {
182 TreePatternNode *OtherNode =
183 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
Nate Begemanb73628b2005-12-30 00:12:56 +0000184 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
185 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000186 }
187 case SDTCisVTSmallerThanOp: {
188 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
189 // have an integer type that is smaller than the VT.
190 if (!NodeToApply->isLeaf() ||
191 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
192 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
193 ->isSubClassOf("ValueType"))
194 TP.error(N->getOperator()->getName() + " expects a VT operand!");
195 MVT::ValueType VT =
196 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
197 if (!MVT::isInteger(VT))
198 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
199
200 TreePatternNode *OtherNode =
201 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000202
203 // It must be integer.
204 bool MadeChange = false;
205 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
206
Nate Begemanb73628b2005-12-30 00:12:56 +0000207 // This code only handles nodes that have one type set. Assert here so
208 // that we can change this if we ever need to deal with multiple value
209 // types at this point.
210 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
211 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Chris Lattner32707602005-09-08 23:22:48 +0000212 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
213 return false;
214 }
Chris Lattner03ebd802005-10-14 04:53:53 +0000215 case SDTCisOpSmallerThanOp: {
Chris Lattner603d78c2005-10-14 06:25:00 +0000216 TreePatternNode *BigOperand =
217 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
218
219 // Both operands must be integer or FP, but we don't care which.
220 bool MadeChange = false;
221
Nate Begemanb73628b2005-12-30 00:12:56 +0000222 // This code does not currently handle nodes which have multiple types,
223 // where some types are integer, and some are fp. Assert that this is not
224 // the case.
225 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
226 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
227 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
228 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
229 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
230 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000231 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000232 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000233 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000234 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000235 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
Nate Begemanb73628b2005-12-30 00:12:56 +0000236 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Chris Lattner603d78c2005-10-14 06:25:00 +0000237 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
238
239 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
240
Nate Begemanb73628b2005-12-30 00:12:56 +0000241 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000242 VTs = FilterVTs(VTs, MVT::isInteger);
Nate Begemanb73628b2005-12-30 00:12:56 +0000243 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Chris Lattner603d78c2005-10-14 06:25:00 +0000244 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
245 } else {
246 VTs.clear();
247 }
248
249 switch (VTs.size()) {
250 default: // Too many VT's to pick from.
251 case 0: break; // No info yet.
252 case 1:
253 // Only one VT of this flavor. Cannot ever satisify the constraints.
254 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
255 case 2:
256 // If we have exactly two possible types, the little operand must be the
257 // small one, the big operand should be the big one. Common with
258 // float/double for example.
259 assert(VTs[0] < VTs[1] && "Should be sorted!");
260 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
261 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
262 break;
263 }
264 return MadeChange;
Chris Lattner03ebd802005-10-14 04:53:53 +0000265 }
Chris Lattner697f8842006-03-20 05:39:48 +0000266 case SDTCisIntVectorOfSameSize: {
267 TreePatternNode *OtherOperand =
268 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
269 N, NumResults);
270 if (OtherOperand->hasTypeSet()) {
271 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
272 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
273 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
274 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
275 return NodeToApply->UpdateNodeType(IVT, TP);
276 }
277 return false;
278 }
Chris Lattner32707602005-09-08 23:22:48 +0000279 }
280 return false;
281}
282
283
Chris Lattner33c92e92005-09-08 21:27:15 +0000284//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000285// SDNodeInfo implementation
286//
287SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
288 EnumName = R->getValueAsString("Opcode");
289 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000290 Record *TypeProfile = R->getValueAsDef("TypeProfile");
291 NumResults = TypeProfile->getValueAsInt("NumResults");
292 NumOperands = TypeProfile->getValueAsInt("NumOperands");
293
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000294 // Parse the properties.
295 Properties = 0;
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000296 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
Chris Lattner6bc0d742005-10-28 22:43:25 +0000297 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
298 if (PropList[i]->getName() == "SDNPCommutative") {
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000299 Properties |= 1 << SDNPCommutative;
Chris Lattner6bc0d742005-10-28 22:43:25 +0000300 } else if (PropList[i]->getName() == "SDNPAssociative") {
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000301 Properties |= 1 << SDNPAssociative;
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000302 } else if (PropList[i]->getName() == "SDNPHasChain") {
303 Properties |= 1 << SDNPHasChain;
Evan Cheng51fecc82006-01-09 18:27:06 +0000304 } else if (PropList[i]->getName() == "SDNPOutFlag") {
305 Properties |= 1 << SDNPOutFlag;
306 } else if (PropList[i]->getName() == "SDNPInFlag") {
307 Properties |= 1 << SDNPInFlag;
308 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
309 Properties |= 1 << SDNPOptInFlag;
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000310 } else {
Chris Lattner6bc0d742005-10-28 22:43:25 +0000311 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
Chris Lattnera1a68ae2005-09-28 18:28:29 +0000312 << "' on node '" << R->getName() << "'!\n";
313 exit(1);
314 }
315 }
316
317
Chris Lattner33c92e92005-09-08 21:27:15 +0000318 // Parse the type constraints.
Chris Lattnerb0e103d2005-10-28 22:49:02 +0000319 std::vector<Record*> ConstraintList =
320 TypeProfile->getValueAsListOfDefs("Constraints");
321 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
Chris Lattnerca559d02005-09-08 21:03:01 +0000322}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000323
324//===----------------------------------------------------------------------===//
325// TreePatternNode implementation
326//
327
328TreePatternNode::~TreePatternNode() {
329#if 0 // FIXME: implement refcounted tree nodes!
330 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
331 delete getChild(i);
332#endif
333}
334
Chris Lattner32707602005-09-08 23:22:48 +0000335/// UpdateNodeType - Set the node type of N to VT if VT contains
336/// information. If N already contains a conflicting type, then throw an
337/// exception. This returns true if any information was updated.
338///
Nate Begemanb73628b2005-12-30 00:12:56 +0000339bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
340 TreePattern &TP) {
341 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
342
343 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
344 return false;
345 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
346 setTypes(ExtVTs);
Chris Lattner32707602005-09-08 23:22:48 +0000347 return true;
348 }
349
Nate Begemanb73628b2005-12-30 00:12:56 +0000350 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
351 assert(hasTypeSet() && "should be handled above!");
352 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
353 if (getExtTypes() == FVTs)
354 return false;
355 setTypes(FVTs);
356 return true;
357 }
358 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
359 assert(hasTypeSet() && "should be handled above!");
Chris Lattner488580c2006-01-28 19:06:51 +0000360 std::vector<unsigned char> FVTs =
361 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
Nate Begemanb73628b2005-12-30 00:12:56 +0000362 if (getExtTypes() == FVTs)
363 return false;
364 setTypes(FVTs);
365 return true;
366 }
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000367
368 // If we know this is an int or fp type, and we are told it is a specific one,
369 // take the advice.
Nate Begemanb73628b2005-12-30 00:12:56 +0000370 //
371 // Similarly, we should probably set the type here to the intersection of
372 // {isInt|isFP} and ExtVTs
373 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
374 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
375 setTypes(ExtVTs);
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000376 return true;
377 }
378
Chris Lattner1531f202005-10-26 16:59:37 +0000379 if (isLeaf()) {
380 dump();
Evan Chengbcecf332005-12-17 01:19:28 +0000381 std::cerr << " ";
Chris Lattner1531f202005-10-26 16:59:37 +0000382 TP.error("Type inference contradiction found in node!");
383 } else {
384 TP.error("Type inference contradiction found in node " +
385 getOperator()->getName() + "!");
386 }
Chris Lattner32707602005-09-08 23:22:48 +0000387 return true; // unreachable
388}
389
390
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000391void TreePatternNode::print(std::ostream &OS) const {
392 if (isLeaf()) {
393 OS << *getLeafValue();
394 } else {
395 OS << "(" << getOperator()->getName();
396 }
397
Nate Begemanb73628b2005-12-30 00:12:56 +0000398 // FIXME: At some point we should handle printing all the value types for
399 // nodes that are multiply typed.
400 switch (getExtTypeNum(0)) {
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000401 case MVT::Other: OS << ":Other"; break;
402 case MVT::isInt: OS << ":isInt"; break;
403 case MVT::isFP : OS << ":isFP"; break;
404 case MVT::isUnknown: ; /*OS << ":?";*/ break;
Nate Begemanb73628b2005-12-30 00:12:56 +0000405 default: OS << ":" << getTypeNum(0); break;
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000406 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000407
408 if (!isLeaf()) {
409 if (getNumChildren() != 0) {
410 OS << " ";
411 getChild(0)->print(OS);
412 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
413 OS << ", ";
414 getChild(i)->print(OS);
415 }
416 }
417 OS << ")";
418 }
419
420 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000421 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000422 if (TransformFn)
423 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000424 if (!getName().empty())
425 OS << ":$" << getName();
426
427}
428void TreePatternNode::dump() const {
429 print(std::cerr);
430}
431
Chris Lattnere46e17b2005-09-29 19:28:10 +0000432/// isIsomorphicTo - Return true if this node is recursively isomorphic to
433/// the specified node. For this comparison, all of the state of the node
434/// is considered, except for the assigned name. Nodes with differing names
435/// that are otherwise identical are considered isomorphic.
436bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
437 if (N == this) return true;
Nate Begemanb73628b2005-12-30 00:12:56 +0000438 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Chris Lattnere46e17b2005-09-29 19:28:10 +0000439 getPredicateFn() != N->getPredicateFn() ||
440 getTransformFn() != N->getTransformFn())
441 return false;
442
443 if (isLeaf()) {
444 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
445 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
446 return DI->getDef() == NDI->getDef();
447 return getLeafValue() == N->getLeafValue();
448 }
449
450 if (N->getOperator() != getOperator() ||
451 N->getNumChildren() != getNumChildren()) return false;
452 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
453 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
454 return false;
455 return true;
456}
457
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000458/// clone - Make a copy of this tree and all of its children.
459///
460TreePatternNode *TreePatternNode::clone() const {
461 TreePatternNode *New;
462 if (isLeaf()) {
463 New = new TreePatternNode(getLeafValue());
464 } else {
465 std::vector<TreePatternNode*> CChildren;
466 CChildren.reserve(Children.size());
467 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
468 CChildren.push_back(getChild(i)->clone());
469 New = new TreePatternNode(getOperator(), CChildren);
470 }
471 New->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000472 New->setTypes(getExtTypes());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000473 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000474 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000475 return New;
476}
477
Chris Lattner32707602005-09-08 23:22:48 +0000478/// SubstituteFormalArguments - Replace the formal arguments in this tree
479/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000480void TreePatternNode::
481SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
482 if (isLeaf()) return;
483
484 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
485 TreePatternNode *Child = getChild(i);
486 if (Child->isLeaf()) {
487 Init *Val = Child->getLeafValue();
488 if (dynamic_cast<DefInit*>(Val) &&
489 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
490 // We found a use of a formal argument, replace it with its value.
491 Child = ArgMap[Child->getName()];
492 assert(Child && "Couldn't find formal argument!");
493 setChild(i, Child);
494 }
495 } else {
496 getChild(i)->SubstituteFormalArguments(ArgMap);
497 }
498 }
499}
500
501
502/// InlinePatternFragments - If this pattern refers to any pattern
503/// fragments, inline them into place, giving us a pattern without any
504/// PatFrag references.
505TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
506 if (isLeaf()) return this; // nothing to do.
507 Record *Op = getOperator();
508
509 if (!Op->isSubClassOf("PatFrag")) {
510 // Just recursively inline children nodes.
511 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
512 setChild(i, getChild(i)->InlinePatternFragments(TP));
513 return this;
514 }
515
516 // Otherwise, we found a reference to a fragment. First, look up its
517 // TreePattern record.
518 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
519
520 // Verify that we are passing the right number of operands.
521 if (Frag->getNumArgs() != Children.size())
522 TP.error("'" + Op->getName() + "' fragment requires " +
523 utostr(Frag->getNumArgs()) + " operands!");
524
Chris Lattner37937092005-09-09 01:15:01 +0000525 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000526
527 // Resolve formal arguments to their actual value.
528 if (Frag->getNumArgs()) {
529 // Compute the map of formal to actual arguments.
530 std::map<std::string, TreePatternNode*> ArgMap;
531 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
532 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
533
534 FragTree->SubstituteFormalArguments(ArgMap);
535 }
536
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000537 FragTree->setName(getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000538 FragTree->UpdateNodeType(getExtTypes(), TP);
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000539
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000540 // Get a new copy of this fragment to stitch into here.
541 //delete this; // FIXME: implement refcounting!
542 return FragTree;
543}
544
Chris Lattner52793e22006-04-06 20:19:52 +0000545/// getImplicitType - Check to see if the specified record has an implicit
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000546/// type which should be applied to it. This infer the type of register
547/// references from the register file information, for example.
548///
Chris Lattner52793e22006-04-06 20:19:52 +0000549static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
Chris Lattner3c7e18d2005-10-14 06:12:03 +0000550 TreePattern &TP) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000551 // Some common return values
552 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
553 std::vector<unsigned char> Other(1, MVT::Other);
554
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000555 // Check to see if this is a register or a register class...
556 if (R->isSubClassOf("RegisterClass")) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000557 if (NotRegisters)
558 return Unknown;
Nate Begeman6510b222005-12-01 04:51:06 +0000559 const CodeGenRegisterClass &RC =
560 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
Nate Begemanb73628b2005-12-30 00:12:56 +0000561 return ConvertVTs(RC.getValueTypes());
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000562 } else if (R->isSubClassOf("PatFrag")) {
563 // Pattern fragment types will be resolved when they are inlined.
Nate Begemanb73628b2005-12-30 00:12:56 +0000564 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000565 } else if (R->isSubClassOf("Register")) {
Evan Cheng37e90052006-01-15 10:04:45 +0000566 if (NotRegisters)
567 return Unknown;
Chris Lattner22faeab2005-12-05 02:36:37 +0000568 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
Evan Cheng44a65fa2006-05-16 07:05:30 +0000569 return T.getRegisterVTs(R);
Chris Lattner1531f202005-10-26 16:59:37 +0000570 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
571 // Using a VTSDNode or CondCodeSDNode.
Nate Begemanb73628b2005-12-30 00:12:56 +0000572 return Other;
Evan Cheng0fc71982005-12-08 02:00:36 +0000573 } else if (R->isSubClassOf("ComplexPattern")) {
Evan Cheng57c517d2006-01-17 07:36:41 +0000574 if (NotRegisters)
575 return Unknown;
Nate Begemanb73628b2005-12-30 00:12:56 +0000576 std::vector<unsigned char>
577 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
578 return ComplexPat;
Evan Cheng01f318b2005-12-14 02:21:57 +0000579 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000580 // Placeholder.
Nate Begemanb73628b2005-12-30 00:12:56 +0000581 return Unknown;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000582 }
583
584 TP.error("Unknown node flavor used in pattern: " + R->getName());
Nate Begemanb73628b2005-12-30 00:12:56 +0000585 return Other;
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000586}
587
Chris Lattner32707602005-09-08 23:22:48 +0000588/// ApplyTypeConstraints - Apply all of the type constraints relevent to
589/// this node and its children in the tree. This returns true if it makes a
590/// change, false otherwise. If a type contradiction is found, throw an
591/// exception.
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000592bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000593 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000594 if (isLeaf()) {
Chris Lattner465c7372005-11-03 05:46:11 +0000595 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000596 // If it's a regclass or something else known, include the type.
Chris Lattner52793e22006-04-06 20:19:52 +0000597 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner465c7372005-11-03 05:46:11 +0000598 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
599 // Int inits are always integers. :)
600 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
601
602 if (hasTypeSet()) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000603 // At some point, it may make sense for this tree pattern to have
604 // multiple types. Assert here that it does not, so we revisit this
605 // code when appropriate.
Evan Cheng44a65fa2006-05-16 07:05:30 +0000606 assert(getExtTypes().size() >= 1 && "TreePattern does not have a type!");
607 MVT::ValueType VT = getTypeNum(0);
608 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
609 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
Nate Begemanb73628b2005-12-30 00:12:56 +0000610
611 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
Chris Lattner465c7372005-11-03 05:46:11 +0000612 // Make sure that the value is representable for this type.
613 if (Size < 32) {
614 int Val = (II->getValue() << (32-Size)) >> (32-Size);
615 if (Val != II->getValue())
616 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
617 "' is out of range for type 'MVT::" +
Nate Begemanb73628b2005-12-30 00:12:56 +0000618 getEnumName(getTypeNum(0)) + "'!");
Chris Lattner465c7372005-11-03 05:46:11 +0000619 }
620 }
621
622 return MadeChange;
623 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000624 return false;
625 }
Chris Lattner32707602005-09-08 23:22:48 +0000626
627 // special handling for set, which isn't really an SDNode.
628 if (getOperator()->getName() == "set") {
629 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000630 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
631 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner32707602005-09-08 23:22:48 +0000632
633 // Types of operands must match.
Nate Begemanb73628b2005-12-30 00:12:56 +0000634 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
635 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
Chris Lattner32707602005-09-08 23:22:48 +0000636 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
637 return MadeChange;
Chris Lattner5a1df382006-03-24 23:10:39 +0000638 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
639 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
640 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
641 unsigned IID =
642 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
643 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
644 bool MadeChange = false;
645
646 // Apply the result type to the node.
647 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
648
649 if (getNumChildren() != Int.ArgVTs.size())
Chris Lattner2c4e65d2006-03-27 22:21:18 +0000650 TP.error("Intrinsic '" + Int.Name + "' expects " +
Chris Lattner5a1df382006-03-24 23:10:39 +0000651 utostr(Int.ArgVTs.size()-1) + " operands, not " +
652 utostr(getNumChildren()-1) + " operands!");
653
654 // Apply type info to the intrinsic ID.
655 MVT::ValueType PtrTy = ISE.getTargetInfo().getPointerType();
656 MadeChange |= getChild(0)->UpdateNodeType(PtrTy, TP);
657
658 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
659 MVT::ValueType OpVT = Int.ArgVTs[i];
660 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
661 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
662 }
663 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000664 } else if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000665 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
Chris Lattnerabbb6052005-09-15 21:42:00 +0000666
667 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
668 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000669 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000670 // Branch, etc. do not produce results and top-level forms in instr pattern
671 // must have void types.
672 if (NI.getNumResults() == 0)
673 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner91ded082006-04-06 20:36:51 +0000674
675 // If this is a vector_shuffle operation, apply types to the build_vector
676 // operation. The types of the integers don't matter, but this ensures they
677 // won't get checked.
678 if (getOperator()->getName() == "vector_shuffle" &&
679 getChild(2)->getOperator()->getName() == "build_vector") {
680 TreePatternNode *BV = getChild(2);
681 const std::vector<MVT::ValueType> &LegalVTs
682 = ISE.getTargetInfo().getLegalValueTypes();
683 MVT::ValueType LegalIntVT = MVT::Other;
684 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
685 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
686 LegalIntVT = LegalVTs[i];
687 break;
688 }
689 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
690
691 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
692 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
693 }
Chris Lattnerabbb6052005-09-15 21:42:00 +0000694 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000695 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner5a1df382006-03-24 23:10:39 +0000696 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000697 bool MadeChange = false;
698 unsigned NumResults = Inst.getNumResults();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000699
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000700 assert(NumResults <= 1 &&
701 "Only supports zero or one result instrs!");
Chris Lattnera28aec12005-09-15 22:23:50 +0000702 // Apply the result type to the node
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000703 if (NumResults == 0) {
704 MadeChange = UpdateNodeType(MVT::isVoid, TP);
705 } else {
706 Record *ResultNode = Inst.getResult(0);
707 assert(ResultNode->isSubClassOf("RegisterClass") &&
708 "Operands should be register classes!");
Nate Begemanddb39542005-12-01 00:06:14 +0000709
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000710 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000711 ISE.getTargetInfo().getRegisterClass(ResultNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000712 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000713 }
Chris Lattnera28aec12005-09-15 22:23:50 +0000714
715 if (getNumChildren() != Inst.getNumOperands())
716 TP.error("Instruction '" + getOperator()->getName() + " expects " +
717 utostr(Inst.getNumOperands()) + " operands, not " +
718 utostr(getNumChildren()) + " operands!");
719 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Nate Begemanddb39542005-12-01 00:06:14 +0000720 Record *OperandNode = Inst.getOperand(i);
721 MVT::ValueType VT;
722 if (OperandNode->isSubClassOf("RegisterClass")) {
723 const CodeGenRegisterClass &RC =
Chris Lattner5a1df382006-03-24 23:10:39 +0000724 ISE.getTargetInfo().getRegisterClass(OperandNode);
Nate Begemanb73628b2005-12-30 00:12:56 +0000725 //VT = RC.getValueTypeNum(0);
726 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
727 TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000728 } else if (OperandNode->isSubClassOf("Operand")) {
729 VT = getValueType(OperandNode->getValueAsDef("Type"));
Nate Begemanb73628b2005-12-30 00:12:56 +0000730 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
Nate Begemanddb39542005-12-01 00:06:14 +0000731 } else {
732 assert(0 && "Unknown operand type!");
733 abort();
734 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000735 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnera28aec12005-09-15 22:23:50 +0000736 }
737 return MadeChange;
738 } else {
739 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
740
Evan Chengf26ba692006-03-20 08:09:17 +0000741 // Node transforms always take one operand.
Chris Lattnera28aec12005-09-15 22:23:50 +0000742 if (getNumChildren() != 1)
743 TP.error("Node transform '" + getOperator()->getName() +
744 "' requires one operand!");
Chris Lattner4e2f54d2006-03-21 06:42:58 +0000745
746 // If either the output or input of the xform does not have exact
747 // type info. We assume they must be the same. Otherwise, it is perfectly
748 // legal to transform from one type to a completely different type.
749 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Evan Chengf26ba692006-03-20 08:09:17 +0000750 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
751 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
752 return MadeChange;
753 }
754 return false;
Chris Lattner32707602005-09-08 23:22:48 +0000755 }
Chris Lattner32707602005-09-08 23:22:48 +0000756}
757
Chris Lattnere97603f2005-09-28 19:27:25 +0000758/// canPatternMatch - If it is impossible for this pattern to match on this
759/// target, fill in Reason and return false. Otherwise, return true. This is
760/// used as a santity check for .td files (to prevent people from writing stuff
761/// that can never possibly work), and to prevent the pattern permuter from
762/// generating stuff that is useless.
Chris Lattner7cf2fe62005-09-28 20:58:06 +0000763bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
Chris Lattnere97603f2005-09-28 19:27:25 +0000764 if (isLeaf()) return true;
765
766 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
767 if (!getChild(i)->canPatternMatch(Reason, ISE))
768 return false;
Evan Cheng0fc71982005-12-08 02:00:36 +0000769
Chris Lattner550525e2006-03-24 21:48:51 +0000770 // If this is an intrinsic, handle cases that would make it not match. For
771 // example, if an operand is required to be an immediate.
772 if (getOperator()->isSubClassOf("Intrinsic")) {
773 // TODO:
774 return true;
775 }
776
Chris Lattnere97603f2005-09-28 19:27:25 +0000777 // If this node is a commutative operator, check that the LHS isn't an
778 // immediate.
779 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
780 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
781 // Scan all of the operands of the node and make sure that only the last one
782 // is a constant node.
783 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
784 if (!getChild(i)->isLeaf() &&
785 getChild(i)->getOperator()->getName() == "imm") {
786 Reason = "Immediate value must be on the RHS of commutative operators!";
787 return false;
788 }
789 }
790
791 return true;
792}
Chris Lattner32707602005-09-08 23:22:48 +0000793
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000794//===----------------------------------------------------------------------===//
795// TreePattern implementation
796//
797
Chris Lattneredbd8712005-10-21 01:19:59 +0000798TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000799 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000800 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000801 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
802 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000803}
804
Chris Lattneredbd8712005-10-21 01:19:59 +0000805TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000806 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000807 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000808 Trees.push_back(ParseTreePattern(Pat));
809}
810
Chris Lattneredbd8712005-10-21 01:19:59 +0000811TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnera28aec12005-09-15 22:23:50 +0000812 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattneredbd8712005-10-21 01:19:59 +0000813 isInputPattern = isInput;
Chris Lattnera28aec12005-09-15 22:23:50 +0000814 Trees.push_back(Pat);
815}
816
817
818
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000819void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000820 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000821 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000822}
823
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000824TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
Chris Lattner8c063182006-03-30 22:50:40 +0000825 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
826 if (!OpDef) error("Pattern has unexpected operator type!");
827 Record *Operator = OpDef->getDef();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000828
829 if (Operator->isSubClassOf("ValueType")) {
830 // If the operator is a ValueType, then this must be "type cast" of a leaf
831 // node.
832 if (Dag->getNumArgs() != 1)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000833 error("Type cast only takes one operand!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000834
835 Init *Arg = Dag->getArg(0);
836 TreePatternNode *New;
837 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000838 Record *R = DI->getDef();
839 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000840 Dag->setArg(0, new DagInit(DI,
Chris Lattner72fe91c2005-09-24 00:40:24 +0000841 std::vector<std::pair<Init*, std::string> >()));
Chris Lattner12cf9092005-11-16 23:14:54 +0000842 return ParseTreePattern(Dag);
Evan Cheng1c3d19e2005-12-04 08:18:16 +0000843 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000844 New = new TreePatternNode(DI);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000845 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
846 New = ParseTreePattern(DI);
Chris Lattner0614b622005-11-02 06:49:14 +0000847 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
848 New = new TreePatternNode(II);
849 if (!Dag->getArgName(0).empty())
850 error("Constant int argument should not have a name!");
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000851 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
852 // Turn this into an IntInit.
853 Init *II = BI->convertInitializerTo(new IntRecTy());
854 if (II == 0 || !dynamic_cast<IntInit*>(II))
855 error("Bits value must be constants!");
856
857 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
858 if (!Dag->getArgName(0).empty())
859 error("Constant int argument should not have a name!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000860 } else {
861 Arg->dump();
862 error("Unknown leaf value for tree pattern!");
863 return 0;
864 }
865
Chris Lattner32707602005-09-08 23:22:48 +0000866 // Apply the type cast.
867 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner12cf9092005-11-16 23:14:54 +0000868 New->setName(Dag->getArgName(0));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000869 return New;
870 }
871
872 // Verify that this is something that makes sense for an operator.
873 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000874 !Operator->isSubClassOf("Instruction") &&
875 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner550525e2006-03-24 21:48:51 +0000876 !Operator->isSubClassOf("Intrinsic") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000877 Operator->getName() != "set")
878 error("Unrecognized node '" + Operator->getName() + "'!");
879
Chris Lattneredbd8712005-10-21 01:19:59 +0000880 // Check to see if this is something that is illegal in an input pattern.
881 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
Chris Lattner5a1df382006-03-24 23:10:39 +0000882 Operator->isSubClassOf("SDNodeXForm")))
Chris Lattneredbd8712005-10-21 01:19:59 +0000883 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
884
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000885 std::vector<TreePatternNode*> Children;
886
887 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
888 Init *Arg = Dag->getArg(i);
889 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
890 Children.push_back(ParseTreePattern(DI));
Chris Lattner12cf9092005-11-16 23:14:54 +0000891 if (Children.back()->getName().empty())
892 Children.back()->setName(Dag->getArgName(i));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000893 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
894 Record *R = DefI->getDef();
895 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
896 // TreePatternNode if its own.
897 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Chris Lattner8c063182006-03-30 22:50:40 +0000898 Dag->setArg(i, new DagInit(DefI,
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000899 std::vector<std::pair<Init*, std::string> >()));
900 --i; // Revisit this node...
901 } else {
902 TreePatternNode *Node = new TreePatternNode(DefI);
903 Node->setName(Dag->getArgName(i));
904 Children.push_back(Node);
905
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000906 // Input argument?
907 if (R->getName() == "node") {
908 if (Dag->getArgName(i).empty())
909 error("'node' argument requires a name to match with operand list");
910 Args.push_back(Dag->getArgName(i));
911 }
912 }
Chris Lattner5d5a0562005-10-19 04:30:56 +0000913 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
914 TreePatternNode *Node = new TreePatternNode(II);
915 if (!Dag->getArgName(i).empty())
916 error("Constant int argument should not have a name!");
917 Children.push_back(Node);
Chris Lattnerffa4fdc2006-03-31 05:25:56 +0000918 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
919 // Turn this into an IntInit.
920 Init *II = BI->convertInitializerTo(new IntRecTy());
921 if (II == 0 || !dynamic_cast<IntInit*>(II))
922 error("Bits value must be constants!");
923
924 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
925 if (!Dag->getArgName(i).empty())
926 error("Constant int argument should not have a name!");
927 Children.push_back(Node);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000928 } else {
Chris Lattner5d5a0562005-10-19 04:30:56 +0000929 std::cerr << '"';
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000930 Arg->dump();
Chris Lattner5d5a0562005-10-19 04:30:56 +0000931 std::cerr << "\": ";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000932 error("Unknown leaf value for tree pattern!");
933 }
934 }
935
Chris Lattner5a1df382006-03-24 23:10:39 +0000936 // If the operator is an intrinsic, then this is just syntactic sugar for for
937 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
938 // convert the intrinsic name to a number.
939 if (Operator->isSubClassOf("Intrinsic")) {
940 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
941 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
942
943 // If this intrinsic returns void, it must have side-effects and thus a
944 // chain.
945 if (Int.ArgVTs[0] == MVT::isVoid) {
946 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
947 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
948 // Has side-effects, requires chain.
949 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
950 } else {
951 // Otherwise, no chain.
952 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
953 }
954
955 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
956 Children.insert(Children.begin(), IIDNode);
957 }
958
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000959 return new TreePatternNode(Operator, Children);
960}
961
Chris Lattner32707602005-09-08 23:22:48 +0000962/// InferAllTypes - Infer/propagate as many types throughout the expression
963/// patterns as possible. Return true if all types are infered, false
964/// otherwise. Throw an exception if a type contradiction is found.
965bool TreePattern::InferAllTypes() {
966 bool MadeChange = true;
967 while (MadeChange) {
968 MadeChange = false;
969 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000970 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattner32707602005-09-08 23:22:48 +0000971 }
972
973 bool HasUnresolvedTypes = false;
974 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
975 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
976 return !HasUnresolvedTypes;
977}
978
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000979void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000980 OS << getRecord()->getName();
981 if (!Args.empty()) {
982 OS << "(" << Args[0];
983 for (unsigned i = 1, e = Args.size(); i != e; ++i)
984 OS << ", " << Args[i];
985 OS << ")";
986 }
987 OS << ": ";
988
989 if (Trees.size() > 1)
990 OS << "[\n";
991 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
992 OS << "\t";
993 Trees[i]->print(OS);
994 OS << "\n";
995 }
996
997 if (Trees.size() > 1)
998 OS << "]\n";
999}
1000
1001void TreePattern::dump() const { print(std::cerr); }
1002
1003
1004
1005//===----------------------------------------------------------------------===//
1006// DAGISelEmitter implementation
1007//
1008
Chris Lattnerca559d02005-09-08 21:03:01 +00001009// Parse all of the SDNode definitions for the target, populating SDNodes.
1010void DAGISelEmitter::ParseNodeInfo() {
1011 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1012 while (!Nodes.empty()) {
1013 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1014 Nodes.pop_back();
1015 }
Chris Lattner5a1df382006-03-24 23:10:39 +00001016
1017 // Get the buildin intrinsic nodes.
1018 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1019 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1020 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
Chris Lattnerca559d02005-09-08 21:03:01 +00001021}
1022
Chris Lattner24eeeb82005-09-13 21:51:00 +00001023/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1024/// map, and emit them to the file as functions.
1025void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1026 OS << "\n// Node transformations.\n";
1027 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1028 while (!Xforms.empty()) {
1029 Record *XFormNode = Xforms.back();
1030 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1031 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1032 SDNodeXForms.insert(std::make_pair(XFormNode,
1033 std::make_pair(SDNode, Code)));
1034
Chris Lattner1048b7a2005-09-13 22:03:37 +00001035 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +00001036 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1037 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1038
Chris Lattner1048b7a2005-09-13 22:03:37 +00001039 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +00001040 << "(SDNode *" << C2 << ") {\n";
1041 if (ClassName != "SDNode")
1042 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1043 OS << Code << "\n}\n";
1044 }
1045
1046 Xforms.pop_back();
1047 }
1048}
1049
Evan Cheng0fc71982005-12-08 02:00:36 +00001050void DAGISelEmitter::ParseComplexPatterns() {
1051 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1052 while (!AMs.empty()) {
1053 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1054 AMs.pop_back();
1055 }
1056}
Chris Lattner24eeeb82005-09-13 21:51:00 +00001057
1058
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001059/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1060/// file, building up the PatternFragments map. After we've collected them all,
1061/// inline fragments together as necessary, so that there are no references left
1062/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001063///
1064/// This also emits all of the predicate functions to the output file.
1065///
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001066void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001067 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1068
1069 // First step, parse all of the fragments and emit predicate functions.
1070 OS << "\n// Predicate functions.\n";
1071 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001072 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattneredbd8712005-10-21 01:19:59 +00001073 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001074 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +00001075
1076 // Validate the argument list, converting it to map, to discard duplicates.
1077 std::vector<std::string> &Args = P->getArgList();
1078 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1079
1080 if (OperandsMap.count(""))
1081 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1082
1083 // Parse the operands list.
1084 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Chris Lattner8c063182006-03-30 22:50:40 +00001085 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1086 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
Chris Lattneree9f0c32005-09-13 21:20:49 +00001087 P->error("Operands list should start with '(ops ... '!");
1088
1089 // Copy over the arguments.
1090 Args.clear();
1091 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1092 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1093 static_cast<DefInit*>(OpsList->getArg(j))->
1094 getDef()->getName() != "node")
1095 P->error("Operands list should all be 'node' values.");
1096 if (OpsList->getArgName(j).empty())
1097 P->error("Operands list should have names for each operand!");
1098 if (!OperandsMap.count(OpsList->getArgName(j)))
1099 P->error("'" + OpsList->getArgName(j) +
1100 "' does not occur in pattern or was multiply specified!");
1101 OperandsMap.erase(OpsList->getArgName(j));
1102 Args.push_back(OpsList->getArgName(j));
1103 }
1104
1105 if (!OperandsMap.empty())
1106 P->error("Operands list does not contain an entry for operand '" +
1107 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001108
1109 // If there is a code init for this fragment, emit the predicate code and
1110 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +00001111 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1112 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +00001113 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001114 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +00001115 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001116 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1117
Chris Lattner1048b7a2005-09-13 22:03:37 +00001118 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001119 << "(SDNode *" << C2 << ") {\n";
1120 if (ClassName != "SDNode")
1121 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +00001122 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +00001123 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001124 }
Chris Lattner6de8b532005-09-13 21:59:15 +00001125
1126 // If there is a node transformation corresponding to this, keep track of
1127 // it.
1128 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1129 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +00001130 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001131 }
1132
1133 OS << "\n\n";
1134
1135 // Now that we've parsed all of the tree fragments, do a closure on them so
1136 // that there are not references to PatFrags left inside of them.
1137 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1138 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +00001139 TreePattern *ThePat = I->second;
1140 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +00001141
Chris Lattner32707602005-09-08 23:22:48 +00001142 // Infer as many types as possible. Don't worry about it if we don't infer
1143 // all of them, some may depend on the inputs of the pattern.
1144 try {
1145 ThePat->InferAllTypes();
1146 } catch (...) {
1147 // If this pattern fragment is not supported by this target (no types can
1148 // satisfy its constraints), just ignore it. If the bogus pattern is
1149 // actually used by instructions, the type consistency error will be
1150 // reported there.
1151 }
1152
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001153 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +00001154 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001155 }
1156}
1157
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001158/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +00001159/// instruction input. Return true if this is a real use.
1160static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001161 std::map<std::string, TreePatternNode*> &InstInputs,
1162 std::vector<Record*> &InstImpInputs) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001163 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +00001164 if (Pat->getName().empty()) {
1165 if (Pat->isLeaf()) {
1166 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1167 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1168 I->error("Input " + DI->getDef()->getName() + " must be named!");
Evan Cheng7b05bd52005-12-23 22:11:47 +00001169 else if (DI && DI->getDef()->isSubClassOf("Register"))
1170 InstImpInputs.push_back(DI->getDef());
Chris Lattner7da852f2005-09-14 22:06:36 +00001171 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001172 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +00001173 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001174
1175 Record *Rec;
1176 if (Pat->isLeaf()) {
1177 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1178 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1179 Rec = DI->getDef();
1180 } else {
1181 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1182 Rec = Pat->getOperator();
1183 }
1184
Evan Cheng01f318b2005-12-14 02:21:57 +00001185 // SRCVALUE nodes are ignored.
1186 if (Rec->getName() == "srcvalue")
1187 return false;
1188
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001189 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1190 if (!Slot) {
1191 Slot = Pat;
1192 } else {
1193 Record *SlotRec;
1194 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001195 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001196 } else {
1197 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1198 SlotRec = Slot->getOperator();
1199 }
1200
1201 // Ensure that the inputs agree if we've already seen this input.
1202 if (Rec != SlotRec)
1203 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Nate Begemanb73628b2005-12-30 00:12:56 +00001204 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001205 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1206 }
Chris Lattnerf1311842005-09-14 23:05:13 +00001207 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001208}
1209
1210/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1211/// part of "I", the instruction), computing the set of inputs and outputs of
1212/// the pattern. Report errors if we see anything naughty.
1213void DAGISelEmitter::
1214FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1215 std::map<std::string, TreePatternNode*> &InstInputs,
Chris Lattner947604b2006-03-24 21:52:20 +00001216 std::map<std::string, TreePatternNode*>&InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001217 std::vector<Record*> &InstImpInputs,
Evan Chengbcecf332005-12-17 01:19:28 +00001218 std::vector<Record*> &InstImpResults) {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001219 if (Pat->isLeaf()) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00001220 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerf1311842005-09-14 23:05:13 +00001221 if (!isUse && Pat->getTransformFn())
1222 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001223 return;
1224 } else if (Pat->getOperator()->getName() != "set") {
1225 // If this is not a set, verify that the children nodes are not void typed,
1226 // and recurse.
1227 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001228 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001229 I->error("Cannot have void nodes inside of patterns!");
Evan Chengbcecf332005-12-17 01:19:28 +00001230 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001231 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001232 }
1233
1234 // If this is a non-leaf node with no children, treat it basically as if
1235 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +00001236 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001237 if (Pat->getNumChildren() == 0)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001238 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001239
Chris Lattnerf1311842005-09-14 23:05:13 +00001240 if (!isUse && Pat->getTransformFn())
1241 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001242 return;
1243 }
1244
1245 // Otherwise, this is a set, validate and collect instruction results.
1246 if (Pat->getNumChildren() == 0)
1247 I->error("set requires operands!");
1248 else if (Pat->getNumChildren() & 1)
1249 I->error("set requires an even number of operands");
1250
Chris Lattnerf1311842005-09-14 23:05:13 +00001251 if (Pat->getTransformFn())
1252 I->error("Cannot specify a transform function on a set node!");
1253
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001254 // Check the set destinations.
1255 unsigned NumValues = Pat->getNumChildren()/2;
1256 for (unsigned i = 0; i != NumValues; ++i) {
1257 TreePatternNode *Dest = Pat->getChild(i);
1258 if (!Dest->isLeaf())
Evan Cheng86217892005-12-12 19:37:43 +00001259 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001260
1261 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1262 if (!Val)
Evan Cheng86217892005-12-12 19:37:43 +00001263 I->error("set destination should be a register!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001264
Evan Chengbcecf332005-12-17 01:19:28 +00001265 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1266 if (Dest->getName().empty())
1267 I->error("set destination must have a name!");
1268 if (InstResults.count(Dest->getName()))
1269 I->error("cannot set '" + Dest->getName() +"' multiple times");
Evan Cheng420132e2006-03-20 06:04:09 +00001270 InstResults[Dest->getName()] = Dest;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001271 } else if (Val->getDef()->isSubClassOf("Register")) {
Evan Chengbcecf332005-12-17 01:19:28 +00001272 InstImpResults.push_back(Val->getDef());
1273 } else {
1274 I->error("set destination should be a register!");
1275 }
1276
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001277 // Verify and collect info from the computation.
1278 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
Evan Cheng7b05bd52005-12-23 22:11:47 +00001279 InstInputs, InstResults,
1280 InstImpInputs, InstImpResults);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001281 }
1282}
1283
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001284/// ParseInstructions - Parse all of the instructions, inlining and resolving
1285/// any fragments involved. This populates the Instructions list with fully
1286/// resolved instructions.
1287void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001288 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1289
1290 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001291 ListInit *LI = 0;
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001292
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001293 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1294 LI = Instrs[i]->getValueAsListInit("Pattern");
1295
1296 // If there is no pattern, only collect minimal information about the
1297 // instruction for its operand list. We have to assume that there is one
1298 // result, as we have no detailed info.
1299 if (!LI || LI->getSize() == 0) {
Nate Begemanddb39542005-12-01 00:06:14 +00001300 std::vector<Record*> Results;
1301 std::vector<Record*> Operands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001302
1303 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001304
Evan Cheng3a217f32005-12-22 02:35:21 +00001305 if (InstInfo.OperandList.size() != 0) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001306 // FIXME: temporary hack...
Evan Cheng2b4ea792005-12-26 09:11:45 +00001307 if (InstInfo.noResults) {
Evan Cheng3a217f32005-12-22 02:35:21 +00001308 // These produce no results
1309 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1310 Operands.push_back(InstInfo.OperandList[j].Rec);
1311 } else {
1312 // Assume the first operand is the result.
1313 Results.push_back(InstInfo.OperandList[0].Rec);
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001314
Evan Cheng3a217f32005-12-22 02:35:21 +00001315 // The rest are inputs.
1316 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1317 Operands.push_back(InstInfo.OperandList[j].Rec);
1318 }
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001319 }
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001320
1321 // Create and insert the instruction.
Evan Chengbcecf332005-12-17 01:19:28 +00001322 std::vector<Record*> ImpResults;
1323 std::vector<Record*> ImpOperands;
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001324 Instructions.insert(std::make_pair(Instrs[i],
Evan Cheng7b05bd52005-12-23 22:11:47 +00001325 DAGInstruction(0, Results, Operands, ImpResults,
1326 ImpOperands)));
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001327 continue; // no pattern.
1328 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001329
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001330 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001331 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001332 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +00001333 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001334
Chris Lattner95f6b762005-09-08 23:26:30 +00001335 // Infer as many types as possible. If we cannot infer all of them, we can
1336 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001337 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +00001338 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001339
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001340 // InstInputs - Keep track of all of the inputs of the instruction, along
1341 // with the record they are declared as.
1342 std::map<std::string, TreePatternNode*> InstInputs;
1343
1344 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001345 // in the instruction, including what reg class they are.
Evan Cheng420132e2006-03-20 06:04:09 +00001346 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001347
1348 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001349 std::vector<Record*> InstImpResults;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001350
Chris Lattner1f39e292005-09-14 00:09:24 +00001351 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001352 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +00001353 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1354 TreePatternNode *Pat = I->getTree(j);
Nate Begemanb73628b2005-12-30 00:12:56 +00001355 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattnerf2a17a72005-09-09 01:11:44 +00001356 I->error("Top-level forms in instruction pattern should have"
1357 " void types");
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001358
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001359 // Find inputs and outputs, and verify the structure of the uses/defs.
Evan Chengbcecf332005-12-17 01:19:28 +00001360 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001361 InstImpInputs, InstImpResults);
Chris Lattner1f39e292005-09-14 00:09:24 +00001362 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +00001363
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001364 // Now that we have inputs and outputs of the pattern, inspect the operands
1365 // list for the instruction. This determines the order that operands are
1366 // added to the machine instruction the node corresponds to.
1367 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +00001368
1369 // Parse the operands list from the (ops) list, validating it.
1370 std::vector<std::string> &Args = I->getArgList();
1371 assert(Args.empty() && "Args list should still be empty here!");
1372 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1373
1374 // Check that all of the results occur first in the list.
Nate Begemanddb39542005-12-01 00:06:14 +00001375 std::vector<Record*> Results;
Evan Cheng420132e2006-03-20 06:04:09 +00001376 TreePatternNode *Res0Node = NULL;
Chris Lattner39e8af92005-09-14 18:19:25 +00001377 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +00001378 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001379 I->error("'" + InstResults.begin()->first +
1380 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +00001381 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +00001382
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001383 // Check that it exists in InstResults.
Evan Cheng420132e2006-03-20 06:04:09 +00001384 TreePatternNode *RNode = InstResults[OpName];
Chris Lattner5c4c7742006-03-25 22:12:44 +00001385 if (RNode == 0)
1386 I->error("Operand $" + OpName + " does not exist in operand list!");
1387
Evan Cheng420132e2006-03-20 06:04:09 +00001388 if (i == 0)
1389 Res0Node = RNode;
1390 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
Chris Lattner39e8af92005-09-14 18:19:25 +00001391 if (R == 0)
1392 I->error("Operand $" + OpName + " should be a set destination: all "
1393 "outputs must occur before inputs in operand list!");
1394
1395 if (CGI.OperandList[i].Rec != R)
1396 I->error("Operand $" + OpName + " class mismatch!");
1397
Chris Lattnerae6d8282005-09-15 21:51:12 +00001398 // Remember the return type.
Nate Begemanddb39542005-12-01 00:06:14 +00001399 Results.push_back(CGI.OperandList[i].Rec);
Chris Lattnerae6d8282005-09-15 21:51:12 +00001400
Chris Lattner39e8af92005-09-14 18:19:25 +00001401 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001402 InstResults.erase(OpName);
1403 }
1404
Chris Lattner0b592252005-09-14 21:59:34 +00001405 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1406 // the copy while we're checking the inputs.
1407 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +00001408
1409 std::vector<TreePatternNode*> ResultNodeOperands;
Nate Begemanddb39542005-12-01 00:06:14 +00001410 std::vector<Record*> Operands;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001411 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1412 const std::string &OpName = CGI.OperandList[i].Name;
1413 if (OpName.empty())
1414 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1415
Chris Lattner0b592252005-09-14 21:59:34 +00001416 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001417 I->error("Operand $" + OpName +
1418 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +00001419 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +00001420 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Nate Begemanddb39542005-12-01 00:06:14 +00001421
1422 if (InVal->isLeaf() &&
1423 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1424 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Evan Cheng0fc71982005-12-08 02:00:36 +00001425 if (CGI.OperandList[i].Rec != InRec &&
1426 !InRec->isSubClassOf("ComplexPattern"))
Chris Lattner488580c2006-01-28 19:06:51 +00001427 I->error("Operand $" + OpName + "'s register class disagrees"
1428 " between the operand and pattern");
Nate Begemanddb39542005-12-01 00:06:14 +00001429 }
1430 Operands.push_back(CGI.OperandList[i].Rec);
Chris Lattnerb0276202005-09-14 22:55:26 +00001431
Chris Lattner2175c182005-09-14 23:01:59 +00001432 // Construct the result for the dest-pattern operand list.
1433 TreePatternNode *OpNode = InVal->clone();
1434
1435 // No predicate is useful on the result.
1436 OpNode->setPredicateFn("");
1437
1438 // Promote the xform function to be an explicit node if set.
1439 if (Record *Xform = OpNode->getTransformFn()) {
1440 OpNode->setTransformFn(0);
1441 std::vector<TreePatternNode*> Children;
1442 Children.push_back(OpNode);
1443 OpNode = new TreePatternNode(Xform, Children);
1444 }
1445
1446 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +00001447 }
1448
Chris Lattner0b592252005-09-14 21:59:34 +00001449 if (!InstInputsCheck.empty())
1450 I->error("Input operand $" + InstInputsCheck.begin()->first +
1451 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +00001452
1453 TreePatternNode *ResultPattern =
1454 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Evan Cheng420132e2006-03-20 06:04:09 +00001455 // Copy fully inferred output node type to instruction result pattern.
1456 if (NumResults > 0)
1457 ResultPattern->setTypes(Res0Node->getExtTypes());
Chris Lattnera28aec12005-09-15 22:23:50 +00001458
1459 // Create and insert the instruction.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001460 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
Chris Lattnera28aec12005-09-15 22:23:50 +00001461 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1462
1463 // Use a temporary tree pattern to infer all types and make sure that the
1464 // constructed result is correct. This depends on the instruction already
1465 // being inserted into the Instructions map.
Chris Lattneredbd8712005-10-21 01:19:59 +00001466 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnera28aec12005-09-15 22:23:50 +00001467 Temp.InferAllTypes();
1468
1469 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1470 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +00001471
Chris Lattner32707602005-09-08 23:22:48 +00001472 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001473 }
Chris Lattner1f39e292005-09-14 00:09:24 +00001474
Chris Lattnerd8a3bde2005-09-14 20:53:42 +00001475 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +00001476 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1477 E = Instructions.end(); II != E; ++II) {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001478 DAGInstruction &TheInst = II->second;
1479 TreePattern *I = TheInst.getPattern();
Chris Lattner0c0cfa72005-10-19 01:27:22 +00001480 if (I == 0) continue; // No pattern.
Evan Chengdd304dd2005-12-05 23:08:55 +00001481
Chris Lattner1f39e292005-09-14 00:09:24 +00001482 if (I->getNumTrees() != 1) {
1483 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1484 continue;
1485 }
1486 TreePatternNode *Pattern = I->getTree(0);
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001487 TreePatternNode *SrcPattern;
Evan Chengbcecf332005-12-17 01:19:28 +00001488 if (Pattern->getOperator()->getName() == "set") {
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001489 if (Pattern->getNumChildren() != 2)
1490 continue; // Not a set of a single value (not handled so far)
1491
1492 SrcPattern = Pattern->getChild(1)->clone();
Evan Chengbcecf332005-12-17 01:19:28 +00001493 } else{
1494 // Not a set (store or something?)
1495 SrcPattern = Pattern;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001496 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001497
1498 std::string Reason;
1499 if (!SrcPattern->canPatternMatch(Reason, *this))
1500 I->error("Instruction can never match: " + Reason);
1501
Evan Cheng58e84a62005-12-14 22:02:59 +00001502 Record *Instr = II->first;
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001503 TreePatternNode *DstPattern = TheInst.getResultPattern();
Evan Cheng58e84a62005-12-14 22:02:59 +00001504 PatternsToMatch.
1505 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
Evan Cheng59413202006-04-19 18:07:24 +00001506 SrcPattern, DstPattern,
Evan Chengc81d2a02006-04-19 20:36:09 +00001507 Instr->getValueAsInt("AddedComplexity")));
Chris Lattner1f39e292005-09-14 00:09:24 +00001508 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001509}
1510
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001511void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +00001512 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001513
Chris Lattnerabbb6052005-09-15 21:42:00 +00001514 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +00001515 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
Chris Lattneredbd8712005-10-21 01:19:59 +00001516 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001517
Chris Lattnerabbb6052005-09-15 21:42:00 +00001518 // Inline pattern fragments into it.
1519 Pattern->InlinePatternFragments();
1520
1521 // Infer as many types as possible. If we cannot infer all of them, we can
1522 // never do anything with this pattern: report it to the user.
1523 if (!Pattern->InferAllTypes())
1524 Pattern->error("Could not infer all types in pattern!");
Chris Lattner09c03392005-11-17 17:43:52 +00001525
1526 // Validate that the input pattern is correct.
1527 {
1528 std::map<std::string, TreePatternNode*> InstInputs;
Evan Cheng420132e2006-03-20 06:04:09 +00001529 std::map<std::string, TreePatternNode*> InstResults;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001530 std::vector<Record*> InstImpInputs;
Evan Chengbcecf332005-12-17 01:19:28 +00001531 std::vector<Record*> InstImpResults;
Chris Lattner09c03392005-11-17 17:43:52 +00001532 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
Evan Chengbcecf332005-12-17 01:19:28 +00001533 InstInputs, InstResults,
Evan Cheng7b05bd52005-12-23 22:11:47 +00001534 InstImpInputs, InstImpResults);
Chris Lattner09c03392005-11-17 17:43:52 +00001535 }
Chris Lattnerabbb6052005-09-15 21:42:00 +00001536
1537 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1538 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001539
1540 // Parse the instruction.
Chris Lattneredbd8712005-10-21 01:19:59 +00001541 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +00001542
1543 // Inline pattern fragments into it.
1544 Result->InlinePatternFragments();
1545
1546 // Infer as many types as possible. If we cannot infer all of them, we can
1547 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +00001548 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +00001549 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +00001550
1551 if (Result->getNumTrees() != 1)
1552 Result->error("Cannot handle instructions producing instructions "
1553 "with temporaries yet!");
Chris Lattnere97603f2005-09-28 19:27:25 +00001554
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001555 // Promote the xform function to be an explicit node if set.
1556 std::vector<TreePatternNode*> ResultNodeOperands;
1557 TreePatternNode *DstPattern = Result->getOnlyTree();
1558 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1559 TreePatternNode *OpNode = DstPattern->getChild(ii);
1560 if (Record *Xform = OpNode->getTransformFn()) {
1561 OpNode->setTransformFn(0);
1562 std::vector<TreePatternNode*> Children;
1563 Children.push_back(OpNode);
1564 OpNode = new TreePatternNode(Xform, Children);
1565 }
1566 ResultNodeOperands.push_back(OpNode);
1567 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00001568 DstPattern = Result->getOnlyTree();
1569 if (!DstPattern->isLeaf())
1570 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1571 ResultNodeOperands);
Evan Cheng3a7a14b2006-03-21 20:44:17 +00001572 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1573 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1574 Temp.InferAllTypes();
1575
Chris Lattnere97603f2005-09-28 19:27:25 +00001576 std::string Reason;
1577 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1578 Pattern->error("Pattern can never match: " + Reason);
1579
Evan Cheng58e84a62005-12-14 22:02:59 +00001580 PatternsToMatch.
1581 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1582 Pattern->getOnlyTree(),
Evan Cheng59413202006-04-19 18:07:24 +00001583 Temp.getOnlyTree(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001584 Patterns[i]->getValueAsInt("AddedComplexity")));
Chris Lattnerabbb6052005-09-15 21:42:00 +00001585 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001586}
1587
Chris Lattnere46e17b2005-09-29 19:28:10 +00001588/// CombineChildVariants - Given a bunch of permutations of each child of the
1589/// 'operator' node, put them together in all possible ways.
1590static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattneraf302912005-09-29 22:36:54 +00001591 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
Chris Lattnere46e17b2005-09-29 19:28:10 +00001592 std::vector<TreePatternNode*> &OutVariants,
1593 DAGISelEmitter &ISE) {
Chris Lattneraf302912005-09-29 22:36:54 +00001594 // Make sure that each operand has at least one variant to choose from.
1595 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1596 if (ChildVariants[i].empty())
1597 return;
1598
Chris Lattnere46e17b2005-09-29 19:28:10 +00001599 // The end result is an all-pairs construction of the resultant pattern.
1600 std::vector<unsigned> Idxs;
1601 Idxs.resize(ChildVariants.size());
1602 bool NotDone = true;
1603 while (NotDone) {
1604 // Create the variant and add it to the output list.
1605 std::vector<TreePatternNode*> NewChildren;
1606 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1607 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1608 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1609
1610 // Copy over properties.
1611 R->setName(Orig->getName());
1612 R->setPredicateFn(Orig->getPredicateFn());
1613 R->setTransformFn(Orig->getTransformFn());
Nate Begemanb73628b2005-12-30 00:12:56 +00001614 R->setTypes(Orig->getExtTypes());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001615
1616 // If this pattern cannot every match, do not include it as a variant.
1617 std::string ErrString;
1618 if (!R->canPatternMatch(ErrString, ISE)) {
1619 delete R;
1620 } else {
1621 bool AlreadyExists = false;
1622
1623 // Scan to see if this pattern has already been emitted. We can get
1624 // duplication due to things like commuting:
1625 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1626 // which are the same pattern. Ignore the dups.
1627 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1628 if (R->isIsomorphicTo(OutVariants[i])) {
1629 AlreadyExists = true;
1630 break;
1631 }
1632
1633 if (AlreadyExists)
1634 delete R;
1635 else
1636 OutVariants.push_back(R);
1637 }
1638
1639 // Increment indices to the next permutation.
1640 NotDone = false;
1641 // Look for something we can increment without causing a wrap-around.
1642 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1643 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1644 NotDone = true; // Found something to increment.
1645 break;
1646 }
1647 Idxs[IdxsIdx] = 0;
1648 }
1649 }
1650}
1651
Chris Lattneraf302912005-09-29 22:36:54 +00001652/// CombineChildVariants - A helper function for binary operators.
1653///
1654static void CombineChildVariants(TreePatternNode *Orig,
1655 const std::vector<TreePatternNode*> &LHS,
1656 const std::vector<TreePatternNode*> &RHS,
1657 std::vector<TreePatternNode*> &OutVariants,
1658 DAGISelEmitter &ISE) {
1659 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1660 ChildVariants.push_back(LHS);
1661 ChildVariants.push_back(RHS);
1662 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1663}
1664
1665
1666static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1667 std::vector<TreePatternNode *> &Children) {
1668 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1669 Record *Operator = N->getOperator();
1670
1671 // Only permit raw nodes.
1672 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1673 N->getTransformFn()) {
1674 Children.push_back(N);
1675 return;
1676 }
1677
1678 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1679 Children.push_back(N->getChild(0));
1680 else
1681 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1682
1683 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1684 Children.push_back(N->getChild(1));
1685 else
1686 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1687}
1688
Chris Lattnere46e17b2005-09-29 19:28:10 +00001689/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1690/// the (potentially recursive) pattern by using algebraic laws.
1691///
1692static void GenerateVariantsOf(TreePatternNode *N,
1693 std::vector<TreePatternNode*> &OutVariants,
1694 DAGISelEmitter &ISE) {
1695 // We cannot permute leaves.
1696 if (N->isLeaf()) {
1697 OutVariants.push_back(N);
1698 return;
1699 }
1700
1701 // Look up interesting info about the node.
Chris Lattner5a1df382006-03-24 23:10:39 +00001702 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
Chris Lattnere46e17b2005-09-29 19:28:10 +00001703
1704 // If this node is associative, reassociate.
Chris Lattner5a1df382006-03-24 23:10:39 +00001705 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
Chris Lattneraf302912005-09-29 22:36:54 +00001706 // Reassociate by pulling together all of the linked operators
1707 std::vector<TreePatternNode*> MaximalChildren;
1708 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1709
1710 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1711 // permutations.
1712 if (MaximalChildren.size() == 3) {
1713 // Find the variants of all of our maximal children.
1714 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1715 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1716 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1717 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1718
1719 // There are only two ways we can permute the tree:
1720 // (A op B) op C and A op (B op C)
1721 // Within these forms, we can also permute A/B/C.
1722
1723 // Generate legal pair permutations of A/B/C.
1724 std::vector<TreePatternNode*> ABVariants;
1725 std::vector<TreePatternNode*> BAVariants;
1726 std::vector<TreePatternNode*> ACVariants;
1727 std::vector<TreePatternNode*> CAVariants;
1728 std::vector<TreePatternNode*> BCVariants;
1729 std::vector<TreePatternNode*> CBVariants;
1730 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1731 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1732 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1733 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1734 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1735 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1736
1737 // Combine those into the result: (x op x) op x
1738 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1739 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1740 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1741 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1742 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1743 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1744
1745 // Combine those into the result: x op (x op x)
1746 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1747 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1748 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1749 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1750 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1751 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1752 return;
1753 }
1754 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001755
1756 // Compute permutations of all children.
1757 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1758 ChildVariants.resize(N->getNumChildren());
1759 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1760 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1761
1762 // Build all permutations based on how the children were formed.
1763 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1764
1765 // If this node is commutative, consider the commuted order.
Chris Lattner5a1df382006-03-24 23:10:39 +00001766 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001767 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
Chris Lattneraf302912005-09-29 22:36:54 +00001768 // Consider the commuted order.
1769 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1770 OutVariants, ISE);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001771 }
1772}
1773
1774
Chris Lattnere97603f2005-09-28 19:27:25 +00001775// GenerateVariants - Generate variants. For example, commutative patterns can
1776// match multiple ways. Add them to PatternsToMatch as well.
1777void DAGISelEmitter::GenerateVariants() {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001778
1779 DEBUG(std::cerr << "Generating instruction variants.\n");
1780
1781 // Loop over all of the patterns we've collected, checking to see if we can
1782 // generate variants of the instruction, through the exploitation of
1783 // identities. This permits the target to provide agressive matching without
1784 // the .td file having to contain tons of variants of instructions.
1785 //
1786 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1787 // intentionally do not reconsider these. Any variants of added patterns have
1788 // already been added.
1789 //
1790 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1791 std::vector<TreePatternNode*> Variants;
Evan Cheng58e84a62005-12-14 22:02:59 +00001792 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
Chris Lattnere46e17b2005-09-29 19:28:10 +00001793
1794 assert(!Variants.empty() && "Must create at least original variant!");
Chris Lattnere46e17b2005-09-29 19:28:10 +00001795 Variants.erase(Variants.begin()); // Remove the original pattern.
1796
1797 if (Variants.empty()) // No variants for this pattern.
1798 continue;
1799
1800 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
Evan Cheng58e84a62005-12-14 22:02:59 +00001801 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00001802 std::cerr << "\n");
1803
1804 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1805 TreePatternNode *Variant = Variants[v];
1806
1807 DEBUG(std::cerr << " VAR#" << v << ": ";
1808 Variant->dump();
1809 std::cerr << "\n");
1810
1811 // Scan to see if an instruction or explicit pattern already matches this.
1812 bool AlreadyExists = false;
1813 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1814 // Check to see if this variant already exists.
Evan Cheng58e84a62005-12-14 22:02:59 +00001815 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
Chris Lattnere46e17b2005-09-29 19:28:10 +00001816 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1817 AlreadyExists = true;
1818 break;
1819 }
1820 }
1821 // If we already have it, ignore the variant.
1822 if (AlreadyExists) continue;
1823
1824 // Otherwise, add it to the list of patterns we have.
Evan Cheng58e84a62005-12-14 22:02:59 +00001825 PatternsToMatch.
1826 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
Evan Cheng59413202006-04-19 18:07:24 +00001827 Variant, PatternsToMatch[i].getDstPattern(),
Evan Chengc81d2a02006-04-19 20:36:09 +00001828 PatternsToMatch[i].getAddedComplexity()));
Chris Lattnere46e17b2005-09-29 19:28:10 +00001829 }
1830
1831 DEBUG(std::cerr << "\n");
1832 }
Chris Lattnere97603f2005-09-28 19:27:25 +00001833}
1834
Chris Lattner7cf2fe62005-09-28 20:58:06 +00001835
Evan Cheng0fc71982005-12-08 02:00:36 +00001836// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1837// ComplexPattern.
1838static bool NodeIsComplexPattern(TreePatternNode *N)
1839{
1840 return (N->isLeaf() &&
1841 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1842 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1843 isSubClassOf("ComplexPattern"));
1844}
1845
1846// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1847// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1848static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1849 DAGISelEmitter &ISE)
1850{
1851 if (N->isLeaf() &&
1852 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1853 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1854 isSubClassOf("ComplexPattern")) {
1855 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1856 ->getDef());
1857 }
1858 return NULL;
1859}
1860
Chris Lattner05814af2005-09-28 17:57:56 +00001861/// getPatternSize - Return the 'size' of this pattern. We want to match large
1862/// patterns before small ones. This is used to determine the size of a
1863/// pattern.
Evan Cheng0fc71982005-12-08 02:00:36 +00001864static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
Evan Cheng4a7c2842006-01-06 22:19:44 +00001865 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1866 isExtFloatingPointInVTs(P->getExtTypes()) ||
1867 P->getExtTypeNum(0) == MVT::isVoid ||
1868 P->getExtTypeNum(0) == MVT::Flag &&
1869 "Not a valid pattern node to size!");
Evan Chenge1050d62006-01-06 02:30:23 +00001870 unsigned Size = 2; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +00001871 // If the root node is a ConstantSDNode, increases its size.
1872 // e.g. (set R32:$dst, 0).
1873 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1874 Size++;
Evan Cheng0fc71982005-12-08 02:00:36 +00001875
1876 // FIXME: This is a hack to statically increase the priority of patterns
1877 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1878 // Later we can allow complexity / cost for each pattern to be (optionally)
1879 // specified. To get best possible pattern match we'll need to dynamically
1880 // calculate the complexity of all patterns a dag can potentially map to.
1881 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1882 if (AM)
Evan Cheng4a7c2842006-01-06 22:19:44 +00001883 Size += AM->getNumOperands() * 2;
Chris Lattner3e179802006-02-03 18:06:02 +00001884
1885 // If this node has some predicate function that must match, it adds to the
1886 // complexity of this node.
1887 if (!P->getPredicateFn().empty())
1888 ++Size;
1889
Chris Lattner05814af2005-09-28 17:57:56 +00001890 // Count children in the count if they are also nodes.
1891 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1892 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +00001893 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Evan Cheng0fc71982005-12-08 02:00:36 +00001894 Size += getPatternSize(Child, ISE);
1895 else if (Child->isLeaf()) {
1896 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Chris Lattner3e179802006-02-03 18:06:02 +00001897 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
Evan Cheng4a7c2842006-01-06 22:19:44 +00001898 else if (NodeIsComplexPattern(Child))
1899 Size += getPatternSize(Child, ISE);
Chris Lattner3e179802006-02-03 18:06:02 +00001900 else if (!Child->getPredicateFn().empty())
1901 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +00001902 }
Chris Lattner05814af2005-09-28 17:57:56 +00001903 }
1904
1905 return Size;
1906}
1907
1908/// getResultPatternCost - Compute the number of instructions for this pattern.
1909/// This is a temporary hack. We should really include the instruction
1910/// latencies in this calculation.
Evan Chengfbad7082006-02-18 02:33:09 +00001911static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
Chris Lattner05814af2005-09-28 17:57:56 +00001912 if (P->isLeaf()) return 0;
1913
Evan Chengfbad7082006-02-18 02:33:09 +00001914 unsigned Cost = 0;
1915 Record *Op = P->getOperator();
1916 if (Op->isSubClassOf("Instruction")) {
1917 Cost++;
1918 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1919 if (II.usesCustomDAGSchedInserter)
1920 Cost += 10;
1921 }
Chris Lattner05814af2005-09-28 17:57:56 +00001922 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Evan Chengfbad7082006-02-18 02:33:09 +00001923 Cost += getResultPatternCost(P->getChild(i), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001924 return Cost;
1925}
1926
1927// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1928// In particular, we want to match maximal patterns first and lowest cost within
1929// a particular complexity first.
1930struct PatternSortingPredicate {
Evan Cheng0fc71982005-12-08 02:00:36 +00001931 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1932 DAGISelEmitter &ISE;
1933
Evan Cheng58e84a62005-12-14 22:02:59 +00001934 bool operator()(PatternToMatch *LHS,
1935 PatternToMatch *RHS) {
1936 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1937 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
Evan Chengc81d2a02006-04-19 20:36:09 +00001938 LHSSize += LHS->getAddedComplexity();
1939 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +00001940 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1941 if (LHSSize < RHSSize) return false;
1942
1943 // If the patterns have equal complexity, compare generated instruction cost
Evan Chengfbad7082006-02-18 02:33:09 +00001944 return getResultPatternCost(LHS->getDstPattern(), ISE) <
1945 getResultPatternCost(RHS->getDstPattern(), ISE);
Chris Lattner05814af2005-09-28 17:57:56 +00001946 }
1947};
1948
Nate Begeman6510b222005-12-01 04:51:06 +00001949/// getRegisterValueType - Look up and return the first ValueType of specified
1950/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +00001951static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +00001952 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1953 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +00001954 return MVT::Other;
1955}
1956
Chris Lattner72fe91c2005-09-24 00:40:24 +00001957
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001958/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1959/// type information from it.
1960static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +00001961 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001962 if (!N->isLeaf())
1963 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1964 RemoveAllTypes(N->getChild(i));
1965}
Chris Lattner72fe91c2005-09-24 00:40:24 +00001966
Chris Lattner0614b622005-11-02 06:49:14 +00001967Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1968 Record *N = Records.getDef(Name);
Chris Lattner5a1df382006-03-24 23:10:39 +00001969 if (!N || !N->isSubClassOf("SDNode")) {
1970 std::cerr << "Error getting SDNode '" << Name << "'!\n";
1971 exit(1);
1972 }
Chris Lattner0614b622005-11-02 06:49:14 +00001973 return N;
1974}
1975
Evan Cheng51fecc82006-01-09 18:27:06 +00001976/// NodeHasProperty - return true if TreePatternNode has the specified
1977/// property.
1978static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1979 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001980{
1981 if (N->isLeaf()) return false;
1982 Record *Operator = N->getOperator();
1983 if (!Operator->isSubClassOf("SDNode")) return false;
1984
1985 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
Evan Cheng51fecc82006-01-09 18:27:06 +00001986 return NodeInfo.hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +00001987}
1988
Evan Cheng51fecc82006-01-09 18:27:06 +00001989static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1990 DAGISelEmitter &ISE)
Evan Cheng7b05bd52005-12-23 22:11:47 +00001991{
Evan Cheng51fecc82006-01-09 18:27:06 +00001992 if (NodeHasProperty(N, Property, ISE))
Evan Cheng7b05bd52005-12-23 22:11:47 +00001993 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +00001994
1995 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1996 TreePatternNode *Child = N->getChild(i);
1997 if (PatternHasProperty(Child, Property, ISE))
1998 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +00001999 }
2000
2001 return false;
2002}
2003
Evan Chengb915f312005-12-09 22:45:35 +00002004class PatternCodeEmitter {
2005private:
2006 DAGISelEmitter &ISE;
2007
Evan Cheng58e84a62005-12-14 22:02:59 +00002008 // Predicates.
2009 ListInit *Predicates;
Evan Cheng59413202006-04-19 18:07:24 +00002010 // Pattern cost.
2011 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +00002012 // Instruction selector pattern.
2013 TreePatternNode *Pattern;
2014 // Matched instruction.
2015 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002016
Evan Chengb915f312005-12-09 22:45:35 +00002017 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +00002018 std::map<std::string, std::string> VariableMap;
2019 // Node to operator mapping
2020 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +00002021 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002022 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +00002023 std::set<std::string> Duplicates;
Evan Cheng61a02092006-04-28 02:08:10 +00002024 /// These nodes are being marked "in-flight" so they cannot be folded.
2025 std::vector<std::string> InflightNodes;
Evan Chengb915f312005-12-09 22:45:35 +00002026
Chris Lattner8a0604b2006-01-28 20:31:24 +00002027 /// GeneratedCode - This is the buffer that we emit code to. The first bool
2028 /// indicates whether this is an exit predicate (something that should be
2029 /// tested, and if true, the match fails) [when true] or normal code to emit
2030 /// [when false].
2031 std::vector<std::pair<bool, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00002032 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2033 /// the set of patterns for each top-level opcode.
Evan Chengd7805a72006-02-09 07:16:09 +00002034 std::set<std::pair<bool, std::string> > &GeneratedDecl;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002035
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002036 std::string ChainName;
Evan Chenged66e852006-03-09 08:19:11 +00002037 bool NewTF;
Evan Chenge41bf822006-02-05 06:43:12 +00002038 bool DoReplace;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002039 unsigned TmpNo;
2040
2041 void emitCheck(const std::string &S) {
2042 if (!S.empty())
2043 GeneratedCode.push_back(std::make_pair(true, S));
2044 }
2045 void emitCode(const std::string &S) {
2046 if (!S.empty())
2047 GeneratedCode.push_back(std::make_pair(false, S));
2048 }
Evan Chengd7805a72006-02-09 07:16:09 +00002049 void emitDecl(const std::string &S, bool isSDNode=false) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002050 assert(!S.empty() && "Invalid declaration");
Evan Chengd7805a72006-02-09 07:16:09 +00002051 GeneratedDecl.insert(std::make_pair(isSDNode, S));
Evan Cheng21ad3922006-02-07 00:37:41 +00002052 }
Evan Chengb915f312005-12-09 22:45:35 +00002053public:
Evan Cheng58e84a62005-12-14 22:02:59 +00002054 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2055 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng21ad3922006-02-07 00:37:41 +00002056 std::vector<std::pair<bool, std::string> > &gc,
Evan Chengd7805a72006-02-09 07:16:09 +00002057 std::set<std::pair<bool, std::string> > &gd,
Evan Cheng21ad3922006-02-07 00:37:41 +00002058 bool dorep)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002059 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Chenged66e852006-03-09 08:19:11 +00002060 GeneratedCode(gc), GeneratedDecl(gd),
2061 NewTF(false), DoReplace(dorep), TmpNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +00002062
2063 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2064 /// if the match fails. At this point, we already know that the opcode for N
2065 /// matches, and the SDNode for the result has the RootName specified name.
Evan Chenge41bf822006-02-05 06:43:12 +00002066 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2067 const std::string &RootName, const std::string &ParentName,
2068 const std::string &ChainSuffix, bool &FoundChain) {
2069 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +00002070 // Emit instruction predicates. Each predicate is just a string for now.
2071 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002072 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +00002073 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2074 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2075 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +00002076 if (!Def->isSubClassOf("Predicate")) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002077 Def->dump();
2078 assert(0 && "Unknown predicate type!");
2079 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002080 if (!PredicateCheck.empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002081 PredicateCheck += " || ";
2082 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +00002083 }
2084 }
Chris Lattner8a0604b2006-01-28 20:31:24 +00002085
2086 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +00002087 }
2088
Evan Chengb915f312005-12-09 22:45:35 +00002089 if (N->isLeaf()) {
2090 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002091 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +00002092 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002093 return;
2094 } else if (!NodeIsComplexPattern(N)) {
2095 assert(0 && "Cannot match this as a leaf value!");
2096 abort();
2097 }
2098 }
2099
Chris Lattner488580c2006-01-28 19:06:51 +00002100 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002101 // we already saw this in the pattern, emit code to verify dagness.
2102 if (!N->getName().empty()) {
2103 std::string &VarMapEntry = VariableMap[N->getName()];
2104 if (VarMapEntry.empty()) {
2105 VarMapEntry = RootName;
2106 } else {
2107 // If we get here, this is a second reference to a specific name. Since
2108 // we already have checked that the first reference is valid, we don't
2109 // have to recursively match it, just check that it's the same as the
2110 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002111 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +00002112 return;
2113 }
Evan Chengf805c2e2006-01-12 19:35:54 +00002114
2115 if (!N->isLeaf())
2116 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +00002117 }
2118
2119
2120 // Emit code to load the child nodes and match their contents recursively.
2121 unsigned OpNo = 0;
Evan Chenge41bf822006-02-05 06:43:12 +00002122 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2123 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2124 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
Evan Cheng1feeeec2006-01-26 19:13:45 +00002125 bool EmittedUseCheck = false;
2126 bool EmittedSlctedCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +00002127 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +00002128 if (NodeHasChain)
2129 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +00002130 if (!isRoot) {
Evan Cheng1129e872005-12-10 00:09:17 +00002131 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
Evan Cheng61a02092006-04-28 02:08:10 +00002132 // Not in flight?
Evan Cheng55d0fa12006-04-28 18:54:11 +00002133 emitCheck("InFlightSet.count(" + RootName + ".Val) == 0");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002134 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002135 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +00002136 EmittedUseCheck = true;
2137 // hasOneUse() check is not strong enough. If the original node has
2138 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002139 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002140 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002141 "))");
2142
Evan Cheng1feeeec2006-01-26 19:13:45 +00002143 EmittedSlctedCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +00002144 if (NodeHasChain) {
2145 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2146 // has a chain use.
2147 // This a workaround for this problem:
2148 //
2149 // [ch, r : ld]
2150 // ^ ^
2151 // | |
2152 // [XX]--/ \- [flag : cmp]
2153 // ^ ^
2154 // | |
2155 // \---[br flag]-
2156 //
2157 // cmp + br should be considered as a single node as they are flagged
2158 // together. So, if the ld is folded into the cmp, the XX node in the
2159 // graph is now both an operand and a use of the ld/cmp/br node.
2160 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2161 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2162
2163 // If the immediate use can somehow reach this node through another
2164 // path, then can't fold it either or it will create a cycle.
2165 // e.g. In the following diagram, XX can reach ld through YY. If
2166 // ld is folded into XX, then YY is both a predecessor and a successor
2167 // of XX.
2168 //
2169 // [ld]
2170 // ^ ^
2171 // | |
2172 // / \---
2173 // / [YY]
2174 // | ^
2175 // [XX]-------|
2176 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2177 if (PInfo.getNumOperands() > 1 ||
2178 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2179 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2180 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
Evan Cheng6f8aaf22006-03-07 08:31:27 +00002181 if (PInfo.getNumOperands() > 1) {
2182 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2183 ".Val)");
2184 } else {
2185 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2186 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2187 ".Val))");
2188 }
Evan Chenge41bf822006-02-05 06:43:12 +00002189 }
Evan Chengb915f312005-12-09 22:45:35 +00002190 }
Evan Chenge41bf822006-02-05 06:43:12 +00002191
Evan Chengc15d18c2006-01-27 22:13:45 +00002192 if (NodeHasChain) {
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002193 ChainName = "Chain" + ChainSuffix;
Evan Cheng21ad3922006-02-07 00:37:41 +00002194 emitDecl(ChainName);
Evan Chenged66e852006-03-09 08:19:11 +00002195 if (FoundChain) {
2196 // FIXME: temporary workaround for a common case where chain
2197 // is a TokenFactor and the previous "inner" chain is an operand.
2198 NewTF = true;
2199 emitDecl("OldTF", true);
2200 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2201 RootName + ".Val, Chain.Val, OldTF)).Val");
2202 } else {
2203 FoundChain = true;
2204 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2205 }
Evan Cheng1cf6db22006-01-06 00:41:12 +00002206 }
Evan Chengb915f312005-12-09 22:45:35 +00002207 }
2208
Evan Cheng54597732006-01-26 00:22:25 +00002209 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002210 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +00002211 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +00002212 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2213 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +00002214 if (!isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002215 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2216 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2217 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +00002218 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2219 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002220 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +00002221 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +00002222 }
Evan Cheng1feeeec2006-01-26 19:13:45 +00002223 if (!EmittedSlctedCheck)
2224 // hasOneUse() check is not strong enough. If the original node has
2225 // already been selected, it may have been replaced with another.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002226 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
Chris Lattner67a202b2006-01-28 20:43:52 +00002227 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002228 "))");
Evan Cheng54597732006-01-26 00:22:25 +00002229 }
2230
Evan Chengb915f312005-12-09 22:45:35 +00002231 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002232 emitDecl(RootName + utostr(OpNo));
2233 emitCode(RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002234 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002235 TreePatternNode *Child = N->getChild(i);
2236
2237 if (!Child->isLeaf()) {
2238 // If it's not a leaf, recursively match.
2239 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
Chris Lattner67a202b2006-01-28 20:43:52 +00002240 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002241 CInfo.getEnumName());
Evan Chenge41bf822006-02-05 06:43:12 +00002242 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2243 ChainSuffix + utostr(OpNo), FoundChain);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002244 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002245 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2246 CInfo.getNumResults()));
Evan Chengb915f312005-12-09 22:45:35 +00002247 } else {
Chris Lattner488580c2006-01-28 19:06:51 +00002248 // If this child has a name associated with it, capture it in VarMap. If
Evan Chengb915f312005-12-09 22:45:35 +00002249 // we already saw this in the pattern, emit code to verify dagness.
2250 if (!Child->getName().empty()) {
2251 std::string &VarMapEntry = VariableMap[Child->getName()];
2252 if (VarMapEntry.empty()) {
2253 VarMapEntry = RootName + utostr(OpNo);
2254 } else {
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00002255 // If we get here, this is a second reference to a specific name.
2256 // Since we already have checked that the first reference is valid,
2257 // we don't have to recursively match it, just check that it's the
2258 // same as the previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +00002259 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
Evan Chengb4ad33c2006-01-19 01:55:45 +00002260 Duplicates.insert(RootName + utostr(OpNo));
Evan Chengb915f312005-12-09 22:45:35 +00002261 continue;
2262 }
2263 }
2264
2265 // Handle leaves of various types.
2266 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2267 Record *LeafRec = DI->getDef();
2268 if (LeafRec->isSubClassOf("RegisterClass")) {
2269 // Handle register references. Nothing to do here.
2270 } else if (LeafRec->isSubClassOf("Register")) {
Evan Cheng97938882005-12-22 02:24:50 +00002271 // Handle register references.
Evan Chengb915f312005-12-09 22:45:35 +00002272 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2273 // Handle complex pattern. Nothing to do here.
Evan Cheng01f318b2005-12-14 02:21:57 +00002274 } else if (LeafRec->getName() == "srcvalue") {
2275 // Place holder for SRCVALUE nodes. Nothing to do here.
Evan Chengb915f312005-12-09 22:45:35 +00002276 } else if (LeafRec->isSubClassOf("ValueType")) {
2277 // Make sure this is the specified value type.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002278 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002279 ")->getVT() == MVT::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002280 } else if (LeafRec->isSubClassOf("CondCode")) {
2281 // Make sure this is the specified cond code.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002282 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
Chris Lattner67a202b2006-01-28 20:43:52 +00002283 ")->get() == ISD::" + LeafRec->getName());
Evan Chengb915f312005-12-09 22:45:35 +00002284 } else {
2285 Child->dump();
Evan Cheng97938882005-12-22 02:24:50 +00002286 std::cerr << " ";
Evan Chengb915f312005-12-09 22:45:35 +00002287 assert(0 && "Unknown leaf type!");
2288 }
Chris Lattner488580c2006-01-28 19:06:51 +00002289 } else if (IntInit *II =
2290 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Chris Lattner8bc74722006-01-29 04:25:26 +00002291 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2292 unsigned CTmp = TmpNo++;
Andrew Lenharth8e517732006-01-29 05:22:37 +00002293 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
Chris Lattner8bc74722006-01-29 04:25:26 +00002294 RootName + utostr(OpNo) + ")->getSignExtended();");
2295
2296 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +00002297 } else {
2298 Child->dump();
2299 assert(0 && "Unknown leaf type!");
2300 }
2301 }
2302 }
2303
2304 // If there is a node predicate for this, emit the call.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002305 if (!N->getPredicateFn().empty())
Chris Lattner67a202b2006-01-28 20:43:52 +00002306 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
Evan Chengb915f312005-12-09 22:45:35 +00002307 }
2308
2309 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2310 /// we actually have to build a DAG!
2311 std::pair<unsigned, unsigned>
Chris Lattner947604b2006-03-24 21:52:20 +00002312 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2313 bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002314 // This is something selected from the pattern we matched.
2315 if (!N->getName().empty()) {
Evan Chengb915f312005-12-09 22:45:35 +00002316 std::string &Val = VariableMap[N->getName()];
2317 assert(!Val.empty() &&
2318 "Variable referenced but not defined and not caught earlier!");
2319 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2320 // Already selected this operand, just return the tmpval.
2321 return std::make_pair(1, atoi(Val.c_str()+3));
2322 }
2323
2324 const ComplexPattern *CP;
2325 unsigned ResNo = TmpNo++;
2326 unsigned NumRes = 1;
2327 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +00002328 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +00002329 std::string CastType;
Nate Begemanb73628b2005-12-30 00:12:56 +00002330 switch (N->getTypeNum(0)) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002331 default: assert(0 && "Unknown type for constant node!");
Chris Lattner78593132006-01-29 20:01:35 +00002332 case MVT::i1: CastType = "bool"; break;
2333 case MVT::i8: CastType = "unsigned char"; break;
2334 case MVT::i16: CastType = "unsigned short"; break;
2335 case MVT::i32: CastType = "unsigned"; break;
2336 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +00002337 }
Chris Lattner78593132006-01-29 20:01:35 +00002338 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
Andrew Lenharth2cba57c2006-01-29 05:17:22 +00002339 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
Evan Cheng21ad3922006-02-07 00:37:41 +00002340 emitDecl("Tmp" + utostr(ResNo));
2341 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002342 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2343 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengbb48e332006-01-12 07:54:57 +00002344 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +00002345 Record *Op = OperatorMap[N->getName()];
2346 // Transform ExternalSymbol to TargetExternalSymbol
2347 if (Op && Op->getName() == "externalsym") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002348 emitDecl("Tmp" + utostr(ResNo));
2349 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002350 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2351 Val + ")->getSymbol(), MVT::" +
2352 getEnumName(N->getTypeNum(0)) + ");");
2353 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002354 emitDecl("Tmp" + utostr(ResNo));
2355 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002356 }
Evan Chengb915f312005-12-09 22:45:35 +00002357 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
Evan Chengf805c2e2006-01-12 19:35:54 +00002358 Record *Op = OperatorMap[N->getName()];
2359 // Transform GlobalAddress to TargetGlobalAddress
2360 if (Op && Op->getName() == "globaladdr") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002361 emitDecl("Tmp" + utostr(ResNo));
2362 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +00002363 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2364 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2365 ");");
2366 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002367 emitDecl("Tmp" + utostr(ResNo));
2368 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002369 }
Chris Lattner4e3c8e512006-01-03 22:55:16 +00002370 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Cheng21ad3922006-02-07 00:37:41 +00002371 emitDecl("Tmp" + utostr(ResNo));
2372 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengbb48e332006-01-12 07:54:57 +00002373 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
Evan Cheng21ad3922006-02-07 00:37:41 +00002374 emitDecl("Tmp" + utostr(ResNo));
2375 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Chengb915f312005-12-09 22:45:35 +00002376 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2377 std::string Fn = CP->getSelectFunc();
2378 NumRes = CP->getNumOperands();
Evan Cheng21ad3922006-02-07 00:37:41 +00002379 for (unsigned i = 0; i < NumRes; ++i)
2380 emitDecl("Tmp" + utostr(i+ResNo));
Chris Lattner8a0604b2006-01-28 20:31:24 +00002381
Evan Cheng21ad3922006-02-07 00:37:41 +00002382 std::string Code = Fn + "(" + Val;
Jeff Cohen60e91872006-01-04 03:23:30 +00002383 for (unsigned i = 0; i < NumRes; i++)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002384 Code += ", Tmp" + utostr(i + ResNo);
2385 emitCheck(Code + ")");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002386
Evan Cheng61a02092006-04-28 02:08:10 +00002387 for (unsigned i = 0; i < NumRes; ++i) {
2388 emitCode("InFlightSet.insert(Tmp" + utostr(i+ResNo) + ".Val);");
2389 InflightNodes.push_back("Tmp" + utostr(i+ResNo));
2390 }
Evan Cheng2216d8a2006-02-05 05:22:18 +00002391 for (unsigned i = 0; i < NumRes; ++i)
Evan Cheng34167212006-02-09 00:37:58 +00002392 emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
Evan Cheng2216d8a2006-02-05 05:22:18 +00002393 utostr(i+ResNo) + ");");
Evan Cheng9c4815a2006-02-04 08:50:49 +00002394
Evan Chengb915f312005-12-09 22:45:35 +00002395 TmpNo = ResNo + NumRes;
2396 } else {
Evan Cheng21ad3922006-02-07 00:37:41 +00002397 emitDecl("Tmp" + utostr(ResNo));
Evan Cheng863bf5a2006-03-20 22:53:06 +00002398 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2399 // node even if it isn't one. Don't select it.
2400 if (LikeLeaf)
2401 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
Evan Cheng61a02092006-04-28 02:08:10 +00002402 else {
Evan Cheng863bf5a2006-03-20 22:53:06 +00002403 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
Evan Cheng61a02092006-04-28 02:08:10 +00002404 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +00002405
2406 if (isRoot && N->isLeaf()) {
2407 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2408 emitCode("return;");
2409 }
Evan Chengb915f312005-12-09 22:45:35 +00002410 }
2411 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2412 // value if used multiple times by this pattern result.
2413 Val = "Tmp"+utostr(ResNo);
2414 return std::make_pair(NumRes, ResNo);
2415 }
Evan Chengb915f312005-12-09 22:45:35 +00002416 if (N->isLeaf()) {
2417 // If this is an explicit register reference, handle it.
2418 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2419 unsigned ResNo = TmpNo++;
2420 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002421 emitDecl("Tmp" + utostr(ResNo));
2422 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002423 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2424 getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002425 return std::make_pair(1, ResNo);
2426 }
2427 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2428 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +00002429 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng21ad3922006-02-07 00:37:41 +00002430 emitDecl("Tmp" + utostr(ResNo));
2431 emitCode("Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002432 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2433 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
Evan Chengb915f312005-12-09 22:45:35 +00002434 return std::make_pair(1, ResNo);
2435 }
2436
2437 N->dump();
2438 assert(0 && "Unknown leaf type!");
2439 return std::make_pair(1, ~0U);
2440 }
2441
2442 Record *Op = N->getOperator();
2443 if (Op->isSubClassOf("Instruction")) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002444 const CodeGenTarget &CGT = ISE.getTargetInfo();
2445 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Evan Cheng4fba2812005-12-20 07:37:41 +00002446 const DAGInstruction &Inst = ISE.getInstruction(Op);
Evan Cheng045953c2006-05-10 00:05:46 +00002447 TreePattern *InstPat = Inst.getPattern();
2448 TreePatternNode *InstPatNode =
2449 isRoot ? (InstPat ? InstPat->getOnlyTree() : Pattern)
2450 : (InstPat ? InstPat->getOnlyTree() : NULL);
2451 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
2452 InstPatNode = InstPatNode->getChild(1);
2453 }
2454 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
2455 bool HasImpResults = isRoot && Inst.getNumImpResults() > 0;
2456 bool NodeHasOptInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002457 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002458 bool NodeHasInFlag = isRoot &&
Evan Cheng54597732006-01-26 00:22:25 +00002459 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
Evan Cheng045953c2006-05-10 00:05:46 +00002460 bool NodeHasOutFlag = HasImpResults || (isRoot &&
2461 PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2462 bool NodeHasChain = InstPatNode &&
2463 PatternHasProperty(InstPatNode, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002464 bool InputHasChain = isRoot &&
2465 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng4fba2812005-12-20 07:37:41 +00002466
Evan Cheng045953c2006-05-10 00:05:46 +00002467 if (NodeHasInFlag || NodeHasOutFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng21ad3922006-02-07 00:37:41 +00002468 emitDecl("InFlag");
Evan Cheng045953c2006-05-10 00:05:46 +00002469 if (NodeHasOptInFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002470 emitCode("bool HasOptInFlag = false;");
Evan Cheng4fba2812005-12-20 07:37:41 +00002471
Evan Cheng823b7522006-01-19 21:57:10 +00002472 // How many results is this pattern expected to produce?
Evan Chenged66e852006-03-09 08:19:11 +00002473 unsigned PatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +00002474 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2475 MVT::ValueType VT = Pattern->getTypeNum(i);
2476 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Chenged66e852006-03-09 08:19:11 +00002477 PatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +00002478 }
2479
Evan Chengb915f312005-12-09 22:45:35 +00002480 // Determine operand emission order. Complex pattern first.
2481 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2482 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2483 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2484 TreePatternNode *Child = N->getChild(i);
2485 if (i == 0) {
2486 EmitOrder.push_back(std::make_pair(i, Child));
2487 OI = EmitOrder.begin();
2488 } else if (NodeIsComplexPattern(Child)) {
2489 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2490 } else {
2491 EmitOrder.push_back(std::make_pair(i, Child));
2492 }
2493 }
2494
Evan Cheng61a02092006-04-28 02:08:10 +00002495 // Make sure these operands which would be selected won't be folded while
2496 // the isel traverses the DAG upward.
Evan Chengb915f312005-12-09 22:45:35 +00002497 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2498 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
Evan Cheng61a02092006-04-28 02:08:10 +00002499 TreePatternNode *Child = EmitOrder[i].second;
2500 if (!Child->getName().empty()) {
2501 std::string &Val = VariableMap[Child->getName()];
2502 assert(!Val.empty() &&
2503 "Variable referenced but not defined and not caught earlier!");
2504 if (Child->isLeaf() && !NodeGetComplexPattern(Child, ISE)) {
2505 emitCode("InFlightSet.insert(" + Val + ".Val);");
2506 InflightNodes.push_back(Val);
2507 }
2508 }
2509 }
2510
2511 // Emit all of the operands.
2512 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
Evan Chengb915f312005-12-09 22:45:35 +00002513 unsigned OpOrder = EmitOrder[i].first;
2514 TreePatternNode *Child = EmitOrder[i].second;
2515 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2516 NumTemps[OpOrder] = NumTemp;
2517 }
2518
2519 // List all the operands in the right order.
2520 std::vector<unsigned> Ops;
2521 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2522 for (unsigned j = 0; j < NumTemps[i].first; j++)
2523 Ops.push_back(NumTemps[i].second + j);
2524 }
2525
Evan Chengb915f312005-12-09 22:45:35 +00002526 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +00002527 bool ChainEmitted = NodeHasChain;
2528 if (NodeHasChain)
Evan Cheng34167212006-02-09 00:37:58 +00002529 emitCode("Select(" + ChainName + ", " + ChainName + ");");
Evan Cheng045953c2006-05-10 00:05:46 +00002530 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng54597732006-01-26 00:22:25 +00002531 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
Evan Chengb915f312005-12-09 22:45:35 +00002532
Evan Cheng045953c2006-05-10 00:05:46 +00002533 if (isRoot) {
2534 // The operands have been selected. Remove them from InFlightSet.
2535 for (std::vector<std::string>::iterator AI = InflightNodes.begin(),
2536 AE = InflightNodes.end(); AI != AE; ++AI)
2537 emitCode("InFlightSet.erase(" + *AI + ".Val);");
2538 }
2539
Evan Chengb915f312005-12-09 22:45:35 +00002540 unsigned NumResults = Inst.getNumResults();
2541 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002542 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
2543 NodeHasOptInFlag) {
Evan Cheng045953c2006-05-10 00:05:46 +00002544 if (NodeHasOptInFlag) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002545 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
Evan Chengd7805a72006-02-09 07:16:09 +00002546 emitDecl("ResNode", true);
Chris Lattner8a0604b2006-01-28 20:31:24 +00002547 emitCode("if (HasOptInFlag)");
Evan Chengd7805a72006-02-09 07:16:09 +00002548 std::string Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002549 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002550
Evan Cheng9789aaa2006-01-24 20:46:50 +00002551 // Output order: results, chain, flags
2552 // Result types.
Evan Cheng3eff89b2006-05-10 02:47:57 +00002553 if (PatResults > 0) {
Evan Cheng9789aaa2006-01-24 20:46:50 +00002554 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002555 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng9789aaa2006-01-24 20:46:50 +00002556 }
Evan Cheng045953c2006-05-10 00:05:46 +00002557 if (NodeHasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002558 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002559 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002560 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002561
2562 // Inputs.
2563 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002564 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002565 if (NodeHasChain) Code += ", " + ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +00002566 emitCode(Code + ", InFlag);");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002567
Chris Lattner8a0604b2006-01-28 20:31:24 +00002568 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002569 Code = " ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002570 II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002571
2572 // Output order: results, chain, flags
2573 // Result types.
Evan Cheng3eff89b2006-05-10 02:47:57 +00002574 if (PatResults > 0 && N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002575 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng045953c2006-05-10 00:05:46 +00002576 if (NodeHasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002577 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002578 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002579 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002580
2581 // Inputs.
2582 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002583 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002584 if (NodeHasChain) Code += ", " + ChainName + ");";
Chris Lattner8a0604b2006-01-28 20:31:24 +00002585 emitCode(Code);
Evan Cheng3eff89b2006-05-10 02:47:57 +00002586
2587 if (NodeHasChain)
2588 // Remember which op produces the chain.
2589 emitCode(ChainName + " = SDOperand(ResNode" +
2590 ", " + utostr(PatResults) + ");");
Evan Cheng9789aaa2006-01-24 20:46:50 +00002591 } else {
Evan Cheng045953c2006-05-10 00:05:46 +00002592 std::string Code;
Evan Cheng3eff89b2006-05-10 02:47:57 +00002593 std::string NodeName;
Evan Cheng045953c2006-05-10 00:05:46 +00002594 if (!isRoot) {
Evan Cheng3eff89b2006-05-10 02:47:57 +00002595 NodeName = "Tmp" + utostr(ResNo);
Evan Cheng045953c2006-05-10 00:05:46 +00002596 emitDecl(NodeName);
2597 Code = NodeName + " = SDOperand(";
2598 } else {
Evan Cheng3eff89b2006-05-10 02:47:57 +00002599 NodeName = "ResNode";
Evan Cheng045953c2006-05-10 00:05:46 +00002600 emitDecl(NodeName, true);
2601 Code = NodeName + " = ";
2602 }
2603 Code += "CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002604 II.Namespace + "::" + II.TheDef->getName();
Evan Cheng9789aaa2006-01-24 20:46:50 +00002605
2606 // Output order: results, chain, flags
2607 // Result types.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002608 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2609 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng045953c2006-05-10 00:05:46 +00002610 if (NodeHasChain)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002611 Code += ", MVT::Other";
Evan Cheng54597732006-01-26 00:22:25 +00002612 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002613 Code += ", MVT::Flag";
Evan Cheng9789aaa2006-01-24 20:46:50 +00002614
2615 // Inputs.
2616 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002617 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002618 if (NodeHasChain) Code += ", " + ChainName;
2619 if (NodeHasInFlag || HasImpInputs) Code += ", InFlag";
2620 if (!isRoot)
2621 emitCode(Code + "), 0);");
2622 else
2623 emitCode(Code + ");");
Evan Cheng3eff89b2006-05-10 02:47:57 +00002624
2625 if (NodeHasChain)
2626 // Remember which op produces the chain.
2627 if (!isRoot)
2628 emitCode(ChainName + " = SDOperand(" + NodeName +
2629 ".Val, " + utostr(PatResults) + ");");
2630 else
2631 emitCode(ChainName + " = SDOperand(" + NodeName +
2632 ", " + utostr(PatResults) + ");");
Evan Chengbcecf332005-12-17 01:19:28 +00002633 }
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002634
Evan Cheng045953c2006-05-10 00:05:46 +00002635 if (!isRoot)
2636 return std::make_pair(1, ResNo);
2637
Evan Chenged66e852006-03-09 08:19:11 +00002638 if (NewTF)
2639 emitCode("if (OldTF) "
2640 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2641 ChainName + ".Val, 0);");
2642
2643 for (unsigned i = 0; i < NumResults; i++)
Evan Cheng67212a02006-02-09 22:12:27 +00002644 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Chenged66e852006-03-09 08:19:11 +00002645 utostr(i) + ", ResNode, " + utostr(i) + ");");
Evan Chengf9fc25d2005-12-19 22:40:04 +00002646
Evan Cheng54597732006-01-26 00:22:25 +00002647 if (NodeHasOutFlag)
Evan Chengd7805a72006-02-09 07:16:09 +00002648 emitCode("InFlag = SDOperand(ResNode, " +
Evan Cheng045953c2006-05-10 00:05:46 +00002649 utostr(NumResults + (unsigned)NodeHasChain) + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00002650
Chris Lattner8a0604b2006-01-28 20:31:24 +00002651 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
Evan Chenged66e852006-03-09 08:19:11 +00002652 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2653 "0, ResNode, 0);");
2654 NumResults = 1;
Evan Cheng97938882005-12-22 02:24:50 +00002655 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002656
Evan Cheng045953c2006-05-10 00:05:46 +00002657 if (InputHasChain) {
Evan Cheng67212a02006-02-09 22:12:27 +00002658 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Cheng3eff89b2006-05-10 02:47:57 +00002659 utostr(PatResults) + ", " + ChainName + ".Val, " +
2660 ChainName + ".ResNo" + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002661 if (DoReplace)
Evan Chenged66e852006-03-09 08:19:11 +00002662 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
Evan Cheng3eff89b2006-05-10 02:47:57 +00002663 utostr(PatResults) + ", " + ChainName + ".Val, " +
2664 ChainName + ".ResNo" + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002665 }
2666
Evan Cheng97938882005-12-22 02:24:50 +00002667 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002668 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00002669 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Evan Cheng67212a02006-02-09 22:12:27 +00002670 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2671 FoldedChains[j].first + ".Val, " +
2672 utostr(FoldedChains[j].second) + ", ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002673 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002674
2675 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2676 std::string Code =
Evan Cheng67212a02006-02-09 22:12:27 +00002677 FoldedChains[j].first + ".Val, " +
2678 utostr(FoldedChains[j].second) + ", ";
2679 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
Evan Chenged66e852006-03-09 08:19:11 +00002680 utostr(NumResults) + ");");
Evan Chenge41bf822006-02-05 06:43:12 +00002681 }
Evan Chengb915f312005-12-09 22:45:35 +00002682 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00002683
Evan Cheng54597732006-01-26 00:22:25 +00002684 if (NodeHasOutFlag)
Evan Cheng67212a02006-02-09 22:12:27 +00002685 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
Evan Cheng045953c2006-05-10 00:05:46 +00002686 utostr(PatResults + (unsigned)InputHasChain) +
Evan Chenged66e852006-03-09 08:19:11 +00002687 ", InFlag.Val, InFlag.ResNo);");
Evan Cheng97938882005-12-22 02:24:50 +00002688
Evan Chenged66e852006-03-09 08:19:11 +00002689 // User does not expect the instruction would produce a chain!
Evan Cheng045953c2006-05-10 00:05:46 +00002690 bool AddedChain = NodeHasChain && !InputHasChain;
Evan Cheng54597732006-01-26 00:22:25 +00002691 if (AddedChain && NodeHasOutFlag) {
Evan Chenged66e852006-03-09 08:19:11 +00002692 if (PatResults == 0) {
Evan Chengd7805a72006-02-09 07:16:09 +00002693 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002694 } else {
Evan Chenged66e852006-03-09 08:19:11 +00002695 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
Evan Chengd7805a72006-02-09 07:16:09 +00002696 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002697 emitCode("else");
Evan Chengd7805a72006-02-09 07:16:09 +00002698 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
Evan Cheng97938882005-12-22 02:24:50 +00002699 }
Evan Cheng3eff89b2006-05-10 02:47:57 +00002700 } else if (InputHasChain && !NodeHasChain) {
2701 // One of the inner node produces a chain.
2702 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2703 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2704 if (NodeHasOutFlag) {
2705 emitCode("else if (N.ResNo > " + utostr(PatResults) + ")");
2706 emitCode(" Result = SDOperand(ResNode, N.ResNo-1);");
2707 }
2708 emitCode("else");
2709 emitCode(" Result = SDOperand(" + ChainName + ".Val, " + ChainName + ".ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002710 } else {
Evan Chengd7805a72006-02-09 07:16:09 +00002711 emitCode("Result = SDOperand(ResNode, N.ResNo);");
Evan Cheng4fba2812005-12-20 07:37:41 +00002712 }
Evan Chengb915f312005-12-09 22:45:35 +00002713 } else {
2714 // If this instruction is the root, and if there is only one use of it,
2715 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
Chris Lattner8a0604b2006-01-28 20:31:24 +00002716 emitCode("if (N.Val->hasOneUse()) {");
Evan Cheng34167212006-02-09 00:37:58 +00002717 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002718 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002719 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002720 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002721 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002722 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002723 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002724 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002725 if (NodeHasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002726 Code += ", InFlag";
2727 emitCode(Code + ");");
2728 emitCode("} else {");
Evan Chengd7805a72006-02-09 07:16:09 +00002729 emitDecl("ResNode", true);
2730 Code = " ResNode = CurDAG->getTargetNode(" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002731 II.Namespace + "::" + II.TheDef->getName();
Nate Begemanb73628b2005-12-30 00:12:56 +00002732 if (N->getTypeNum(0) != MVT::isVoid)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002733 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
Evan Cheng54597732006-01-26 00:22:25 +00002734 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002735 Code += ", MVT::Flag";
Evan Chengb915f312005-12-09 22:45:35 +00002736 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002737 Code += ", Tmp" + utostr(Ops[i]);
Evan Cheng045953c2006-05-10 00:05:46 +00002738 if (NodeHasInFlag || HasImpInputs)
Chris Lattner8a0604b2006-01-28 20:31:24 +00002739 Code += ", InFlag";
2740 emitCode(Code + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002741 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2742 "ResNode, 0);");
2743 emitCode(" Result = SDOperand(ResNode, 0);");
Chris Lattner8a0604b2006-01-28 20:31:24 +00002744 emitCode("}");
Evan Chengb915f312005-12-09 22:45:35 +00002745 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002746
Evan Cheng34167212006-02-09 00:37:58 +00002747 if (isRoot)
2748 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002749 return std::make_pair(1, ResNo);
2750 } else if (Op->isSubClassOf("SDNodeXForm")) {
2751 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00002752 // PatLeaf node - the operand may or may not be a leaf node. But it should
2753 // behave like one.
2754 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
Evan Chengb915f312005-12-09 22:45:35 +00002755 unsigned ResNo = TmpNo++;
Evan Cheng21ad3922006-02-07 00:37:41 +00002756 emitDecl("Tmp" + utostr(ResNo));
2757 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Chris Lattner8a0604b2006-01-28 20:31:24 +00002758 + "(Tmp" + utostr(OpVal) + ".Val);");
Evan Chengb915f312005-12-09 22:45:35 +00002759 if (isRoot) {
Evan Cheng67212a02006-02-09 22:12:27 +00002760 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2761 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2762 utostr(ResNo) + ".ResNo);");
Evan Cheng34167212006-02-09 00:37:58 +00002763 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2764 emitCode("return;");
Evan Chengb915f312005-12-09 22:45:35 +00002765 }
2766 return std::make_pair(1, ResNo);
2767 } else {
2768 N->dump();
Chris Lattner7893f132006-01-11 01:33:49 +00002769 std::cerr << "\n";
2770 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00002771 }
2772 }
2773
Chris Lattner488580c2006-01-28 19:06:51 +00002774 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2775 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00002776 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2777 /// for, this returns true otherwise false if Pat has all types.
2778 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2779 const std::string &Prefix) {
2780 // Did we find one?
2781 if (!Pat->hasTypeSet()) {
2782 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00002783 Pat->setTypes(Other->getExtTypes());
Chris Lattner67a202b2006-01-28 20:43:52 +00002784 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002785 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00002786 return true;
Evan Chengb915f312005-12-09 22:45:35 +00002787 }
2788
Evan Cheng51fecc82006-01-09 18:27:06 +00002789 unsigned OpNo =
2790 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002791 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2792 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2793 Prefix + utostr(OpNo)))
2794 return true;
2795 return false;
2796 }
2797
2798private:
Evan Cheng54597732006-01-26 00:22:25 +00002799 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00002800 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00002801 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2802 bool &ChainEmitted, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00002803 const CodeGenTarget &T = ISE.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00002804 unsigned OpNo =
2805 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
Evan Cheng54597732006-01-26 00:22:25 +00002806 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2807 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
Evan Chengb915f312005-12-09 22:45:35 +00002808 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2809 TreePatternNode *Child = N->getChild(i);
2810 if (!Child->isLeaf()) {
Evan Cheng54597732006-01-26 00:22:25 +00002811 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
Evan Chengb915f312005-12-09 22:45:35 +00002812 } else {
2813 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00002814 if (!Child->getName().empty()) {
2815 std::string Name = RootName + utostr(OpNo);
2816 if (Duplicates.find(Name) != Duplicates.end())
2817 // A duplicate! Do not emit a copy for this node.
2818 continue;
2819 }
2820
Evan Chengb915f312005-12-09 22:45:35 +00002821 Record *RR = DI->getDef();
2822 if (RR->isSubClassOf("Register")) {
2823 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00002824 if (RVT == MVT::Flag) {
Evan Cheng34167212006-02-09 00:37:58 +00002825 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
Evan Chengb2c6d492006-01-11 22:16:13 +00002826 } else {
2827 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002828 emitDecl("Chain");
2829 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002830 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00002831 ChainEmitted = true;
2832 }
Evan Cheng34167212006-02-09 00:37:58 +00002833 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2834 RootName + utostr(OpNo) + ");");
Evan Cheng67212a02006-02-09 22:12:27 +00002835 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002836 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
Evan Cheng34167212006-02-09 00:37:58 +00002837 ", MVT::" + getEnumName(RVT) + "), " +
Evan Chengd7805a72006-02-09 07:16:09 +00002838 RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng67212a02006-02-09 22:12:27 +00002839 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2840 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00002841 }
2842 }
2843 }
2844 }
2845 }
Evan Cheng54597732006-01-26 00:22:25 +00002846
2847 if (HasInFlag || HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002848 std::string Code;
Evan Cheng54597732006-01-26 00:22:25 +00002849 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002850 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2851 ") {");
2852 Code = " ";
Evan Cheng54597732006-01-26 00:22:25 +00002853 }
Evan Cheng34167212006-02-09 00:37:58 +00002854 emitCode(Code + "Select(InFlag, " + RootName +
2855 ".getOperand(" + utostr(OpNo) + "));");
Evan Cheng54597732006-01-26 00:22:25 +00002856 if (HasOptInFlag) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00002857 emitCode(" HasOptInFlag = true;");
2858 emitCode("}");
Evan Cheng54597732006-01-26 00:22:25 +00002859 }
2860 }
Evan Chengb915f312005-12-09 22:45:35 +00002861 }
Evan Cheng4fba2812005-12-20 07:37:41 +00002862
2863 /// EmitCopyFromRegs - Emit code to copy result to physical registers
Evan Cheng7b05bd52005-12-23 22:11:47 +00002864 /// as specified by the instruction. It returns true if any copy is
2865 /// emitted.
Evan Chengb2c6d492006-01-11 22:16:13 +00002866 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
Evan Cheng7b05bd52005-12-23 22:11:47 +00002867 bool RetVal = false;
Evan Cheng4fba2812005-12-20 07:37:41 +00002868 Record *Op = N->getOperator();
2869 if (Op->isSubClassOf("Instruction")) {
2870 const DAGInstruction &Inst = ISE.getInstruction(Op);
2871 const CodeGenTarget &CGT = ISE.getTargetInfo();
Evan Cheng4fba2812005-12-20 07:37:41 +00002872 unsigned NumImpResults = Inst.getNumImpResults();
2873 for (unsigned i = 0; i < NumImpResults; i++) {
2874 Record *RR = Inst.getImpResult(i);
2875 if (RR->isSubClassOf("Register")) {
2876 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2877 if (RVT != MVT::Flag) {
Evan Chengb2c6d492006-01-11 22:16:13 +00002878 if (!ChainEmitted) {
Evan Cheng21ad3922006-02-07 00:37:41 +00002879 emitDecl("Chain");
2880 emitCode("Chain = CurDAG->getEntryNode();");
Evan Chengb2c6d492006-01-11 22:16:13 +00002881 ChainEmitted = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +00002882 ChainName = "Chain";
Evan Cheng4fba2812005-12-20 07:37:41 +00002883 }
Evan Chengd7805a72006-02-09 07:16:09 +00002884 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +00002885 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
Evan Chengd7805a72006-02-09 07:16:09 +00002886 ", InFlag).Val;");
2887 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2888 emitCode("InFlag = SDOperand(ResNode, 2);");
Evan Cheng7b05bd52005-12-23 22:11:47 +00002889 RetVal = true;
Evan Cheng4fba2812005-12-20 07:37:41 +00002890 }
2891 }
2892 }
2893 }
Evan Cheng7b05bd52005-12-23 22:11:47 +00002894 return RetVal;
Evan Cheng4fba2812005-12-20 07:37:41 +00002895 }
Evan Chengb915f312005-12-09 22:45:35 +00002896};
2897
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00002898/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2899/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00002900/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner8bc74722006-01-29 04:25:26 +00002901void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
Evan Chenge41bf822006-02-05 06:43:12 +00002902 std::vector<std::pair<bool, std::string> > &GeneratedCode,
Evan Chengd7805a72006-02-09 07:16:09 +00002903 std::set<std::pair<bool, std::string> > &GeneratedDecl,
Evan Chenge41bf822006-02-05 06:43:12 +00002904 bool DoReplace) {
Evan Cheng58e84a62005-12-14 22:02:59 +00002905 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2906 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Cheng21ad3922006-02-07 00:37:41 +00002907 GeneratedCode, GeneratedDecl, DoReplace);
Evan Chengb915f312005-12-09 22:45:35 +00002908
Chris Lattner8fc35682005-09-23 23:16:51 +00002909 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00002910 bool FoundChain = false;
Evan Chenge41bf822006-02-05 06:43:12 +00002911 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00002912
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002913 // TP - Get *SOME* tree pattern, we don't care which.
2914 TreePattern &TP = *PatternFragments.begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00002915
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002916 // At this point, we know that we structurally match the pattern, but the
2917 // types of the nodes may not match. Figure out the fewest number of type
2918 // comparisons we need to emit. For example, if there is only one integer
2919 // type supported by a target, there should be no type comparisons at all for
2920 // integer patterns!
2921 //
2922 // To figure out the fewest number of type checks needed, clone the pattern,
2923 // remove the types, then perform type inference on the pattern as a whole.
2924 // If there are unresolved types, emit an explicit check for those types,
2925 // apply the type to the tree, then rerun type inference. Iterate until all
2926 // types are resolved.
2927 //
Evan Cheng58e84a62005-12-14 22:02:59 +00002928 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002929 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00002930
2931 do {
2932 // Resolve/propagate as many types as possible.
2933 try {
2934 bool MadeChange = true;
2935 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00002936 MadeChange = Pat->ApplyTypeConstraints(TP,
2937 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00002938 } catch (...) {
2939 assert(0 && "Error: could not find consistent types for something we"
2940 " already decided was ok!");
2941 abort();
2942 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002943
Chris Lattner7e82f132005-10-15 21:34:21 +00002944 // Insert a check for an unresolved type and add it to the tree. If we find
2945 // an unresolved type to add a check for, this returns true and we iterate,
2946 // otherwise we are done.
Evan Cheng58e84a62005-12-14 22:02:59 +00002947 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00002948
Evan Cheng863bf5a2006-03-20 22:53:06 +00002949 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00002950 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00002951}
2952
Chris Lattner24e00a42006-01-29 04:41:05 +00002953/// EraseCodeLine - Erase one code line from all of the patterns. If removing
2954/// a line causes any of them to be empty, remove them and return true when
2955/// done.
2956static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2957 std::vector<std::pair<bool, std::string> > > >
2958 &Patterns) {
2959 bool ErasedPatterns = false;
2960 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2961 Patterns[i].second.pop_back();
2962 if (Patterns[i].second.empty()) {
2963 Patterns.erase(Patterns.begin()+i);
2964 --i; --e;
2965 ErasedPatterns = true;
2966 }
2967 }
2968 return ErasedPatterns;
2969}
2970
Chris Lattner8bc74722006-01-29 04:25:26 +00002971/// EmitPatterns - Emit code for at least one pattern, but try to group common
2972/// code together between the patterns.
2973void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
2974 std::vector<std::pair<bool, std::string> > > >
2975 &Patterns, unsigned Indent,
2976 std::ostream &OS) {
2977 typedef std::pair<bool, std::string> CodeLine;
2978 typedef std::vector<CodeLine> CodeList;
2979 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2980
2981 if (Patterns.empty()) return;
2982
Chris Lattner24e00a42006-01-29 04:41:05 +00002983 // Figure out how many patterns share the next code line. Explicitly copy
2984 // FirstCodeLine so that we don't invalidate a reference when changing
2985 // Patterns.
2986 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00002987 unsigned LastMatch = Patterns.size()-1;
2988 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2989 --LastMatch;
2990
2991 // If not all patterns share this line, split the list into two pieces. The
2992 // first chunk will use this line, the second chunk won't.
2993 if (LastMatch != 0) {
2994 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2995 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2996
2997 // FIXME: Emit braces?
2998 if (Shared.size() == 1) {
2999 PatternToMatch &Pattern = *Shared.back().first;
3000 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3001 Pattern.getSrcPattern()->print(OS);
3002 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3003 Pattern.getDstPattern()->print(OS);
3004 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003005 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003006 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003007 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003008 << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00003009 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003010 }
3011 if (!FirstCodeLine.first) {
3012 OS << std::string(Indent, ' ') << "{\n";
3013 Indent += 2;
3014 }
3015 EmitPatterns(Shared, Indent, OS);
3016 if (!FirstCodeLine.first) {
3017 Indent -= 2;
3018 OS << std::string(Indent, ' ') << "}\n";
3019 }
3020
3021 if (Other.size() == 1) {
3022 PatternToMatch &Pattern = *Other.back().first;
3023 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
3024 Pattern.getSrcPattern()->print(OS);
3025 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
3026 Pattern.getDstPattern()->print(OS);
3027 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00003028 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00003029 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Evan Chengc81d2a02006-04-19 20:36:09 +00003030 << getPatternSize(Pattern.getSrcPattern(), *this) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00003031 << " cost = "
Evan Chengfbad7082006-02-18 02:33:09 +00003032 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00003033 }
3034 EmitPatterns(Other, Indent, OS);
3035 return;
3036 }
3037
Chris Lattner24e00a42006-01-29 04:41:05 +00003038 // Remove this code from all of the patterns that share it.
3039 bool ErasedPatterns = EraseCodeLine(Patterns);
3040
Chris Lattner8bc74722006-01-29 04:25:26 +00003041 bool isPredicate = FirstCodeLine.first;
3042
3043 // Otherwise, every pattern in the list has this line. Emit it.
3044 if (!isPredicate) {
3045 // Normal code.
3046 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
3047 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00003048 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
3049
3050 // If the next code line is another predicate, and if all of the pattern
3051 // in this group share the same next line, emit it inline now. Do this
3052 // until we run out of common predicates.
3053 while (!ErasedPatterns && Patterns.back().second.back().first) {
3054 // Check that all of fhe patterns in Patterns end with the same predicate.
3055 bool AllEndWithSamePredicate = true;
3056 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
3057 if (Patterns[i].second.back() != Patterns.back().second.back()) {
3058 AllEndWithSamePredicate = false;
3059 break;
3060 }
3061 // If all of the predicates aren't the same, we can't share them.
3062 if (!AllEndWithSamePredicate) break;
3063
3064 // Otherwise we can. Emit it shared now.
3065 OS << " &&\n" << std::string(Indent+4, ' ')
3066 << Patterns.back().second.back().second;
3067 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00003068 }
Chris Lattner24e00a42006-01-29 04:41:05 +00003069
3070 OS << ") {\n";
3071 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00003072 }
3073
3074 EmitPatterns(Patterns, Indent, OS);
3075
3076 if (isPredicate)
3077 OS << std::string(Indent-2, ' ') << "}\n";
3078}
3079
3080
Chris Lattner37481472005-09-26 21:59:35 +00003081
3082namespace {
3083 /// CompareByRecordName - An ordering predicate that implements less-than by
3084 /// comparing the names records.
3085 struct CompareByRecordName {
3086 bool operator()(const Record *LHS, const Record *RHS) const {
3087 // Sort by name first.
3088 if (LHS->getName() < RHS->getName()) return true;
3089 // If both names are equal, sort by pointer.
3090 return LHS->getName() == RHS->getName() && LHS < RHS;
3091 }
3092 };
3093}
3094
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003095void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003096 std::string InstNS = Target.inst_begin()->second.Namespace;
3097 if (!InstNS.empty()) InstNS += "::";
3098
Chris Lattner602f6922006-01-04 00:25:00 +00003099 // Group the patterns by their top-level opcodes.
3100 std::map<Record*, std::vector<PatternToMatch*>,
3101 CompareByRecordName> PatternsByOpcode;
3102 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3103 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3104 if (!Node->isLeaf()) {
3105 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3106 } else {
3107 const ComplexPattern *CP;
3108 if (IntInit *II =
3109 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3110 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3111 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3112 std::vector<Record*> OpNodes = CP->getRootNodes();
3113 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner488580c2006-01-28 19:06:51 +00003114 PatternsByOpcode[OpNodes[j]]
3115 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
Chris Lattner602f6922006-01-04 00:25:00 +00003116 }
3117 } else {
3118 std::cerr << "Unrecognized opcode '";
3119 Node->dump();
3120 std::cerr << "' on tree pattern '";
Chris Lattner488580c2006-01-28 19:06:51 +00003121 std::cerr <<
3122 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
Chris Lattner602f6922006-01-04 00:25:00 +00003123 std::cerr << "'!\n";
3124 exit(1);
3125 }
3126 }
3127 }
3128
3129 // Emit one Select_* method for each top-level opcode. We do this instead of
3130 // emitting one giant switch statement to support compilers where this will
3131 // result in the recursive functions taking less stack space.
3132 for (std::map<Record*, std::vector<PatternToMatch*>,
3133 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3134 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Evan Chenge41bf822006-02-05 06:43:12 +00003135 const std::string &OpName = PBOI->first->getName();
Evan Cheng34167212006-02-09 00:37:58 +00003136 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003137
3138 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Evan Chenge41bf822006-02-05 06:43:12 +00003139 bool OptSlctOrder =
3140 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3141 OpcodeInfo.getNumResults() > 0);
3142
3143 if (OptSlctOrder) {
Evan Chenge41bf822006-02-05 06:43:12 +00003144 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3145 << " && N.getValue(0).hasOneUse()) {\n"
3146 << " SDOperand Dummy = "
3147 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003148 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3149 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3150 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3151 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003152 << " Result = Dummy;\n"
3153 << " return;\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003154 << " }\n";
3155 }
3156
Chris Lattner602f6922006-01-04 00:25:00 +00003157 std::vector<PatternToMatch*> &Patterns = PBOI->second;
Chris Lattner355408b2006-01-29 02:43:35 +00003158 assert(!Patterns.empty() && "No patterns but map has entry?");
Chris Lattner602f6922006-01-04 00:25:00 +00003159
3160 // We want to emit all of the matching code now. However, we want to emit
3161 // the matches in order of minimal cost. Sort the patterns so the least
3162 // cost one is at the start.
3163 std::stable_sort(Patterns.begin(), Patterns.end(),
3164 PatternSortingPredicate(*this));
Evan Cheng21ad3922006-02-07 00:37:41 +00003165
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003166 typedef std::vector<std::pair<bool, std::string> > CodeList;
Evan Cheng21ad3922006-02-07 00:37:41 +00003167 typedef std::set<std::string> DeclSet;
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003168
3169 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
Evan Chengd7805a72006-02-09 07:16:09 +00003170 std::set<std::pair<bool, std::string> > GeneratedDecl;
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003171 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003172 CodeList GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +00003173 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3174 OptSlctOrder);
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003175 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3176 }
3177
3178 // Scan the code to see if all of the patterns are reachable and if it is
3179 // possible that the last one might not match.
3180 bool mightNotMatch = true;
3181 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3182 CodeList &GeneratedCode = CodeForPatterns[i].second;
3183 mightNotMatch = false;
Chris Lattner355408b2006-01-29 02:43:35 +00003184
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003185 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3186 if (GeneratedCode[j].first) { // predicate.
3187 mightNotMatch = true;
3188 break;
3189 }
3190 }
Chris Lattner355408b2006-01-29 02:43:35 +00003191
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003192 // If this pattern definitely matches, and if it isn't the last one, the
3193 // patterns after it CANNOT ever match. Error out.
3194 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3195 std::cerr << "Pattern '";
3196 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3197 std::cerr << "' is impossible to select!\n";
3198 exit(1);
3199 }
3200 }
Evan Cheng21ad3922006-02-07 00:37:41 +00003201
3202 // Print all declarations.
Chris Lattner947604b2006-03-24 21:52:20 +00003203 for (std::set<std::pair<bool, std::string> >::iterator
3204 I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
Evan Chengd7805a72006-02-09 07:16:09 +00003205 if (I->first)
3206 OS << " SDNode *" << I->second << ";\n";
3207 else
3208 OS << " SDOperand " << I->second << "(0, 0);\n";
Evan Cheng21ad3922006-02-07 00:37:41 +00003209
Chris Lattner8bc74722006-01-29 04:25:26 +00003210 // Loop through and reverse all of the CodeList vectors, as we will be
3211 // accessing them from their logical front, but accessing the end of a
3212 // vector is more efficient.
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003213 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3214 CodeList &GeneratedCode = CodeForPatterns[i].second;
Chris Lattner8bc74722006-01-29 04:25:26 +00003215 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003216 }
Chris Lattner602f6922006-01-04 00:25:00 +00003217
Chris Lattner8bc74722006-01-29 04:25:26 +00003218 // Next, reverse the list of patterns itself for the same reason.
3219 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3220
3221 // Emit all of the patterns now, grouped together to share code.
3222 EmitPatterns(CodeForPatterns, 2, OS);
3223
Chris Lattner2bd4dd72006-01-29 02:57:39 +00003224 // If the last pattern has predicates (which could fail) emit code to catch
3225 // the case where nothing handles a pattern.
Chris Lattnerb026e702006-03-28 00:41:33 +00003226 if (mightNotMatch) {
3227 OS << " std::cerr << \"Cannot yet select: \";\n";
3228 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3229 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3230 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3231 OS << " N.Val->dump(CurDAG);\n";
3232 } else {
3233 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3234 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3235 << " std::cerr << \"intrinsic %\"<< "
3236 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3237 }
3238 OS << " std::cerr << '\\n';\n"
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003239 << " abort();\n";
Chris Lattnerb026e702006-03-28 00:41:33 +00003240 }
Jeff Cohen9b0ffca2006-01-27 22:22:28 +00003241 OS << "}\n\n";
Chris Lattner602f6922006-01-04 00:25:00 +00003242 }
3243
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003244 // Emit boilerplate.
Evan Cheng34167212006-02-09 00:37:58 +00003245 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003246 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Evan Cheng34167212006-02-09 00:37:58 +00003247 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003248 << " // Select the flag operand.\n"
3249 << " if (Ops.back().getValueType() == MVT::Flag)\n"
Evan Cheng34167212006-02-09 00:37:58 +00003250 << " Select(Ops.back(), Ops.back());\n"
Chris Lattnerfd105d42006-02-24 02:13:31 +00003251 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003252 << " std::vector<MVT::ValueType> VTs;\n"
3253 << " VTs.push_back(MVT::Other);\n"
3254 << " VTs.push_back(MVT::Flag);\n"
3255 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003256 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3257 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003258 << " Result = New.getValue(N.ResNo);\n"
3259 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003260 << "}\n\n";
3261
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003262 OS << "// The main instruction selector code.\n"
Evan Cheng34167212006-02-09 00:37:58 +00003263 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003264 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00003265 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00003266 << "INSTRUCTION_LIST_END)) {\n"
3267 << " Result = N;\n"
3268 << " return; // Already selected.\n"
3269 << " }\n\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003270 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003271 << " if (CGMI != CodeGenMap.end()) {\n"
3272 << " Result = CGMI->second;\n"
3273 << " return;\n"
3274 << " }\n\n"
Chris Lattner547394c2005-09-23 21:53:45 +00003275 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003276 << " default: break;\n"
3277 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00003278 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00003279 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00003280 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00003281 << " case ISD::TargetConstant:\n"
3282 << " case ISD::TargetConstantPool:\n"
3283 << " case ISD::TargetFrameIndex:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00003284 << " case ISD::TargetJumpTable:\n"
Evan Cheng34167212006-02-09 00:37:58 +00003285 << " case ISD::TargetGlobalAddress: {\n"
3286 << " Result = N;\n"
3287 << " return;\n"
3288 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003289 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00003290 << " case ISD::AssertZext: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003291 << " SDOperand Tmp0;\n"
3292 << " Select(Tmp0, N.getOperand(0));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003293 << " if (!N.Val->hasOneUse())\n"
3294 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3295 << "Tmp0.Val, Tmp0.ResNo);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003296 << " Result = Tmp0;\n"
3297 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003298 << " }\n"
3299 << " case ISD::TokenFactor:\n"
3300 << " if (N.getNumOperands() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003301 << " SDOperand Op0, Op1;\n"
3302 << " Select(Op0, N.getOperand(0));\n"
3303 << " Select(Op1, N.getOperand(1));\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003304 << " Result = \n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003305 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003306 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3307 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003308 << " } else {\n"
3309 << " std::vector<SDOperand> Ops;\n"
Evan Cheng34167212006-02-09 00:37:58 +00003310 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3311 << " SDOperand Val;\n"
3312 << " Select(Val, N.getOperand(i));\n"
3313 << " Ops.push_back(Val);\n"
3314 << " }\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003315 << " Result = \n"
3316 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3317 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3318 << "Result.Val, Result.ResNo);\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003319 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003320 << " return;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003321 << " case ISD::CopyFromReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003322 << " SDOperand Chain;\n"
3323 << " Select(Chain, N.getOperand(0));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003324 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3325 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003326 << " if (N.Val->getNumValues() == 2) {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003327 << " if (Chain == N.getOperand(0)) {\n"
3328 << " Result = N; // No change\n"
3329 << " return;\n"
3330 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003331 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003332 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3333 << "New.Val, 0);\n"
3334 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3335 << "New.Val, 1);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003336 << " Result = New.getValue(N.ResNo);\n"
3337 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003338 << " } else {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003339 << " SDOperand Flag;\n"
3340 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003341 << " if (Chain == N.getOperand(0) &&\n"
Evan Cheng34167212006-02-09 00:37:58 +00003342 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3343 << " Result = N; // No change\n"
3344 << " return;\n"
3345 << " }\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003346 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003347 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3348 << "New.Val, 0);\n"
3349 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3350 << "New.Val, 1);\n"
3351 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3352 << "New.Val, 2);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003353 << " Result = New.getValue(N.ResNo);\n"
3354 << " return;\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003355 << " }\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00003356 << " }\n"
3357 << " case ISD::CopyToReg: {\n"
Evan Cheng34167212006-02-09 00:37:58 +00003358 << " SDOperand Chain;\n"
3359 << " Select(Chain, N.getOperand(0));\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003360 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
Evan Cheng34167212006-02-09 00:37:58 +00003361 << " SDOperand Val;\n"
3362 << " Select(Val, N.getOperand(2));\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003363 << " Result = N;\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003364 << " if (N.Val->getNumValues() == 1) {\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003365 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003366 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003367 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3368 << "Result.Val, 0);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003369 << " } else {\n"
Chris Lattner7a8054f2005-12-22 20:37:36 +00003370 << " SDOperand Flag(0, 0);\n"
Evan Cheng34167212006-02-09 00:37:58 +00003371 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003372 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
Chris Lattnerdc464de2005-12-18 15:45:51 +00003373 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003374 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
Evan Cheng67212a02006-02-09 22:12:27 +00003375 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3376 << "Result.Val, 0);\n"
3377 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3378 << "Result.Val, 1);\n"
Evan Chengd7805a72006-02-09 07:16:09 +00003379 << " Result = Result.getValue(N.ResNo);\n"
Chris Lattner755dd092005-12-18 15:28:25 +00003380 << " }\n"
Evan Cheng34167212006-02-09 00:37:58 +00003381 << " return;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003382 << " }\n"
Chris Lattner947604b2006-03-24 21:52:20 +00003383 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00003384
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003385
Chris Lattner602f6922006-01-04 00:25:00 +00003386 // Loop over all of the case statements, emiting a call to each method we
3387 // emitted above.
Chris Lattner37481472005-09-26 21:59:35 +00003388 for (std::map<Record*, std::vector<PatternToMatch*>,
3389 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3390 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
Chris Lattner81303322005-09-23 19:36:15 +00003391 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
Chris Lattner602f6922006-01-04 00:25:00 +00003392 OS << " case " << OpcodeInfo.getEnumName() << ": "
Chris Lattner11966a02006-01-04 00:32:01 +00003393 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
Evan Cheng34167212006-02-09 00:37:58 +00003394 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
Chris Lattner81303322005-09-23 19:36:15 +00003395 }
Chris Lattner81303322005-09-23 19:36:15 +00003396
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003397 OS << " } // end of big switch.\n\n"
3398 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00003399 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3400 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3401 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00003402 << " N.Val->dump(CurDAG);\n"
3403 << " } else {\n"
3404 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3405 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3406 << " std::cerr << \"intrinsic %\"<< "
3407 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3408 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003409 << " std::cerr << '\\n';\n"
3410 << " abort();\n"
3411 << "}\n";
3412}
3413
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003414void DAGISelEmitter::run(std::ostream &OS) {
3415 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3416 " target", OS);
3417
Chris Lattner1f39e292005-09-14 00:09:24 +00003418 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3419 << "// *** instruction selector class. These functions are really "
3420 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003421
Chris Lattner296dfe32005-09-24 00:50:51 +00003422 OS << "// Instance var to keep track of multiply used nodes that have \n"
3423 << "// already been selected.\n"
3424 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003425
3426 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003427 << "// and their place handle nodes.\n";
3428 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3429 OS << "// Instance var to keep track of mapping of place handle nodes\n"
Evan Chenge41bf822006-02-05 06:43:12 +00003430 << "// and their replacement nodes.\n";
3431 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
Evan Cheng61a02092006-04-28 02:08:10 +00003432 OS << "// Keep track of nodes that are currently being selecte and therefore\n"
3433 << "// should not be folded.\n";
3434 OS << "std::set<SDNode*> InFlightSet;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003435
3436 OS << "\n";
3437 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3438 << "std::set<SDNode *> &Visited) {\n";
3439 OS << " if (found || !Visited.insert(Use).second) return;\n";
3440 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3441 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3442 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3443 OS << " if (N != Def) {\n";
3444 OS << " findNonImmUse(N, Def, found, Visited);\n";
3445 OS << " } else {\n";
3446 OS << " found = true;\n";
3447 OS << " break;\n";
3448 OS << " }\n";
3449 OS << " }\n";
3450 OS << " }\n";
3451 OS << "}\n";
3452
3453 OS << "\n";
3454 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3455 OS << " std::set<SDNode *> Visited;\n";
3456 OS << " bool found = false;\n";
3457 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3458 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3459 OS << " if (N != Def) {\n";
3460 OS << " findNonImmUse(N, Def, found, Visited);\n";
3461 OS << " if (found) break;\n";
3462 OS << " }\n";
3463 OS << " }\n";
3464 OS << " return found;\n";
3465 OS << "}\n";
3466
3467 OS << "\n";
Evan Cheng024524f2006-02-06 06:03:35 +00003468 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
Evan Cheng7cd19d02006-02-06 08:12:55 +00003469 << "// handle node in ReplaceMap.\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003470 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3471 << "unsigned RNum) {\n";
3472 OS << " SDOperand N(H, HNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003473 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3474 OS << " if (HMI != HandleMap.end()) {\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003475 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003476 OS << " HandleMap.erase(N);\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003477 OS << " }\n";
3478 OS << "}\n";
3479
3480 OS << "\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003481 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3482 OS << "// handles.Some handles do not yet have replacements because the\n";
3483 OS << "// nodes they replacements have only dead readers.\n";
3484 OS << "void SelectDanglingHandles() {\n";
3485 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3486 << "HandleMap.begin(),\n"
3487 << " E = HandleMap.end(); I != E; ++I) {\n";
3488 OS << " SDOperand N = I->first;\n";
Evan Cheng34167212006-02-09 00:37:58 +00003489 OS << " SDOperand R;\n";
3490 OS << " Select(R, N.getValue(0));\n";
Evan Cheng67212a02006-02-09 22:12:27 +00003491 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003492 OS << " }\n";
3493 OS << "}\n";
3494 OS << "\n";
3495 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003496 OS << "// specific nodes.\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003497 OS << "void ReplaceHandles() {\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003498 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3499 << "ReplaceMap.begin(),\n"
3500 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3501 OS << " SDOperand From = I->first;\n";
3502 OS << " SDOperand To = I->second;\n";
3503 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3504 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3505 OS << " SDNode *Use = *UI;\n";
3506 OS << " std::vector<SDOperand> Ops;\n";
3507 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3508 OS << " SDOperand O = Use->getOperand(i);\n";
3509 OS << " if (O.Val == From.Val)\n";
3510 OS << " Ops.push_back(To);\n";
3511 OS << " else\n";
3512 OS << " Ops.push_back(O);\n";
3513 OS << " }\n";
3514 OS << " SDOperand U = SDOperand(Use, 0);\n";
3515 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3516 OS << " }\n";
3517 OS << " }\n";
3518 OS << "}\n";
3519
3520 OS << "\n";
Evan Chenged66e852006-03-09 08:19:11 +00003521 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3522 OS << "// if the folding were to happen. This is called when, for example,\n";
3523 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3524 OS << "// then the resulting node's input chain would be the load's input\n";
3525 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3526 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3527 OS << "// with the other operands along with the input chain of the load.\n";
3528 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3529 << "SDNode *Chain, SDNode* &OldTF) {\n";
3530 OS << " OldTF = NULL;\n";
3531 OS << " if (N == Chain) {\n";
3532 OS << " return N->getOperand(0);\n";
3533 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3534 OS << " N->isOperand(Chain)) {\n";
3535 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3536 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3537 << "CodeGenMap.find(Ch);\n";
3538 OS << " if (CGMI != CodeGenMap.end())\n";
3539 OS << " return SDOperand(0, 0);\n";
3540 OS << " OldTF = Chain;\n";
3541 OS << " std::vector<SDOperand> Ops;\n";
3542 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3543 OS << " SDOperand Op = Chain->getOperand(i);\n";
3544 OS << " if (Op.Val == N)\n";
3545 OS << " Ops.push_back(N->getOperand(0));\n";
3546 OS << " else\n";
3547 OS << " Ops.push_back(Op);\n";
3548 OS << " }\n";
3549 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3550 OS << " }\n";
3551 OS << " return SDOperand(0, 0);\n";
3552 OS << "}\n";
3553
3554 OS << "\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003555 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3556 OS << "SDOperand SelectRoot(SDOperand N) {\n";
Evan Cheng34167212006-02-09 00:37:58 +00003557 OS << " SDOperand ResNode;\n";
3558 OS << " Select(ResNode, N);\n";
Evan Cheng7cd19d02006-02-06 08:12:55 +00003559 OS << " SelectDanglingHandles();\n";
3560 OS << " ReplaceHandles();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003561 OS << " ReplaceMap.clear();\n";
Evan Cheng34167212006-02-09 00:37:58 +00003562 OS << " return ResNode;\n";
Evan Chenge41bf822006-02-05 06:43:12 +00003563 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00003564
Chris Lattner550525e2006-03-24 21:48:51 +00003565 Intrinsics = LoadIntrinsics(Records);
Chris Lattnerca559d02005-09-08 21:03:01 +00003566 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00003567 ParseNodeTransforms(OS);
Evan Cheng0fc71982005-12-08 02:00:36 +00003568 ParseComplexPatterns();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003569 ParsePatternFragments(OS);
3570 ParseInstructions();
3571 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00003572
Chris Lattnere97603f2005-09-28 19:27:25 +00003573 // Generate variants. For example, commutative patterns can match
Chris Lattner3f7e9142005-09-23 20:52:47 +00003574 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnere97603f2005-09-28 19:27:25 +00003575 GenerateVariants();
Chris Lattnerb39e4be2005-09-15 02:38:02 +00003576
Chris Lattnere46e17b2005-09-29 19:28:10 +00003577
3578 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3579 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Evan Cheng58e84a62005-12-14 22:02:59 +00003580 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3581 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
Chris Lattnere46e17b2005-09-29 19:28:10 +00003582 std::cerr << "\n";
3583 });
3584
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00003585 // At this point, we have full information about the 'Patterns' we need to
3586 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00003587 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003588 EmitInstructionSelector(OS);
3589
3590 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3591 E = PatternFragments.end(); I != E; ++I)
3592 delete I->second;
3593 PatternFragments.clear();
3594
Chris Lattner54cb8fd2005-09-07 23:44:43 +00003595 Instructions.clear();
3596}