blob: 882c7245f6126b5bae863dc9d8aee39060689754 [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Support/Debug.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "llvm/Support/Streams.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000020#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000021#include <algorithm>
Chris Lattner6cefb772008-01-05 22:25:12 +000022using namespace llvm;
23
24//===----------------------------------------------------------------------===//
25// Helpers for working with extended types.
26
27/// FilterVTs - Filter a list of VT's according to a predicate.
28///
29template<typename T>
Duncan Sands83ec4b62008-06-06 12:08:01 +000030static std::vector<MVT::SimpleValueType>
31FilterVTs(const std::vector<MVT::SimpleValueType> &InVTs, T Filter) {
32 std::vector<MVT::SimpleValueType> Result;
Chris Lattner6cefb772008-01-05 22:25:12 +000033 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
34 if (Filter(InVTs[i]))
35 Result.push_back(InVTs[i]);
36 return Result;
37}
38
39template<typename T>
40static std::vector<unsigned char>
41FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +000044 if (Filter((MVT::SimpleValueType)InVTs[i]))
Chris Lattner6cefb772008-01-05 22:25:12 +000045 Result.push_back(InVTs[i]);
46 return Result;
47}
48
49static std::vector<unsigned char>
Duncan Sands83ec4b62008-06-06 12:08:01 +000050ConvertVTs(const std::vector<MVT::SimpleValueType> &InVTs) {
Chris Lattner6cefb772008-01-05 22:25:12 +000051 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
54 return Result;
55}
56
Duncan Sands83ec4b62008-06-06 12:08:01 +000057static inline bool isInteger(MVT::SimpleValueType VT) {
58 return MVT(VT).isInteger();
59}
60
61static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
62 return MVT(VT).isFloatingPoint();
63}
64
65static inline bool isVector(MVT::SimpleValueType VT) {
66 return MVT(VT).isVector();
67}
68
Chris Lattner6cefb772008-01-05 22:25:12 +000069static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
70 const std::vector<unsigned char> &RHS) {
71 if (LHS.size() > RHS.size()) return false;
72 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
73 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
74 return false;
75 return true;
76}
77
78/// isExtIntegerVT - Return true if the specified extended value type vector
79/// contains isInt or an integer value type.
80namespace llvm {
Duncan Sands83ec4b62008-06-06 12:08:01 +000081namespace EMVT {
Chris Lattner6cefb772008-01-05 22:25:12 +000082bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
83 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
84 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
85}
86
87/// isExtFloatingPointVT - Return true if the specified extended value type
88/// vector contains isFP or a FP value type.
89bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
90 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
91 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
92}
Duncan Sands83ec4b62008-06-06 12:08:01 +000093} // end namespace EMVT.
Chris Lattner6cefb772008-01-05 22:25:12 +000094} // end namespace llvm.
95
Scott Michel327d0652008-03-05 17:49:05 +000096
97/// Dependent variable map for CodeGenDAGPattern variant generation
98typedef std::map<std::string, int> DepVarMap;
99
100/// Const iterator shorthand for DepVarMap
101typedef DepVarMap::const_iterator DepVarMap_citer;
102
103namespace {
104void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
105 if (N->isLeaf()) {
106 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
107 DepMap[N->getName()]++;
108 }
109 } else {
110 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
111 FindDepVarsOf(N->getChild(i), DepMap);
112 }
113}
114
115//! Find dependent variables within child patterns
116/*!
117 */
118void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
119 DepVarMap depcounts;
120 FindDepVarsOf(N, depcounts);
121 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
122 if (i->second > 1) { // std::pair<std::string, int>
123 DepVars.insert(i->first);
124 }
125 }
126}
127
128//! Dump the dependent variable set:
129void DumpDepVars(MultipleUseVarSet &DepVars) {
130 if (DepVars.empty()) {
131 DOUT << "<empty set>";
132 } else {
133 DOUT << "[ ";
134 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
135 i != e; ++i) {
136 DOUT << (*i) << " ";
137 }
138 DOUT << "]";
139 }
140}
141}
142
Chris Lattner6cefb772008-01-05 22:25:12 +0000143//===----------------------------------------------------------------------===//
144// SDTypeConstraint implementation
145//
146
147SDTypeConstraint::SDTypeConstraint(Record *R) {
148 OperandNo = R->getValueAsInt("OperandNum");
149
150 if (R->isSubClassOf("SDTCisVT")) {
151 ConstraintType = SDTCisVT;
152 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
153 } else if (R->isSubClassOf("SDTCisPtrTy")) {
154 ConstraintType = SDTCisPtrTy;
155 } else if (R->isSubClassOf("SDTCisInt")) {
156 ConstraintType = SDTCisInt;
157 } else if (R->isSubClassOf("SDTCisFP")) {
158 ConstraintType = SDTCisFP;
159 } else if (R->isSubClassOf("SDTCisSameAs")) {
160 ConstraintType = SDTCisSameAs;
161 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
162 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
163 ConstraintType = SDTCisVTSmallerThanOp;
164 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
165 R->getValueAsInt("OtherOperandNum");
166 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
167 ConstraintType = SDTCisOpSmallerThanOp;
168 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
169 R->getValueAsInt("BigOperandNum");
170 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
171 ConstraintType = SDTCisIntVectorOfSameSize;
172 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
173 R->getValueAsInt("OtherOpNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000174 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
175 ConstraintType = SDTCisEltOfVec;
176 x.SDTCisEltOfVec_Info.OtherOperandNum =
177 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000178 } else {
179 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
180 exit(1);
181 }
182}
183
184/// getOperandNum - Return the node corresponding to operand #OpNo in tree
185/// N, which has NumResults results.
186TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
187 TreePatternNode *N,
188 unsigned NumResults) const {
189 assert(NumResults <= 1 &&
190 "We only work with nodes with zero or one result so far!");
191
192 if (OpNo >= (NumResults + N->getNumChildren())) {
193 cerr << "Invalid operand number " << OpNo << " ";
194 N->dump();
195 cerr << '\n';
196 exit(1);
197 }
198
199 if (OpNo < NumResults)
200 return N; // FIXME: need value #
201 else
202 return N->getChild(OpNo-NumResults);
203}
204
205/// ApplyTypeConstraint - Given a node in a pattern, apply this type
206/// constraint to the nodes operands. This returns true if it makes a
207/// change, false otherwise. If a type contradiction is found, throw an
208/// exception.
209bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
210 const SDNodeInfo &NodeInfo,
211 TreePattern &TP) const {
212 unsigned NumResults = NodeInfo.getNumResults();
213 assert(NumResults <= 1 &&
214 "We only work with nodes with zero or one result so far!");
215
216 // Check that the number of operands is sane. Negative operands -> varargs.
217 if (NodeInfo.getNumOperands() >= 0) {
218 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
219 TP.error(N->getOperator()->getName() + " node requires exactly " +
220 itostr(NodeInfo.getNumOperands()) + " operands!");
221 }
222
223 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
224
225 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
226
227 switch (ConstraintType) {
228 default: assert(0 && "Unknown constraint type!");
229 case SDTCisVT:
230 // Operand must be a particular type.
231 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
232 case SDTCisPtrTy: {
233 // Operand must be same as target pointer type.
234 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
235 }
236 case SDTCisInt: {
237 // If there is only one integer type supported, this must be it.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000238 std::vector<MVT::SimpleValueType> IntVTs =
239 FilterVTs(CGT.getLegalValueTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000240
241 // If we found exactly one supported integer type, apply it.
242 if (IntVTs.size() == 1)
243 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000244 return NodeToApply->UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000245 }
246 case SDTCisFP: {
247 // If there is only one FP type supported, this must be it.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000248 std::vector<MVT::SimpleValueType> FPVTs =
249 FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000250
251 // If we found exactly one supported FP type, apply it.
252 if (FPVTs.size() == 1)
253 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000254 return NodeToApply->UpdateNodeType(EMVT::isFP, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000255 }
256 case SDTCisSameAs: {
257 TreePatternNode *OtherNode =
258 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
259 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
260 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
261 }
262 case SDTCisVTSmallerThanOp: {
263 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
264 // have an integer type that is smaller than the VT.
265 if (!NodeToApply->isLeaf() ||
266 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
267 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
268 ->isSubClassOf("ValueType"))
269 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000270 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000271 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000272 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000273 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
274
275 TreePatternNode *OtherNode =
276 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
277
278 // It must be integer.
279 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000280 MadeChange |= OtherNode->UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000281
282 // This code only handles nodes that have one type set. Assert here so
283 // that we can change this if we ever need to deal with multiple value
284 // types at this point.
285 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
286 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
287 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
288 return false;
289 }
290 case SDTCisOpSmallerThanOp: {
291 TreePatternNode *BigOperand =
292 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
293
294 // Both operands must be integer or FP, but we don't care which.
295 bool MadeChange = false;
296
297 // This code does not currently handle nodes which have multiple types,
298 // where some types are integer, and some are fp. Assert that this is not
299 // the case.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000300 assert(!(EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
301 EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
302 !(EMVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
303 EMVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000304 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000305 if (EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
306 MadeChange |= BigOperand->UpdateNodeType(EMVT::isInt, TP);
307 else if (EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
308 MadeChange |= BigOperand->UpdateNodeType(EMVT::isFP, TP);
309 if (EMVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
310 MadeChange |= NodeToApply->UpdateNodeType(EMVT::isInt, TP);
311 else if (EMVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
312 MadeChange |= NodeToApply->UpdateNodeType(EMVT::isFP, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000313
Duncan Sands83ec4b62008-06-06 12:08:01 +0000314 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
315
316 if (EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
317 VTs = FilterVTs(VTs, isInteger);
318 } else if (EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
319 VTs = FilterVTs(VTs, isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000320 } else {
321 VTs.clear();
322 }
323
324 switch (VTs.size()) {
325 default: // Too many VT's to pick from.
326 case 0: break; // No info yet.
327 case 1:
328 // Only one VT of this flavor. Cannot ever satisify the constraints.
329 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
330 case 2:
331 // If we have exactly two possible types, the little operand must be the
332 // small one, the big operand should be the big one. Common with
333 // float/double for example.
334 assert(VTs[0] < VTs[1] && "Should be sorted!");
335 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
336 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
337 break;
338 }
339 return MadeChange;
340 }
341 case SDTCisIntVectorOfSameSize: {
342 TreePatternNode *OtherOperand =
343 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
344 N, NumResults);
345 if (OtherOperand->hasTypeSet()) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000346 if (!isVector(OtherOperand->getTypeNum(0)))
Chris Lattner6cefb772008-01-05 22:25:12 +0000347 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000348 MVT IVT = OtherOperand->getTypeNum(0);
349 unsigned NumElements = IVT.getVectorNumElements();
350 IVT = MVT::getIntVectorWithNumElements(NumElements);
351 return NodeToApply->UpdateNodeType(IVT.getSimpleVT(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000352 }
353 return false;
354 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000355 case SDTCisEltOfVec: {
356 TreePatternNode *OtherOperand =
357 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
358 N, NumResults);
359 if (OtherOperand->hasTypeSet()) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000360 if (!isVector(OtherOperand->getTypeNum(0)))
Nate Begemanb5af3342008-02-09 01:37:05 +0000361 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000362 MVT IVT = OtherOperand->getTypeNum(0);
363 IVT = IVT.getVectorElementType();
364 return NodeToApply->UpdateNodeType(IVT.getSimpleVT(), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000365 }
366 return false;
367 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000368 }
369 return false;
370}
371
372//===----------------------------------------------------------------------===//
373// SDNodeInfo implementation
374//
375SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
376 EnumName = R->getValueAsString("Opcode");
377 SDClassName = R->getValueAsString("SDClass");
378 Record *TypeProfile = R->getValueAsDef("TypeProfile");
379 NumResults = TypeProfile->getValueAsInt("NumResults");
380 NumOperands = TypeProfile->getValueAsInt("NumOperands");
381
382 // Parse the properties.
383 Properties = 0;
384 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
385 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
386 if (PropList[i]->getName() == "SDNPCommutative") {
387 Properties |= 1 << SDNPCommutative;
388 } else if (PropList[i]->getName() == "SDNPAssociative") {
389 Properties |= 1 << SDNPAssociative;
390 } else if (PropList[i]->getName() == "SDNPHasChain") {
391 Properties |= 1 << SDNPHasChain;
392 } else if (PropList[i]->getName() == "SDNPOutFlag") {
393 Properties |= 1 << SDNPOutFlag;
394 } else if (PropList[i]->getName() == "SDNPInFlag") {
395 Properties |= 1 << SDNPInFlag;
396 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
397 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000398 } else if (PropList[i]->getName() == "SDNPMayStore") {
399 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000400 } else if (PropList[i]->getName() == "SDNPMayLoad") {
401 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000402 } else if (PropList[i]->getName() == "SDNPSideEffect") {
403 Properties |= 1 << SDNPSideEffect;
Chris Lattner6cefb772008-01-05 22:25:12 +0000404 } else {
405 cerr << "Unknown SD Node property '" << PropList[i]->getName()
406 << "' on node '" << R->getName() << "'!\n";
407 exit(1);
408 }
409 }
410
411
412 // Parse the type constraints.
413 std::vector<Record*> ConstraintList =
414 TypeProfile->getValueAsListOfDefs("Constraints");
415 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
416}
417
418//===----------------------------------------------------------------------===//
419// TreePatternNode implementation
420//
421
422TreePatternNode::~TreePatternNode() {
423#if 0 // FIXME: implement refcounted tree nodes!
424 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
425 delete getChild(i);
426#endif
427}
428
429/// UpdateNodeType - Set the node type of N to VT if VT contains
430/// information. If N already contains a conflicting type, then throw an
431/// exception. This returns true if any information was updated.
432///
433bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
434 TreePattern &TP) {
435 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
436
Duncan Sands83ec4b62008-06-06 12:08:01 +0000437 if (ExtVTs[0] == EMVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
Chris Lattner6cefb772008-01-05 22:25:12 +0000438 return false;
439 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
440 setTypes(ExtVTs);
441 return true;
442 }
443
444 if (getExtTypeNum(0) == MVT::iPTR) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000445 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == EMVT::isInt)
Chris Lattner6cefb772008-01-05 22:25:12 +0000446 return false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000447 if (EMVT::isExtIntegerInVTs(ExtVTs)) {
448 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000449 if (FVTs.size()) {
450 setTypes(ExtVTs);
451 return true;
452 }
453 }
454 }
455
Duncan Sands83ec4b62008-06-06 12:08:01 +0000456 if (ExtVTs[0] == EMVT::isInt && EMVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000457 assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000458 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000459 if (getExtTypes() == FVTs)
460 return false;
461 setTypes(FVTs);
462 return true;
463 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000464 if (ExtVTs[0] == MVT::iPTR && EMVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000465 //assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000466 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000467 if (getExtTypes() == FVTs)
468 return false;
469 if (FVTs.size()) {
470 setTypes(FVTs);
471 return true;
472 }
473 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000474 if (ExtVTs[0] == EMVT::isFP && EMVT::isExtFloatingPointInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000475 assert(hasTypeSet() && "should be handled above!");
476 std::vector<unsigned char> FVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000477 FilterEVTs(getExtTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000478 if (getExtTypes() == FVTs)
479 return false;
480 setTypes(FVTs);
481 return true;
482 }
483
484 // If we know this is an int or fp type, and we are told it is a specific one,
485 // take the advice.
486 //
487 // Similarly, we should probably set the type here to the intersection of
488 // {isInt|isFP} and ExtVTs
Duncan Sands83ec4b62008-06-06 12:08:01 +0000489 if ((getExtTypeNum(0) == EMVT::isInt &&
490 EMVT::isExtIntegerInVTs(ExtVTs)) ||
491 (getExtTypeNum(0) == EMVT::isFP &&
492 EMVT::isExtFloatingPointInVTs(ExtVTs))) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000493 setTypes(ExtVTs);
494 return true;
495 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000496 if (getExtTypeNum(0) == EMVT::isInt && ExtVTs[0] == MVT::iPTR) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000497 setTypes(ExtVTs);
498 return true;
499 }
500
501 if (isLeaf()) {
502 dump();
503 cerr << " ";
504 TP.error("Type inference contradiction found in node!");
505 } else {
506 TP.error("Type inference contradiction found in node " +
507 getOperator()->getName() + "!");
508 }
509 return true; // unreachable
510}
511
512
513void TreePatternNode::print(std::ostream &OS) const {
514 if (isLeaf()) {
515 OS << *getLeafValue();
516 } else {
517 OS << "(" << getOperator()->getName();
518 }
519
520 // FIXME: At some point we should handle printing all the value types for
521 // nodes that are multiply typed.
522 switch (getExtTypeNum(0)) {
523 case MVT::Other: OS << ":Other"; break;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000524 case EMVT::isInt: OS << ":isInt"; break;
525 case EMVT::isFP : OS << ":isFP"; break;
526 case EMVT::isUnknown: ; /*OS << ":?";*/ break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000527 case MVT::iPTR: OS << ":iPTR"; break;
528 default: {
529 std::string VTName = llvm::getName(getTypeNum(0));
530 // Strip off MVT:: prefix if present.
531 if (VTName.substr(0,5) == "MVT::")
532 VTName = VTName.substr(5);
533 OS << ":" << VTName;
534 break;
535 }
536 }
537
538 if (!isLeaf()) {
539 if (getNumChildren() != 0) {
540 OS << " ";
541 getChild(0)->print(OS);
542 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
543 OS << ", ";
544 getChild(i)->print(OS);
545 }
546 }
547 OS << ")";
548 }
549
550 if (!PredicateFn.empty())
551 OS << "<<P:" << PredicateFn << ">>";
552 if (TransformFn)
553 OS << "<<X:" << TransformFn->getName() << ">>";
554 if (!getName().empty())
555 OS << ":$" << getName();
556
557}
558void TreePatternNode::dump() const {
559 print(*cerr.stream());
560}
561
Scott Michel327d0652008-03-05 17:49:05 +0000562/// isIsomorphicTo - Return true if this node is recursively
563/// isomorphic to the specified node. For this comparison, the node's
564/// entire state is considered. The assigned name is ignored, since
565/// nodes with differing names are considered isomorphic. However, if
566/// the assigned name is present in the dependent variable set, then
567/// the assigned name is considered significant and the node is
568/// isomorphic if the names match.
569bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
570 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000571 if (N == this) return true;
572 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
573 getPredicateFn() != N->getPredicateFn() ||
574 getTransformFn() != N->getTransformFn())
575 return false;
576
577 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000578 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
579 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000580 return ((DI->getDef() == NDI->getDef())
581 && (DepVars.find(getName()) == DepVars.end()
582 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000583 }
584 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000585 return getLeafValue() == N->getLeafValue();
586 }
587
588 if (N->getOperator() != getOperator() ||
589 N->getNumChildren() != getNumChildren()) return false;
590 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000591 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000592 return false;
593 return true;
594}
595
596/// clone - Make a copy of this tree and all of its children.
597///
598TreePatternNode *TreePatternNode::clone() const {
599 TreePatternNode *New;
600 if (isLeaf()) {
601 New = new TreePatternNode(getLeafValue());
602 } else {
603 std::vector<TreePatternNode*> CChildren;
604 CChildren.reserve(Children.size());
605 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
606 CChildren.push_back(getChild(i)->clone());
607 New = new TreePatternNode(getOperator(), CChildren);
608 }
609 New->setName(getName());
610 New->setTypes(getExtTypes());
611 New->setPredicateFn(getPredicateFn());
612 New->setTransformFn(getTransformFn());
613 return New;
614}
615
616/// SubstituteFormalArguments - Replace the formal arguments in this tree
617/// with actual values specified by ArgMap.
618void TreePatternNode::
619SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
620 if (isLeaf()) return;
621
622 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
623 TreePatternNode *Child = getChild(i);
624 if (Child->isLeaf()) {
625 Init *Val = Child->getLeafValue();
626 if (dynamic_cast<DefInit*>(Val) &&
627 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
628 // We found a use of a formal argument, replace it with its value.
629 Child = ArgMap[Child->getName()];
630 assert(Child && "Couldn't find formal argument!");
631 setChild(i, Child);
632 }
633 } else {
634 getChild(i)->SubstituteFormalArguments(ArgMap);
635 }
636 }
637}
638
639
640/// InlinePatternFragments - If this pattern refers to any pattern
641/// fragments, inline them into place, giving us a pattern without any
642/// PatFrag references.
643TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
644 if (isLeaf()) return this; // nothing to do.
645 Record *Op = getOperator();
646
647 if (!Op->isSubClassOf("PatFrag")) {
648 // Just recursively inline children nodes.
649 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
650 setChild(i, getChild(i)->InlinePatternFragments(TP));
651 return this;
652 }
653
654 // Otherwise, we found a reference to a fragment. First, look up its
655 // TreePattern record.
656 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
657
658 // Verify that we are passing the right number of operands.
659 if (Frag->getNumArgs() != Children.size())
660 TP.error("'" + Op->getName() + "' fragment requires " +
661 utostr(Frag->getNumArgs()) + " operands!");
662
663 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
664
665 // Resolve formal arguments to their actual value.
666 if (Frag->getNumArgs()) {
667 // Compute the map of formal to actual arguments.
668 std::map<std::string, TreePatternNode*> ArgMap;
669 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
670 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
671
672 FragTree->SubstituteFormalArguments(ArgMap);
673 }
674
675 FragTree->setName(getName());
676 FragTree->UpdateNodeType(getExtTypes(), TP);
677
678 // Get a new copy of this fragment to stitch into here.
679 //delete this; // FIXME: implement refcounting!
680 return FragTree;
681}
682
683/// getImplicitType - Check to see if the specified record has an implicit
684/// type which should be applied to it. This infer the type of register
685/// references from the register file information, for example.
686///
687static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
688 TreePattern &TP) {
689 // Some common return values
Duncan Sands83ec4b62008-06-06 12:08:01 +0000690 std::vector<unsigned char> Unknown(1, EMVT::isUnknown);
Chris Lattner6cefb772008-01-05 22:25:12 +0000691 std::vector<unsigned char> Other(1, MVT::Other);
692
693 // Check to see if this is a register or a register class...
694 if (R->isSubClassOf("RegisterClass")) {
695 if (NotRegisters)
696 return Unknown;
697 const CodeGenRegisterClass &RC =
698 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
699 return ConvertVTs(RC.getValueTypes());
700 } else if (R->isSubClassOf("PatFrag")) {
701 // Pattern fragment types will be resolved when they are inlined.
702 return Unknown;
703 } else if (R->isSubClassOf("Register")) {
704 if (NotRegisters)
705 return Unknown;
706 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
707 return T.getRegisterVTs(R);
708 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
709 // Using a VTSDNode or CondCodeSDNode.
710 return Other;
711 } else if (R->isSubClassOf("ComplexPattern")) {
712 if (NotRegisters)
713 return Unknown;
714 std::vector<unsigned char>
715 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
716 return ComplexPat;
717 } else if (R->getName() == "ptr_rc") {
718 Other[0] = MVT::iPTR;
719 return Other;
720 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
721 R->getName() == "zero_reg") {
722 // Placeholder.
723 return Unknown;
724 }
725
726 TP.error("Unknown node flavor used in pattern: " + R->getName());
727 return Other;
728}
729
Chris Lattnere67bde52008-01-06 05:36:50 +0000730
731/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
732/// CodeGenIntrinsic information for it, otherwise return a null pointer.
733const CodeGenIntrinsic *TreePatternNode::
734getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
735 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
736 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
737 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
738 return 0;
739
740 unsigned IID =
741 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
742 return &CDP.getIntrinsicInfo(IID);
743}
744
745
Chris Lattner6cefb772008-01-05 22:25:12 +0000746/// ApplyTypeConstraints - Apply all of the type constraints relevent to
747/// this node and its children in the tree. This returns true if it makes a
748/// change, false otherwise. If a type contradiction is found, throw an
749/// exception.
750bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +0000751 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +0000752 if (isLeaf()) {
753 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
754 // If it's a regclass or something else known, include the type.
755 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
756 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
757 // Int inits are always integers. :)
Duncan Sands83ec4b62008-06-06 12:08:01 +0000758 bool MadeChange = UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000759
760 if (hasTypeSet()) {
761 // At some point, it may make sense for this tree pattern to have
762 // multiple types. Assert here that it does not, so we revisit this
763 // code when appropriate.
764 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000765 MVT::SimpleValueType VT = getTypeNum(0);
Chris Lattner6cefb772008-01-05 22:25:12 +0000766 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
767 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
768
769 VT = getTypeNum(0);
770 if (VT != MVT::iPTR) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000771 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattner6cefb772008-01-05 22:25:12 +0000772 // Make sure that the value is representable for this type.
773 if (Size < 32) {
774 int Val = (II->getValue() << (32-Size)) >> (32-Size);
Scott Michel0123b7d2008-02-15 23:05:48 +0000775 if (Val != II->getValue()) {
Bill Wendling27926af2008-02-26 10:45:29 +0000776 // If sign-extended doesn't fit, does it fit as unsigned?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000777 unsigned ValueMask;
778 unsigned UnsignedVal;
779 ValueMask = unsigned(MVT(VT).getIntegerVTBitMask());
780 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +0000781
Bill Wendling27926af2008-02-26 10:45:29 +0000782 if ((ValueMask & UnsignedVal) != UnsignedVal) {
783 TP.error("Integer value '" + itostr(II->getValue())+
784 "' is out of range for type '" +
785 getEnumName(getTypeNum(0)) + "'!");
786 }
787 }
788 }
789 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000790 }
791
792 return MadeChange;
793 }
794 return false;
795 }
796
797 // special handling for set, which isn't really an SDNode.
798 if (getOperator()->getName() == "set") {
799 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
800 unsigned NC = getNumChildren();
801 bool MadeChange = false;
802 for (unsigned i = 0; i < NC-1; ++i) {
803 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
804 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
805
806 // Types of operands must match.
807 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
808 TP);
809 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
810 TP);
811 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
812 }
813 return MadeChange;
814 } else if (getOperator()->getName() == "implicit" ||
815 getOperator()->getName() == "parallel") {
816 bool MadeChange = false;
817 for (unsigned i = 0; i < getNumChildren(); ++i)
818 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
819 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
820 return MadeChange;
Chris Lattnere67bde52008-01-06 05:36:50 +0000821 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000822 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000823
Chris Lattner6cefb772008-01-05 22:25:12 +0000824 // Apply the result type to the node.
Chris Lattnere67bde52008-01-06 05:36:50 +0000825 MadeChange = UpdateNodeType(Int->ArgVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000826
Chris Lattnere67bde52008-01-06 05:36:50 +0000827 if (getNumChildren() != Int->ArgVTs.size())
828 TP.error("Intrinsic '" + Int->Name + "' expects " +
829 utostr(Int->ArgVTs.size()-1) + " operands, not " +
Chris Lattner6cefb772008-01-05 22:25:12 +0000830 utostr(getNumChildren()-1) + " operands!");
831
832 // Apply type info to the intrinsic ID.
833 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
834
835 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000836 MVT::SimpleValueType OpVT = Int->ArgVTs[i];
Chris Lattner6cefb772008-01-05 22:25:12 +0000837 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
838 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
839 }
840 return MadeChange;
841 } else if (getOperator()->isSubClassOf("SDNode")) {
842 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
843
844 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
845 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
846 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
847 // Branch, etc. do not produce results and top-level forms in instr pattern
848 // must have void types.
849 if (NI.getNumResults() == 0)
850 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
851
852 // If this is a vector_shuffle operation, apply types to the build_vector
853 // operation. The types of the integers don't matter, but this ensures they
854 // won't get checked.
855 if (getOperator()->getName() == "vector_shuffle" &&
856 getChild(2)->getOperator()->getName() == "build_vector") {
857 TreePatternNode *BV = getChild(2);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000858 const std::vector<MVT::SimpleValueType> &LegalVTs
Chris Lattner6cefb772008-01-05 22:25:12 +0000859 = CDP.getTargetInfo().getLegalValueTypes();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000860 MVT::SimpleValueType LegalIntVT = MVT::Other;
Chris Lattner6cefb772008-01-05 22:25:12 +0000861 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +0000862 if (isInteger(LegalVTs[i]) && !isVector(LegalVTs[i])) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000863 LegalIntVT = LegalVTs[i];
864 break;
865 }
866 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
867
868 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
869 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
870 }
871 return MadeChange;
872 } else if (getOperator()->isSubClassOf("Instruction")) {
873 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
874 bool MadeChange = false;
875 unsigned NumResults = Inst.getNumResults();
876
877 assert(NumResults <= 1 &&
878 "Only supports zero or one result instrs!");
879
880 CodeGenInstruction &InstInfo =
881 CDP.getTargetInfo().getInstruction(getOperator()->getName());
882 // Apply the result type to the node
883 if (NumResults == 0 || InstInfo.NumDefs == 0) {
Christopher Lamb02f69372008-03-10 04:16:09 +0000884 MadeChange = UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000885 } else {
886 Record *ResultNode = Inst.getResult(0);
887
888 if (ResultNode->getName() == "ptr_rc") {
889 std::vector<unsigned char> VT;
890 VT.push_back(MVT::iPTR);
891 MadeChange = UpdateNodeType(VT, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +0000892 } else if (ResultNode->getName() == "unknown") {
893 std::vector<unsigned char> VT;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000894 VT.push_back(EMVT::isUnknown);
Christopher Lamb5b415372008-03-11 09:33:47 +0000895 MadeChange = UpdateNodeType(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000896 } else {
897 assert(ResultNode->isSubClassOf("RegisterClass") &&
898 "Operands should be register classes!");
899
900 const CodeGenRegisterClass &RC =
901 CDP.getTargetInfo().getRegisterClass(ResultNode);
902 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
903 }
904 }
905
906 unsigned ChildNo = 0;
907 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
908 Record *OperandNode = Inst.getOperand(i);
909
910 // If the instruction expects a predicate or optional def operand, we
911 // codegen this by setting the operand to it's default value if it has a
912 // non-empty DefaultOps field.
913 if ((OperandNode->isSubClassOf("PredicateOperand") ||
914 OperandNode->isSubClassOf("OptionalDefOperand")) &&
915 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
916 continue;
917
918 // Verify that we didn't run out of provided operands.
919 if (ChildNo >= getNumChildren())
920 TP.error("Instruction '" + getOperator()->getName() +
921 "' expects more operands than were provided.");
922
Duncan Sands83ec4b62008-06-06 12:08:01 +0000923 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +0000924 TreePatternNode *Child = getChild(ChildNo++);
925 if (OperandNode->isSubClassOf("RegisterClass")) {
926 const CodeGenRegisterClass &RC =
927 CDP.getTargetInfo().getRegisterClass(OperandNode);
928 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
929 } else if (OperandNode->isSubClassOf("Operand")) {
930 VT = getValueType(OperandNode->getValueAsDef("Type"));
931 MadeChange |= Child->UpdateNodeType(VT, TP);
932 } else if (OperandNode->getName() == "ptr_rc") {
933 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +0000934 } else if (OperandNode->getName() == "unknown") {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000935 MadeChange |= Child->UpdateNodeType(EMVT::isUnknown, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000936 } else {
937 assert(0 && "Unknown operand type!");
938 abort();
939 }
940 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
941 }
Christopher Lamb5b415372008-03-11 09:33:47 +0000942
Christopher Lamb02f69372008-03-10 04:16:09 +0000943 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +0000944 TP.error("Instruction '" + getOperator()->getName() +
945 "' was provided too many operands!");
946
947 return MadeChange;
948 } else {
949 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
950
951 // Node transforms always take one operand.
952 if (getNumChildren() != 1)
953 TP.error("Node transform '" + getOperator()->getName() +
954 "' requires one operand!");
955
956 // If either the output or input of the xform does not have exact
957 // type info. We assume they must be the same. Otherwise, it is perfectly
958 // legal to transform from one type to a completely different type.
959 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
960 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
961 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
962 return MadeChange;
963 }
964 return false;
965 }
966}
967
968/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
969/// RHS of a commutative operation, not the on LHS.
970static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
971 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
972 return true;
973 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
974 return true;
975 return false;
976}
977
978
979/// canPatternMatch - If it is impossible for this pattern to match on this
980/// target, fill in Reason and return false. Otherwise, return true. This is
981/// used as a santity check for .td files (to prevent people from writing stuff
982/// that can never possibly work), and to prevent the pattern permuter from
983/// generating stuff that is useless.
984bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +0000985 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000986 if (isLeaf()) return true;
987
988 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
989 if (!getChild(i)->canPatternMatch(Reason, CDP))
990 return false;
991
992 // If this is an intrinsic, handle cases that would make it not match. For
993 // example, if an operand is required to be an immediate.
994 if (getOperator()->isSubClassOf("Intrinsic")) {
995 // TODO:
996 return true;
997 }
998
999 // If this node is a commutative operator, check that the LHS isn't an
1000 // immediate.
1001 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1002 if (NodeInfo.hasProperty(SDNPCommutative)) {
1003 // Scan all of the operands of the node and make sure that only the last one
1004 // is a constant node, unless the RHS also is.
1005 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1006 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
1007 if (OnlyOnRHSOfCommutative(getChild(i))) {
1008 Reason="Immediate value must be on the RHS of commutative operators!";
1009 return false;
1010 }
1011 }
1012 }
1013
1014 return true;
1015}
1016
1017//===----------------------------------------------------------------------===//
1018// TreePattern implementation
1019//
1020
1021TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001022 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001023 isInputPattern = isInput;
1024 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1025 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1026}
1027
1028TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001029 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001030 isInputPattern = isInput;
1031 Trees.push_back(ParseTreePattern(Pat));
1032}
1033
1034TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001035 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001036 isInputPattern = isInput;
1037 Trees.push_back(Pat);
1038}
1039
1040
1041
1042void TreePattern::error(const std::string &Msg) const {
1043 dump();
1044 throw "In " + TheRecord->getName() + ": " + Msg;
1045}
1046
1047TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1048 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1049 if (!OpDef) error("Pattern has unexpected operator type!");
1050 Record *Operator = OpDef->getDef();
1051
1052 if (Operator->isSubClassOf("ValueType")) {
1053 // If the operator is a ValueType, then this must be "type cast" of a leaf
1054 // node.
1055 if (Dag->getNumArgs() != 1)
1056 error("Type cast only takes one operand!");
1057
1058 Init *Arg = Dag->getArg(0);
1059 TreePatternNode *New;
1060 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1061 Record *R = DI->getDef();
1062 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1063 Dag->setArg(0, new DagInit(DI,
1064 std::vector<std::pair<Init*, std::string> >()));
1065 return ParseTreePattern(Dag);
1066 }
1067 New = new TreePatternNode(DI);
1068 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1069 New = ParseTreePattern(DI);
1070 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1071 New = new TreePatternNode(II);
1072 if (!Dag->getArgName(0).empty())
1073 error("Constant int argument should not have a name!");
1074 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1075 // Turn this into an IntInit.
1076 Init *II = BI->convertInitializerTo(new IntRecTy());
1077 if (II == 0 || !dynamic_cast<IntInit*>(II))
1078 error("Bits value must be constants!");
1079
1080 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1081 if (!Dag->getArgName(0).empty())
1082 error("Constant int argument should not have a name!");
1083 } else {
1084 Arg->dump();
1085 error("Unknown leaf value for tree pattern!");
1086 return 0;
1087 }
1088
1089 // Apply the type cast.
1090 New->UpdateNodeType(getValueType(Operator), *this);
1091 New->setName(Dag->getArgName(0));
1092 return New;
1093 }
1094
1095 // Verify that this is something that makes sense for an operator.
1096 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
1097 !Operator->isSubClassOf("Instruction") &&
1098 !Operator->isSubClassOf("SDNodeXForm") &&
1099 !Operator->isSubClassOf("Intrinsic") &&
1100 Operator->getName() != "set" &&
1101 Operator->getName() != "implicit" &&
1102 Operator->getName() != "parallel")
1103 error("Unrecognized node '" + Operator->getName() + "'!");
1104
1105 // Check to see if this is something that is illegal in an input pattern.
1106 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1107 Operator->isSubClassOf("SDNodeXForm")))
1108 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1109
1110 std::vector<TreePatternNode*> Children;
1111
1112 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1113 Init *Arg = Dag->getArg(i);
1114 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1115 Children.push_back(ParseTreePattern(DI));
1116 if (Children.back()->getName().empty())
1117 Children.back()->setName(Dag->getArgName(i));
1118 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1119 Record *R = DefI->getDef();
1120 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1121 // TreePatternNode if its own.
1122 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1123 Dag->setArg(i, new DagInit(DefI,
1124 std::vector<std::pair<Init*, std::string> >()));
1125 --i; // Revisit this node...
1126 } else {
1127 TreePatternNode *Node = new TreePatternNode(DefI);
1128 Node->setName(Dag->getArgName(i));
1129 Children.push_back(Node);
1130
1131 // Input argument?
1132 if (R->getName() == "node") {
1133 if (Dag->getArgName(i).empty())
1134 error("'node' argument requires a name to match with operand list");
1135 Args.push_back(Dag->getArgName(i));
1136 }
1137 }
1138 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1139 TreePatternNode *Node = new TreePatternNode(II);
1140 if (!Dag->getArgName(i).empty())
1141 error("Constant int argument should not have a name!");
1142 Children.push_back(Node);
1143 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1144 // Turn this into an IntInit.
1145 Init *II = BI->convertInitializerTo(new IntRecTy());
1146 if (II == 0 || !dynamic_cast<IntInit*>(II))
1147 error("Bits value must be constants!");
1148
1149 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1150 if (!Dag->getArgName(i).empty())
1151 error("Constant int argument should not have a name!");
1152 Children.push_back(Node);
1153 } else {
1154 cerr << '"';
1155 Arg->dump();
1156 cerr << "\": ";
1157 error("Unknown leaf value for tree pattern!");
1158 }
1159 }
1160
1161 // If the operator is an intrinsic, then this is just syntactic sugar for for
1162 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1163 // convert the intrinsic name to a number.
1164 if (Operator->isSubClassOf("Intrinsic")) {
1165 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1166 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1167
1168 // If this intrinsic returns void, it must have side-effects and thus a
1169 // chain.
1170 if (Int.ArgVTs[0] == MVT::isVoid) {
1171 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1172 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1173 // Has side-effects, requires chain.
1174 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1175 } else {
1176 // Otherwise, no chain.
1177 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1178 }
1179
1180 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1181 Children.insert(Children.begin(), IIDNode);
1182 }
1183
1184 return new TreePatternNode(Operator, Children);
1185}
1186
1187/// InferAllTypes - Infer/propagate as many types throughout the expression
1188/// patterns as possible. Return true if all types are infered, false
1189/// otherwise. Throw an exception if a type contradiction is found.
1190bool TreePattern::InferAllTypes() {
1191 bool MadeChange = true;
1192 while (MadeChange) {
1193 MadeChange = false;
1194 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1195 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1196 }
1197
1198 bool HasUnresolvedTypes = false;
1199 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1200 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1201 return !HasUnresolvedTypes;
1202}
1203
1204void TreePattern::print(std::ostream &OS) const {
1205 OS << getRecord()->getName();
1206 if (!Args.empty()) {
1207 OS << "(" << Args[0];
1208 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1209 OS << ", " << Args[i];
1210 OS << ")";
1211 }
1212 OS << ": ";
1213
1214 if (Trees.size() > 1)
1215 OS << "[\n";
1216 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1217 OS << "\t";
1218 Trees[i]->print(OS);
1219 OS << "\n";
1220 }
1221
1222 if (Trees.size() > 1)
1223 OS << "]\n";
1224}
1225
1226void TreePattern::dump() const { print(*cerr.stream()); }
1227
1228//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001229// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001230//
1231
1232// FIXME: REMOVE OSTREAM ARGUMENT
Chris Lattnerfe718932008-01-06 01:10:31 +00001233CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001234 Intrinsics = LoadIntrinsics(Records);
1235 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001236 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001237 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001238 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001239 ParseDefaultOperands();
1240 ParseInstructions();
1241 ParsePatterns();
1242
1243 // Generate variants. For example, commutative patterns can match
1244 // multiple ways. Add them to PatternsToMatch as well.
1245 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001246
1247 // Infer instruction flags. For example, we can detect loads,
1248 // stores, and side effects in many cases by examining an
1249 // instruction's pattern.
1250 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001251}
1252
Chris Lattnerfe718932008-01-06 01:10:31 +00001253CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001254 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1255 E = PatternFragments.end(); I != E; ++I)
1256 delete I->second;
1257}
1258
1259
Chris Lattnerfe718932008-01-06 01:10:31 +00001260Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001261 Record *N = Records.getDef(Name);
1262 if (!N || !N->isSubClassOf("SDNode")) {
1263 cerr << "Error getting SDNode '" << Name << "'!\n";
1264 exit(1);
1265 }
1266 return N;
1267}
1268
1269// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001270void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001271 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1272 while (!Nodes.empty()) {
1273 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1274 Nodes.pop_back();
1275 }
1276
1277 // Get the buildin intrinsic nodes.
1278 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1279 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1280 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1281}
1282
1283/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1284/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001285void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001286 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1287 while (!Xforms.empty()) {
1288 Record *XFormNode = Xforms.back();
1289 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1290 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001291 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001292
1293 Xforms.pop_back();
1294 }
1295}
1296
Chris Lattnerfe718932008-01-06 01:10:31 +00001297void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001298 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1299 while (!AMs.empty()) {
1300 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1301 AMs.pop_back();
1302 }
1303}
1304
1305
1306/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1307/// file, building up the PatternFragments map. After we've collected them all,
1308/// inline fragments together as necessary, so that there are no references left
1309/// inside a pattern fragment to a pattern fragment.
1310///
Chris Lattnerfe718932008-01-06 01:10:31 +00001311void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001312 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1313
Chris Lattnerdc32f982008-01-05 22:43:57 +00001314 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001315 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1316 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1317 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1318 PatternFragments[Fragments[i]] = P;
1319
Chris Lattnerdc32f982008-01-05 22:43:57 +00001320 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001321 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001322 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001323
Chris Lattnerdc32f982008-01-05 22:43:57 +00001324 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001325 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1326
1327 // Parse the operands list.
1328 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1329 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1330 // Special cases: ops == outs == ins. Different names are used to
1331 // improve readibility.
1332 if (!OpsOp ||
1333 (OpsOp->getDef()->getName() != "ops" &&
1334 OpsOp->getDef()->getName() != "outs" &&
1335 OpsOp->getDef()->getName() != "ins"))
1336 P->error("Operands list should start with '(ops ... '!");
1337
1338 // Copy over the arguments.
1339 Args.clear();
1340 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1341 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1342 static_cast<DefInit*>(OpsList->getArg(j))->
1343 getDef()->getName() != "node")
1344 P->error("Operands list should all be 'node' values.");
1345 if (OpsList->getArgName(j).empty())
1346 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001347 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001348 P->error("'" + OpsList->getArgName(j) +
1349 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001350 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001351 Args.push_back(OpsList->getArgName(j));
1352 }
1353
Chris Lattnerdc32f982008-01-05 22:43:57 +00001354 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001355 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001356 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001357
Chris Lattnerdc32f982008-01-05 22:43:57 +00001358 // If there is a code init for this fragment, keep track of the fact that
1359 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001360 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001361 if (!Code.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001362 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001363
1364 // If there is a node transformation corresponding to this, keep track of
1365 // it.
1366 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1367 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1368 P->getOnlyTree()->setTransformFn(Transform);
1369 }
1370
Chris Lattner6cefb772008-01-05 22:25:12 +00001371 // Now that we've parsed all of the tree fragments, do a closure on them so
1372 // that there are not references to PatFrags left inside of them.
1373 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1374 E = PatternFragments.end(); I != E; ++I) {
1375 TreePattern *ThePat = I->second;
1376 ThePat->InlinePatternFragments();
1377
1378 // Infer as many types as possible. Don't worry about it if we don't infer
1379 // all of them, some may depend on the inputs of the pattern.
1380 try {
1381 ThePat->InferAllTypes();
1382 } catch (...) {
1383 // If this pattern fragment is not supported by this target (no types can
1384 // satisfy its constraints), just ignore it. If the bogus pattern is
1385 // actually used by instructions, the type consistency error will be
1386 // reported there.
1387 }
1388
1389 // If debugging, print out the pattern fragment result.
1390 DEBUG(ThePat->dump());
1391 }
1392}
1393
Chris Lattnerfe718932008-01-06 01:10:31 +00001394void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001395 std::vector<Record*> DefaultOps[2];
1396 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1397 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1398
1399 // Find some SDNode.
1400 assert(!SDNodes.empty() && "No SDNodes parsed?");
1401 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1402
1403 for (unsigned iter = 0; iter != 2; ++iter) {
1404 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1405 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1406
1407 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1408 // SomeSDnode so that we can parse this.
1409 std::vector<std::pair<Init*, std::string> > Ops;
1410 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1411 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1412 DefaultInfo->getArgName(op)));
1413 DagInit *DI = new DagInit(SomeSDNode, Ops);
1414
1415 // Create a TreePattern to parse this.
1416 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1417 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1418
1419 // Copy the operands over into a DAGDefaultOperand.
1420 DAGDefaultOperand DefaultOpInfo;
1421
1422 TreePatternNode *T = P.getTree(0);
1423 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1424 TreePatternNode *TPN = T->getChild(op);
1425 while (TPN->ApplyTypeConstraints(P, false))
1426 /* Resolve all types */;
1427
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001428 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001429 if (iter == 0)
1430 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1431 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1432 else
1433 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1434 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001435 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001436 DefaultOpInfo.DefaultOps.push_back(TPN);
1437 }
1438
1439 // Insert it into the DefaultOperands map so we can find it later.
1440 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1441 }
1442 }
1443}
1444
1445/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1446/// instruction input. Return true if this is a real use.
1447static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1448 std::map<std::string, TreePatternNode*> &InstInputs,
1449 std::vector<Record*> &InstImpInputs) {
1450 // No name -> not interesting.
1451 if (Pat->getName().empty()) {
1452 if (Pat->isLeaf()) {
1453 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1454 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1455 I->error("Input " + DI->getDef()->getName() + " must be named!");
1456 else if (DI && DI->getDef()->isSubClassOf("Register"))
1457 InstImpInputs.push_back(DI->getDef());
1458 ;
1459 }
1460 return false;
1461 }
1462
1463 Record *Rec;
1464 if (Pat->isLeaf()) {
1465 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1466 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1467 Rec = DI->getDef();
1468 } else {
1469 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1470 Rec = Pat->getOperator();
1471 }
1472
1473 // SRCVALUE nodes are ignored.
1474 if (Rec->getName() == "srcvalue")
1475 return false;
1476
1477 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1478 if (!Slot) {
1479 Slot = Pat;
1480 } else {
1481 Record *SlotRec;
1482 if (Slot->isLeaf()) {
1483 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1484 } else {
1485 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1486 SlotRec = Slot->getOperator();
1487 }
1488
1489 // Ensure that the inputs agree if we've already seen this input.
1490 if (Rec != SlotRec)
1491 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1492 if (Slot->getExtTypes() != Pat->getExtTypes())
1493 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1494 }
1495 return true;
1496}
1497
1498/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1499/// part of "I", the instruction), computing the set of inputs and outputs of
1500/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001501void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001502FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1503 std::map<std::string, TreePatternNode*> &InstInputs,
1504 std::map<std::string, TreePatternNode*>&InstResults,
1505 std::vector<Record*> &InstImpInputs,
1506 std::vector<Record*> &InstImpResults) {
1507 if (Pat->isLeaf()) {
1508 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1509 if (!isUse && Pat->getTransformFn())
1510 I->error("Cannot specify a transform function for a non-input value!");
1511 return;
1512 } else if (Pat->getOperator()->getName() == "implicit") {
1513 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1514 TreePatternNode *Dest = Pat->getChild(i);
1515 if (!Dest->isLeaf())
1516 I->error("implicitly defined value should be a register!");
1517
1518 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1519 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1520 I->error("implicitly defined value should be a register!");
1521 InstImpResults.push_back(Val->getDef());
1522 }
1523 return;
1524 } else if (Pat->getOperator()->getName() != "set") {
1525 // If this is not a set, verify that the children nodes are not void typed,
1526 // and recurse.
1527 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1528 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1529 I->error("Cannot have void nodes inside of patterns!");
1530 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1531 InstImpInputs, InstImpResults);
1532 }
1533
1534 // If this is a non-leaf node with no children, treat it basically as if
1535 // it were a leaf. This handles nodes like (imm).
1536 bool isUse = false;
1537 if (Pat->getNumChildren() == 0)
1538 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1539
1540 if (!isUse && Pat->getTransformFn())
1541 I->error("Cannot specify a transform function for a non-input value!");
1542 return;
1543 }
1544
1545 // Otherwise, this is a set, validate and collect instruction results.
1546 if (Pat->getNumChildren() == 0)
1547 I->error("set requires operands!");
1548
1549 if (Pat->getTransformFn())
1550 I->error("Cannot specify a transform function on a set node!");
1551
1552 // Check the set destinations.
1553 unsigned NumDests = Pat->getNumChildren()-1;
1554 for (unsigned i = 0; i != NumDests; ++i) {
1555 TreePatternNode *Dest = Pat->getChild(i);
1556 if (!Dest->isLeaf())
1557 I->error("set destination should be a register!");
1558
1559 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1560 if (!Val)
1561 I->error("set destination should be a register!");
1562
1563 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1564 Val->getDef()->getName() == "ptr_rc") {
1565 if (Dest->getName().empty())
1566 I->error("set destination must have a name!");
1567 if (InstResults.count(Dest->getName()))
1568 I->error("cannot set '" + Dest->getName() +"' multiple times");
1569 InstResults[Dest->getName()] = Dest;
1570 } else if (Val->getDef()->isSubClassOf("Register")) {
1571 InstImpResults.push_back(Val->getDef());
1572 } else {
1573 I->error("set destination should be a register!");
1574 }
1575 }
1576
1577 // Verify and collect info from the computation.
1578 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1579 InstInputs, InstResults,
1580 InstImpInputs, InstImpResults);
1581}
1582
Dan Gohmanee4fa192008-04-03 00:02:49 +00001583//===----------------------------------------------------------------------===//
1584// Instruction Analysis
1585//===----------------------------------------------------------------------===//
1586
1587class InstAnalyzer {
1588 const CodeGenDAGPatterns &CDP;
1589 bool &mayStore;
1590 bool &mayLoad;
1591 bool &HasSideEffects;
1592public:
1593 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1594 bool &maystore, bool &mayload, bool &hse)
1595 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1596 }
1597
1598 /// Analyze - Analyze the specified instruction, returning true if the
1599 /// instruction had a pattern.
1600 bool Analyze(Record *InstRecord) {
1601 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1602 if (Pattern == 0) {
1603 HasSideEffects = 1;
1604 return false; // No pattern.
1605 }
1606
1607 // FIXME: Assume only the first tree is the pattern. The others are clobber
1608 // nodes.
1609 AnalyzeNode(Pattern->getTree(0));
1610 return true;
1611 }
1612
1613private:
1614 void AnalyzeNode(const TreePatternNode *N) {
1615 if (N->isLeaf()) {
1616 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1617 Record *LeafRec = DI->getDef();
1618 // Handle ComplexPattern leaves.
1619 if (LeafRec->isSubClassOf("ComplexPattern")) {
1620 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1621 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1622 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1623 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1624 }
1625 }
1626 return;
1627 }
1628
1629 // Analyze children.
1630 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1631 AnalyzeNode(N->getChild(i));
1632
1633 // Ignore set nodes, which are not SDNodes.
1634 if (N->getOperator()->getName() == "set")
1635 return;
1636
1637 // Get information about the SDNode for the operator.
1638 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1639
1640 // Notice properties of the node.
1641 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1642 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1643 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1644
1645 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1646 // If this is an intrinsic, analyze it.
1647 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1648 mayLoad = true;// These may load memory.
1649
1650 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1651 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1652
1653 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1654 // WriteMem intrinsics can have other strange effects.
1655 HasSideEffects = true;
1656 }
1657 }
1658
1659};
1660
1661static void InferFromPattern(const CodeGenInstruction &Inst,
1662 bool &MayStore, bool &MayLoad,
1663 bool &HasSideEffects,
1664 const CodeGenDAGPatterns &CDP) {
1665 MayStore = MayLoad = HasSideEffects = false;
1666
1667 bool HadPattern =
1668 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1669
1670 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1671 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1672 // If we decided that this is a store from the pattern, then the .td file
1673 // entry is redundant.
1674 if (MayStore)
1675 fprintf(stderr,
1676 "Warning: mayStore flag explicitly set on instruction '%s'"
1677 " but flag already inferred from pattern.\n",
1678 Inst.TheDef->getName().c_str());
1679 MayStore = true;
1680 }
1681
1682 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1683 // If we decided that this is a load from the pattern, then the .td file
1684 // entry is redundant.
1685 if (MayLoad)
1686 fprintf(stderr,
1687 "Warning: mayLoad flag explicitly set on instruction '%s'"
1688 " but flag already inferred from pattern.\n",
1689 Inst.TheDef->getName().c_str());
1690 MayLoad = true;
1691 }
1692
1693 if (Inst.neverHasSideEffects) {
1694 if (HadPattern)
1695 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1696 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1697 HasSideEffects = false;
1698 }
1699
1700 if (Inst.hasSideEffects) {
1701 if (HasSideEffects)
1702 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1703 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1704 HasSideEffects = true;
1705 }
1706}
1707
Chris Lattner6cefb772008-01-05 22:25:12 +00001708/// ParseInstructions - Parse all of the instructions, inlining and resolving
1709/// any fragments involved. This populates the Instructions list with fully
1710/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001711void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001712 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1713
1714 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1715 ListInit *LI = 0;
1716
1717 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1718 LI = Instrs[i]->getValueAsListInit("Pattern");
1719
1720 // If there is no pattern, only collect minimal information about the
1721 // instruction for its operand list. We have to assume that there is one
1722 // result, as we have no detailed info.
1723 if (!LI || LI->getSize() == 0) {
1724 std::vector<Record*> Results;
1725 std::vector<Record*> Operands;
1726
1727 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1728
1729 if (InstInfo.OperandList.size() != 0) {
1730 if (InstInfo.NumDefs == 0) {
1731 // These produce no results
1732 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1733 Operands.push_back(InstInfo.OperandList[j].Rec);
1734 } else {
1735 // Assume the first operand is the result.
1736 Results.push_back(InstInfo.OperandList[0].Rec);
1737
1738 // The rest are inputs.
1739 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1740 Operands.push_back(InstInfo.OperandList[j].Rec);
1741 }
1742 }
1743
1744 // Create and insert the instruction.
1745 std::vector<Record*> ImpResults;
1746 std::vector<Record*> ImpOperands;
1747 Instructions.insert(std::make_pair(Instrs[i],
1748 DAGInstruction(0, Results, Operands, ImpResults,
1749 ImpOperands)));
1750 continue; // no pattern.
1751 }
1752
1753 // Parse the instruction.
1754 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1755 // Inline pattern fragments into it.
1756 I->InlinePatternFragments();
1757
1758 // Infer as many types as possible. If we cannot infer all of them, we can
1759 // never do anything with this instruction pattern: report it to the user.
1760 if (!I->InferAllTypes())
1761 I->error("Could not infer all types in pattern!");
1762
1763 // InstInputs - Keep track of all of the inputs of the instruction, along
1764 // with the record they are declared as.
1765 std::map<std::string, TreePatternNode*> InstInputs;
1766
1767 // InstResults - Keep track of all the virtual registers that are 'set'
1768 // in the instruction, including what reg class they are.
1769 std::map<std::string, TreePatternNode*> InstResults;
1770
1771 std::vector<Record*> InstImpInputs;
1772 std::vector<Record*> InstImpResults;
1773
1774 // Verify that the top-level forms in the instruction are of void type, and
1775 // fill in the InstResults map.
1776 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1777 TreePatternNode *Pat = I->getTree(j);
1778 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1779 I->error("Top-level forms in instruction pattern should have"
1780 " void types");
1781
1782 // Find inputs and outputs, and verify the structure of the uses/defs.
1783 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1784 InstImpInputs, InstImpResults);
1785 }
1786
1787 // Now that we have inputs and outputs of the pattern, inspect the operands
1788 // list for the instruction. This determines the order that operands are
1789 // added to the machine instruction the node corresponds to.
1790 unsigned NumResults = InstResults.size();
1791
1792 // Parse the operands list from the (ops) list, validating it.
1793 assert(I->getArgList().empty() && "Args list should still be empty here!");
1794 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1795
1796 // Check that all of the results occur first in the list.
1797 std::vector<Record*> Results;
1798 TreePatternNode *Res0Node = NULL;
1799 for (unsigned i = 0; i != NumResults; ++i) {
1800 if (i == CGI.OperandList.size())
1801 I->error("'" + InstResults.begin()->first +
1802 "' set but does not appear in operand list!");
1803 const std::string &OpName = CGI.OperandList[i].Name;
1804
1805 // Check that it exists in InstResults.
1806 TreePatternNode *RNode = InstResults[OpName];
1807 if (RNode == 0)
1808 I->error("Operand $" + OpName + " does not exist in operand list!");
1809
1810 if (i == 0)
1811 Res0Node = RNode;
1812 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1813 if (R == 0)
1814 I->error("Operand $" + OpName + " should be a set destination: all "
1815 "outputs must occur before inputs in operand list!");
1816
1817 if (CGI.OperandList[i].Rec != R)
1818 I->error("Operand $" + OpName + " class mismatch!");
1819
1820 // Remember the return type.
1821 Results.push_back(CGI.OperandList[i].Rec);
1822
1823 // Okay, this one checks out.
1824 InstResults.erase(OpName);
1825 }
1826
1827 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1828 // the copy while we're checking the inputs.
1829 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1830
1831 std::vector<TreePatternNode*> ResultNodeOperands;
1832 std::vector<Record*> Operands;
1833 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1834 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1835 const std::string &OpName = Op.Name;
1836 if (OpName.empty())
1837 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1838
1839 if (!InstInputsCheck.count(OpName)) {
1840 // If this is an predicate operand or optional def operand with an
1841 // DefaultOps set filled in, we can ignore this. When we codegen it,
1842 // we will do so as always executed.
1843 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1844 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1845 // Does it have a non-empty DefaultOps field? If so, ignore this
1846 // operand.
1847 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1848 continue;
1849 }
1850 I->error("Operand $" + OpName +
1851 " does not appear in the instruction pattern");
1852 }
1853 TreePatternNode *InVal = InstInputsCheck[OpName];
1854 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1855
1856 if (InVal->isLeaf() &&
1857 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1858 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1859 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1860 I->error("Operand $" + OpName + "'s register class disagrees"
1861 " between the operand and pattern");
1862 }
1863 Operands.push_back(Op.Rec);
1864
1865 // Construct the result for the dest-pattern operand list.
1866 TreePatternNode *OpNode = InVal->clone();
1867
1868 // No predicate is useful on the result.
1869 OpNode->setPredicateFn("");
1870
1871 // Promote the xform function to be an explicit node if set.
1872 if (Record *Xform = OpNode->getTransformFn()) {
1873 OpNode->setTransformFn(0);
1874 std::vector<TreePatternNode*> Children;
1875 Children.push_back(OpNode);
1876 OpNode = new TreePatternNode(Xform, Children);
1877 }
1878
1879 ResultNodeOperands.push_back(OpNode);
1880 }
1881
1882 if (!InstInputsCheck.empty())
1883 I->error("Input operand $" + InstInputsCheck.begin()->first +
1884 " occurs in pattern but not in operands list!");
1885
1886 TreePatternNode *ResultPattern =
1887 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1888 // Copy fully inferred output node type to instruction result pattern.
1889 if (NumResults > 0)
1890 ResultPattern->setTypes(Res0Node->getExtTypes());
1891
1892 // Create and insert the instruction.
1893 // FIXME: InstImpResults and InstImpInputs should not be part of
1894 // DAGInstruction.
1895 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1896 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1897
1898 // Use a temporary tree pattern to infer all types and make sure that the
1899 // constructed result is correct. This depends on the instruction already
1900 // being inserted into the Instructions map.
1901 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1902 Temp.InferAllTypes();
1903
1904 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1905 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1906
1907 DEBUG(I->dump());
1908 }
1909
1910 // If we can, convert the instructions to be patterns that are matched!
1911 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1912 E = Instructions.end(); II != E; ++II) {
1913 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00001914 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00001915 if (I == 0) continue; // No pattern.
1916
1917 // FIXME: Assume only the first tree is the pattern. The others are clobber
1918 // nodes.
1919 TreePatternNode *Pattern = I->getTree(0);
1920 TreePatternNode *SrcPattern;
1921 if (Pattern->getOperator()->getName() == "set") {
1922 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1923 } else{
1924 // Not a set (store or something?)
1925 SrcPattern = Pattern;
1926 }
1927
1928 std::string Reason;
1929 if (!SrcPattern->canPatternMatch(Reason, *this))
1930 I->error("Instruction can never match: " + Reason);
1931
1932 Record *Instr = II->first;
1933 TreePatternNode *DstPattern = TheInst.getResultPattern();
1934 PatternsToMatch.
1935 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1936 SrcPattern, DstPattern, TheInst.getImpResults(),
1937 Instr->getValueAsInt("AddedComplexity")));
1938 }
1939}
1940
Dan Gohmanee4fa192008-04-03 00:02:49 +00001941
1942void CodeGenDAGPatterns::InferInstructionFlags() {
1943 std::map<std::string, CodeGenInstruction> &InstrDescs =
1944 Target.getInstructions();
1945 for (std::map<std::string, CodeGenInstruction>::iterator
1946 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
1947 CodeGenInstruction &InstInfo = II->second;
1948 // Determine properties of the instruction from its pattern.
1949 bool MayStore, MayLoad, HasSideEffects;
1950 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
1951 InstInfo.mayStore = MayStore;
1952 InstInfo.mayLoad = MayLoad;
1953 InstInfo.hasSideEffects = HasSideEffects;
1954 }
1955}
1956
Chris Lattnerfe718932008-01-06 01:10:31 +00001957void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001958 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1959
1960 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1961 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1962 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1963 Record *Operator = OpDef->getDef();
1964 TreePattern *Pattern;
1965 if (Operator->getName() != "parallel")
1966 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1967 else {
1968 std::vector<Init*> Values;
1969 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1970 Values.push_back(Tree->getArg(j));
1971 ListInit *LI = new ListInit(Values);
1972 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1973 }
1974
1975 // Inline pattern fragments into it.
1976 Pattern->InlinePatternFragments();
1977
1978 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1979 if (LI->getSize() == 0) continue; // no pattern.
1980
1981 // Parse the instruction.
1982 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1983
1984 // Inline pattern fragments into it.
1985 Result->InlinePatternFragments();
1986
1987 if (Result->getNumTrees() != 1)
1988 Result->error("Cannot handle instructions producing instructions "
1989 "with temporaries yet!");
1990
1991 bool IterateInference;
1992 bool InferredAllPatternTypes, InferredAllResultTypes;
1993 do {
1994 // Infer as many types as possible. If we cannot infer all of them, we
1995 // can never do anything with this pattern: report it to the user.
1996 InferredAllPatternTypes = Pattern->InferAllTypes();
1997
1998 // Infer as many types as possible. If we cannot infer all of them, we
1999 // can never do anything with this pattern: report it to the user.
2000 InferredAllResultTypes = Result->InferAllTypes();
2001
2002 // Apply the type of the result to the source pattern. This helps us
2003 // resolve cases where the input type is known to be a pointer type (which
2004 // is considered resolved), but the result knows it needs to be 32- or
2005 // 64-bits. Infer the other way for good measure.
2006 IterateInference = Pattern->getTree(0)->
2007 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2008 IterateInference |= Result->getTree(0)->
2009 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2010 } while (IterateInference);
2011
2012 // Verify that we inferred enough types that we can do something with the
2013 // pattern and result. If these fire the user has to add type casts.
2014 if (!InferredAllPatternTypes)
2015 Pattern->error("Could not infer all types in pattern!");
2016 if (!InferredAllResultTypes)
2017 Result->error("Could not infer all types in pattern result!");
2018
2019 // Validate that the input pattern is correct.
2020 std::map<std::string, TreePatternNode*> InstInputs;
2021 std::map<std::string, TreePatternNode*> InstResults;
2022 std::vector<Record*> InstImpInputs;
2023 std::vector<Record*> InstImpResults;
2024 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2025 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2026 InstInputs, InstResults,
2027 InstImpInputs, InstImpResults);
2028
2029 // Promote the xform function to be an explicit node if set.
2030 TreePatternNode *DstPattern = Result->getOnlyTree();
2031 std::vector<TreePatternNode*> ResultNodeOperands;
2032 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2033 TreePatternNode *OpNode = DstPattern->getChild(ii);
2034 if (Record *Xform = OpNode->getTransformFn()) {
2035 OpNode->setTransformFn(0);
2036 std::vector<TreePatternNode*> Children;
2037 Children.push_back(OpNode);
2038 OpNode = new TreePatternNode(Xform, Children);
2039 }
2040 ResultNodeOperands.push_back(OpNode);
2041 }
2042 DstPattern = Result->getOnlyTree();
2043 if (!DstPattern->isLeaf())
2044 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2045 ResultNodeOperands);
2046 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2047 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2048 Temp.InferAllTypes();
2049
2050 std::string Reason;
2051 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2052 Pattern->error("Pattern can never match: " + Reason);
2053
2054 PatternsToMatch.
2055 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2056 Pattern->getTree(0),
2057 Temp.getOnlyTree(), InstImpResults,
2058 Patterns[i]->getValueAsInt("AddedComplexity")));
2059 }
2060}
2061
2062/// CombineChildVariants - Given a bunch of permutations of each child of the
2063/// 'operator' node, put them together in all possible ways.
2064static void CombineChildVariants(TreePatternNode *Orig,
2065 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2066 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002067 CodeGenDAGPatterns &CDP,
2068 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002069 // Make sure that each operand has at least one variant to choose from.
2070 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2071 if (ChildVariants[i].empty())
2072 return;
2073
2074 // The end result is an all-pairs construction of the resultant pattern.
2075 std::vector<unsigned> Idxs;
2076 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002077 bool NotDone;
2078 do {
2079#ifndef NDEBUG
2080 if (DebugFlag && !Idxs.empty()) {
2081 cerr << Orig->getOperator()->getName() << ": Idxs = [ ";
2082 for (unsigned i = 0; i < Idxs.size(); ++i) {
2083 cerr << Idxs[i] << " ";
2084 }
2085 cerr << "]\n";
2086 }
2087#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002088 // Create the variant and add it to the output list.
2089 std::vector<TreePatternNode*> NewChildren;
2090 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2091 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2092 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2093
2094 // Copy over properties.
2095 R->setName(Orig->getName());
2096 R->setPredicateFn(Orig->getPredicateFn());
2097 R->setTransformFn(Orig->getTransformFn());
2098 R->setTypes(Orig->getExtTypes());
2099
Scott Michel327d0652008-03-05 17:49:05 +00002100 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002101 std::string ErrString;
2102 if (!R->canPatternMatch(ErrString, CDP)) {
2103 delete R;
2104 } else {
2105 bool AlreadyExists = false;
2106
2107 // Scan to see if this pattern has already been emitted. We can get
2108 // duplication due to things like commuting:
2109 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2110 // which are the same pattern. Ignore the dups.
2111 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002112 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002113 AlreadyExists = true;
2114 break;
2115 }
2116
2117 if (AlreadyExists)
2118 delete R;
2119 else
2120 OutVariants.push_back(R);
2121 }
2122
Scott Michel327d0652008-03-05 17:49:05 +00002123 // Increment indices to the next permutation by incrementing the
2124 // indicies from last index backward, e.g., generate the sequence
2125 // [0, 0], [0, 1], [1, 0], [1, 1].
2126 int IdxsIdx;
2127 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2128 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2129 Idxs[IdxsIdx] = 0;
2130 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002131 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002132 }
Scott Michel327d0652008-03-05 17:49:05 +00002133 NotDone = (IdxsIdx >= 0);
2134 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002135}
2136
2137/// CombineChildVariants - A helper function for binary operators.
2138///
2139static void CombineChildVariants(TreePatternNode *Orig,
2140 const std::vector<TreePatternNode*> &LHS,
2141 const std::vector<TreePatternNode*> &RHS,
2142 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002143 CodeGenDAGPatterns &CDP,
2144 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002145 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2146 ChildVariants.push_back(LHS);
2147 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002148 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002149}
2150
2151
2152static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2153 std::vector<TreePatternNode *> &Children) {
2154 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2155 Record *Operator = N->getOperator();
2156
2157 // Only permit raw nodes.
2158 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
2159 N->getTransformFn()) {
2160 Children.push_back(N);
2161 return;
2162 }
2163
2164 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2165 Children.push_back(N->getChild(0));
2166 else
2167 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2168
2169 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2170 Children.push_back(N->getChild(1));
2171 else
2172 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2173}
2174
2175/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2176/// the (potentially recursive) pattern by using algebraic laws.
2177///
2178static void GenerateVariantsOf(TreePatternNode *N,
2179 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002180 CodeGenDAGPatterns &CDP,
2181 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002182 // We cannot permute leaves.
2183 if (N->isLeaf()) {
2184 OutVariants.push_back(N);
2185 return;
2186 }
2187
2188 // Look up interesting info about the node.
2189 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2190
2191 // If this node is associative, reassociate.
2192 if (NodeInfo.hasProperty(SDNPAssociative)) {
2193 // Reassociate by pulling together all of the linked operators
2194 std::vector<TreePatternNode*> MaximalChildren;
2195 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2196
2197 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2198 // permutations.
2199 if (MaximalChildren.size() == 3) {
2200 // Find the variants of all of our maximal children.
2201 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002202 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2203 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2204 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002205
2206 // There are only two ways we can permute the tree:
2207 // (A op B) op C and A op (B op C)
2208 // Within these forms, we can also permute A/B/C.
2209
2210 // Generate legal pair permutations of A/B/C.
2211 std::vector<TreePatternNode*> ABVariants;
2212 std::vector<TreePatternNode*> BAVariants;
2213 std::vector<TreePatternNode*> ACVariants;
2214 std::vector<TreePatternNode*> CAVariants;
2215 std::vector<TreePatternNode*> BCVariants;
2216 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002217 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2218 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2219 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2220 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2221 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2222 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002223
2224 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002225 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2226 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2227 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2228 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2229 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2230 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002231
2232 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002233 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2234 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2235 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2236 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2237 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2238 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002239 return;
2240 }
2241 }
2242
2243 // Compute permutations of all children.
2244 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2245 ChildVariants.resize(N->getNumChildren());
2246 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002247 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002248
2249 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002250 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002251
2252 // If this node is commutative, consider the commuted order.
2253 if (NodeInfo.hasProperty(SDNPCommutative)) {
2254 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
2255 // Don't count children which are actually register references.
2256 unsigned NC = 0;
2257 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2258 TreePatternNode *Child = N->getChild(i);
2259 if (Child->isLeaf())
2260 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2261 Record *RR = DI->getDef();
2262 if (RR->isSubClassOf("Register"))
2263 continue;
2264 }
2265 NC++;
2266 }
2267 // Consider the commuted order.
2268 if (NC == 2)
2269 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002270 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002271 }
2272}
2273
2274
2275// GenerateVariants - Generate variants. For example, commutative patterns can
2276// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002277void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002278 DOUT << "Generating instruction variants.\n";
2279
2280 // Loop over all of the patterns we've collected, checking to see if we can
2281 // generate variants of the instruction, through the exploitation of
2282 // identities. This permits the target to provide agressive matching without
2283 // the .td file having to contain tons of variants of instructions.
2284 //
2285 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2286 // intentionally do not reconsider these. Any variants of added patterns have
2287 // already been added.
2288 //
2289 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002290 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002291 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002292 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2293 DOUT << "Dependent/multiply used variables: ";
2294 DEBUG(DumpDepVars(DepVars));
2295 DOUT << "\n";
2296 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002297
2298 assert(!Variants.empty() && "Must create at least original variant!");
2299 Variants.erase(Variants.begin()); // Remove the original pattern.
2300
2301 if (Variants.empty()) // No variants for this pattern.
2302 continue;
2303
2304 DOUT << "FOUND VARIANTS OF: ";
2305 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2306 DOUT << "\n";
2307
2308 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2309 TreePatternNode *Variant = Variants[v];
2310
2311 DOUT << " VAR#" << v << ": ";
2312 DEBUG(Variant->dump());
2313 DOUT << "\n";
2314
2315 // Scan to see if an instruction or explicit pattern already matches this.
2316 bool AlreadyExists = false;
2317 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2318 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002319 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002320 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2321 AlreadyExists = true;
2322 break;
2323 }
2324 }
2325 // If we already have it, ignore the variant.
2326 if (AlreadyExists) continue;
2327
2328 // Otherwise, add it to the list of patterns we have.
2329 PatternsToMatch.
2330 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2331 Variant, PatternsToMatch[i].getDstPattern(),
2332 PatternsToMatch[i].getDstRegs(),
2333 PatternsToMatch[i].getAddedComplexity()));
2334 }
2335
2336 DOUT << "\n";
2337 }
2338}
2339