blob: eb0b0990488bc3d8ae74e30f9df9ac7deb8b3784 [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
Chris Lattner6cefb772008-01-05 22:25:12 +000078namespace llvm {
Duncan Sands83ec4b62008-06-06 12:08:01 +000079namespace EMVT {
Dan Gohman4b6fce42009-03-31 16:48:35 +000080/// isExtIntegerInVTs - Return true if the specified extended value type vector
81/// contains isInt or an integer value type.
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
Dan Gohman4b6fce42009-03-31 16:48:35 +000087/// isExtFloatingPointInVTs - Return true if the specified extended value type
Chris Lattner6cefb772008-01-05 22:25:12 +000088/// 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//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000144// PatternToMatch implementation
145//
146
147/// getPredicateCheck - Return a single string containing all of this
148/// pattern's predicates concatenated with "&&" operators.
149///
150std::string PatternToMatch::getPredicateCheck() const {
151 std::string PredicateCheck;
152 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
153 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
154 Record *Def = Pred->getDef();
155 if (!Def->isSubClassOf("Predicate")) {
156#ifndef NDEBUG
157 Def->dump();
158#endif
159 assert(0 && "Unknown predicate type!");
160 }
161 if (!PredicateCheck.empty())
162 PredicateCheck += " && ";
163 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
164 }
165 }
166
167 return PredicateCheck;
168}
169
170//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000171// SDTypeConstraint implementation
172//
173
174SDTypeConstraint::SDTypeConstraint(Record *R) {
175 OperandNo = R->getValueAsInt("OperandNum");
176
177 if (R->isSubClassOf("SDTCisVT")) {
178 ConstraintType = SDTCisVT;
179 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
180 } else if (R->isSubClassOf("SDTCisPtrTy")) {
181 ConstraintType = SDTCisPtrTy;
182 } else if (R->isSubClassOf("SDTCisInt")) {
183 ConstraintType = SDTCisInt;
184 } else if (R->isSubClassOf("SDTCisFP")) {
185 ConstraintType = SDTCisFP;
186 } else if (R->isSubClassOf("SDTCisSameAs")) {
187 ConstraintType = SDTCisSameAs;
188 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
189 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
190 ConstraintType = SDTCisVTSmallerThanOp;
191 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
192 R->getValueAsInt("OtherOperandNum");
193 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
194 ConstraintType = SDTCisOpSmallerThanOp;
195 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
196 R->getValueAsInt("BigOperandNum");
197 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
198 ConstraintType = SDTCisIntVectorOfSameSize;
199 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
200 R->getValueAsInt("OtherOpNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000201 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
202 ConstraintType = SDTCisEltOfVec;
203 x.SDTCisEltOfVec_Info.OtherOperandNum =
204 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000205 } else {
206 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
207 exit(1);
208 }
209}
210
211/// getOperandNum - Return the node corresponding to operand #OpNo in tree
212/// N, which has NumResults results.
213TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
214 TreePatternNode *N,
215 unsigned NumResults) const {
216 assert(NumResults <= 1 &&
217 "We only work with nodes with zero or one result so far!");
218
219 if (OpNo >= (NumResults + N->getNumChildren())) {
220 cerr << "Invalid operand number " << OpNo << " ";
221 N->dump();
222 cerr << '\n';
223 exit(1);
224 }
225
226 if (OpNo < NumResults)
227 return N; // FIXME: need value #
228 else
229 return N->getChild(OpNo-NumResults);
230}
231
232/// ApplyTypeConstraint - Given a node in a pattern, apply this type
233/// constraint to the nodes operands. This returns true if it makes a
234/// change, false otherwise. If a type contradiction is found, throw an
235/// exception.
236bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
237 const SDNodeInfo &NodeInfo,
238 TreePattern &TP) const {
239 unsigned NumResults = NodeInfo.getNumResults();
240 assert(NumResults <= 1 &&
241 "We only work with nodes with zero or one result so far!");
242
243 // Check that the number of operands is sane. Negative operands -> varargs.
244 if (NodeInfo.getNumOperands() >= 0) {
245 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
246 TP.error(N->getOperator()->getName() + " node requires exactly " +
247 itostr(NodeInfo.getNumOperands()) + " operands!");
248 }
249
250 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
251
252 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
253
254 switch (ConstraintType) {
255 default: assert(0 && "Unknown constraint type!");
256 case SDTCisVT:
257 // Operand must be a particular type.
258 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
259 case SDTCisPtrTy: {
260 // Operand must be same as target pointer type.
261 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
262 }
263 case SDTCisInt: {
264 // If there is only one integer type supported, this must be it.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000265 std::vector<MVT::SimpleValueType> IntVTs =
266 FilterVTs(CGT.getLegalValueTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000267
268 // If we found exactly one supported integer type, apply it.
269 if (IntVTs.size() == 1)
270 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000271 return NodeToApply->UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000272 }
273 case SDTCisFP: {
274 // If there is only one FP type supported, this must be it.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000275 std::vector<MVT::SimpleValueType> FPVTs =
276 FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000277
278 // If we found exactly one supported FP type, apply it.
279 if (FPVTs.size() == 1)
280 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000281 return NodeToApply->UpdateNodeType(EMVT::isFP, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000282 }
283 case SDTCisSameAs: {
284 TreePatternNode *OtherNode =
285 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
286 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
287 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
288 }
289 case SDTCisVTSmallerThanOp: {
290 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
291 // have an integer type that is smaller than the VT.
292 if (!NodeToApply->isLeaf() ||
293 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
294 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
295 ->isSubClassOf("ValueType"))
296 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000297 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000298 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000299 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000300 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
301
302 TreePatternNode *OtherNode =
303 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
304
305 // It must be integer.
306 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000307 MadeChange |= OtherNode->UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000308
309 // This code only handles nodes that have one type set. Assert here so
310 // that we can change this if we ever need to deal with multiple value
311 // types at this point.
312 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
313 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
314 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
315 return false;
316 }
317 case SDTCisOpSmallerThanOp: {
318 TreePatternNode *BigOperand =
319 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
320
321 // Both operands must be integer or FP, but we don't care which.
322 bool MadeChange = false;
323
324 // This code does not currently handle nodes which have multiple types,
325 // where some types are integer, and some are fp. Assert that this is not
326 // the case.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000327 assert(!(EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
328 EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
329 !(EMVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
330 EMVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000331 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000332 if (EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
333 MadeChange |= BigOperand->UpdateNodeType(EMVT::isInt, TP);
334 else if (EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
335 MadeChange |= BigOperand->UpdateNodeType(EMVT::isFP, TP);
336 if (EMVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
337 MadeChange |= NodeToApply->UpdateNodeType(EMVT::isInt, TP);
338 else if (EMVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
339 MadeChange |= NodeToApply->UpdateNodeType(EMVT::isFP, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000340
Duncan Sands83ec4b62008-06-06 12:08:01 +0000341 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
342
343 if (EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
344 VTs = FilterVTs(VTs, isInteger);
345 } else if (EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
346 VTs = FilterVTs(VTs, isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000347 } else {
348 VTs.clear();
349 }
350
351 switch (VTs.size()) {
352 default: // Too many VT's to pick from.
353 case 0: break; // No info yet.
354 case 1:
Jim Grosbachda4231f2009-03-26 16:17:51 +0000355 // Only one VT of this flavor. Cannot ever satisfy the constraints.
Chris Lattner6cefb772008-01-05 22:25:12 +0000356 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
357 case 2:
358 // If we have exactly two possible types, the little operand must be the
359 // small one, the big operand should be the big one. Common with
360 // float/double for example.
361 assert(VTs[0] < VTs[1] && "Should be sorted!");
362 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
363 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
364 break;
365 }
366 return MadeChange;
367 }
368 case SDTCisIntVectorOfSameSize: {
369 TreePatternNode *OtherOperand =
370 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
371 N, NumResults);
372 if (OtherOperand->hasTypeSet()) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000373 if (!isVector(OtherOperand->getTypeNum(0)))
Chris Lattner6cefb772008-01-05 22:25:12 +0000374 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000375 MVT IVT = OtherOperand->getTypeNum(0);
376 unsigned NumElements = IVT.getVectorNumElements();
377 IVT = MVT::getIntVectorWithNumElements(NumElements);
378 return NodeToApply->UpdateNodeType(IVT.getSimpleVT(), TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000379 }
380 return false;
381 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000382 case SDTCisEltOfVec: {
383 TreePatternNode *OtherOperand =
384 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
385 N, NumResults);
386 if (OtherOperand->hasTypeSet()) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000387 if (!isVector(OtherOperand->getTypeNum(0)))
Nate Begemanb5af3342008-02-09 01:37:05 +0000388 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000389 MVT IVT = OtherOperand->getTypeNum(0);
390 IVT = IVT.getVectorElementType();
391 return NodeToApply->UpdateNodeType(IVT.getSimpleVT(), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000392 }
393 return false;
394 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000395 }
396 return false;
397}
398
399//===----------------------------------------------------------------------===//
400// SDNodeInfo implementation
401//
402SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
403 EnumName = R->getValueAsString("Opcode");
404 SDClassName = R->getValueAsString("SDClass");
405 Record *TypeProfile = R->getValueAsDef("TypeProfile");
406 NumResults = TypeProfile->getValueAsInt("NumResults");
407 NumOperands = TypeProfile->getValueAsInt("NumOperands");
408
409 // Parse the properties.
410 Properties = 0;
411 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
412 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
413 if (PropList[i]->getName() == "SDNPCommutative") {
414 Properties |= 1 << SDNPCommutative;
415 } else if (PropList[i]->getName() == "SDNPAssociative") {
416 Properties |= 1 << SDNPAssociative;
417 } else if (PropList[i]->getName() == "SDNPHasChain") {
418 Properties |= 1 << SDNPHasChain;
419 } else if (PropList[i]->getName() == "SDNPOutFlag") {
420 Properties |= 1 << SDNPOutFlag;
421 } else if (PropList[i]->getName() == "SDNPInFlag") {
422 Properties |= 1 << SDNPInFlag;
423 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
424 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000425 } else if (PropList[i]->getName() == "SDNPMayStore") {
426 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000427 } else if (PropList[i]->getName() == "SDNPMayLoad") {
428 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000429 } else if (PropList[i]->getName() == "SDNPSideEffect") {
430 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000431 } else if (PropList[i]->getName() == "SDNPMemOperand") {
432 Properties |= 1 << SDNPMemOperand;
Chris Lattner6cefb772008-01-05 22:25:12 +0000433 } else {
434 cerr << "Unknown SD Node property '" << PropList[i]->getName()
435 << "' on node '" << R->getName() << "'!\n";
436 exit(1);
437 }
438 }
439
440
441 // Parse the type constraints.
442 std::vector<Record*> ConstraintList =
443 TypeProfile->getValueAsListOfDefs("Constraints");
444 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
445}
446
447//===----------------------------------------------------------------------===//
448// TreePatternNode implementation
449//
450
451TreePatternNode::~TreePatternNode() {
452#if 0 // FIXME: implement refcounted tree nodes!
453 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
454 delete getChild(i);
455#endif
456}
457
458/// UpdateNodeType - Set the node type of N to VT if VT contains
459/// information. If N already contains a conflicting type, then throw an
460/// exception. This returns true if any information was updated.
461///
462bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
463 TreePattern &TP) {
464 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
465
Duncan Sands83ec4b62008-06-06 12:08:01 +0000466 if (ExtVTs[0] == EMVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
Chris Lattner6cefb772008-01-05 22:25:12 +0000467 return false;
468 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
469 setTypes(ExtVTs);
470 return true;
471 }
472
Mon P Wange3b3a722008-07-30 04:36:53 +0000473 if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000474 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny ||
475 ExtVTs[0] == EMVT::isInt)
Chris Lattner6cefb772008-01-05 22:25:12 +0000476 return false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000477 if (EMVT::isExtIntegerInVTs(ExtVTs)) {
478 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000479 if (FVTs.size()) {
480 setTypes(ExtVTs);
481 return true;
482 }
483 }
484 }
Bob Wilsone035fa52009-01-05 17:52:54 +0000485
486 if ((ExtVTs[0] == EMVT::isInt || ExtVTs[0] == MVT::iAny) &&
487 EMVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000488 assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000489 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000490 if (getExtTypes() == FVTs)
491 return false;
492 setTypes(FVTs);
493 return true;
494 }
Mon P Wange3b3a722008-07-30 04:36:53 +0000495 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
496 EMVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000497 //assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000498 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000499 if (getExtTypes() == FVTs)
500 return false;
501 if (FVTs.size()) {
502 setTypes(FVTs);
503 return true;
504 }
505 }
Bob Wilsone035fa52009-01-05 17:52:54 +0000506 if ((ExtVTs[0] == EMVT::isFP || ExtVTs[0] == MVT::fAny) &&
507 EMVT::isExtFloatingPointInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000508 assert(hasTypeSet() && "should be handled above!");
509 std::vector<unsigned char> FVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000510 FilterEVTs(getExtTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000511 if (getExtTypes() == FVTs)
512 return false;
513 setTypes(FVTs);
514 return true;
515 }
516
517 // If we know this is an int or fp type, and we are told it is a specific one,
518 // take the advice.
519 //
520 // Similarly, we should probably set the type here to the intersection of
521 // {isInt|isFP} and ExtVTs
Bob Wilsone035fa52009-01-05 17:52:54 +0000522 if (((getExtTypeNum(0) == EMVT::isInt || getExtTypeNum(0) == MVT::iAny) &&
Duncan Sands83ec4b62008-06-06 12:08:01 +0000523 EMVT::isExtIntegerInVTs(ExtVTs)) ||
Bob Wilsone035fa52009-01-05 17:52:54 +0000524 ((getExtTypeNum(0) == EMVT::isFP || getExtTypeNum(0) == MVT::fAny) &&
Duncan Sands83ec4b62008-06-06 12:08:01 +0000525 EMVT::isExtFloatingPointInVTs(ExtVTs))) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000526 setTypes(ExtVTs);
527 return true;
528 }
Mon P Wange3b3a722008-07-30 04:36:53 +0000529 if (getExtTypeNum(0) == EMVT::isInt &&
530 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000531 setTypes(ExtVTs);
532 return true;
533 }
534
535 if (isLeaf()) {
536 dump();
537 cerr << " ";
538 TP.error("Type inference contradiction found in node!");
539 } else {
540 TP.error("Type inference contradiction found in node " +
541 getOperator()->getName() + "!");
542 }
543 return true; // unreachable
544}
545
546
547void TreePatternNode::print(std::ostream &OS) const {
548 if (isLeaf()) {
549 OS << *getLeafValue();
550 } else {
551 OS << "(" << getOperator()->getName();
552 }
553
554 // FIXME: At some point we should handle printing all the value types for
555 // nodes that are multiply typed.
556 switch (getExtTypeNum(0)) {
557 case MVT::Other: OS << ":Other"; break;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000558 case EMVT::isInt: OS << ":isInt"; break;
559 case EMVT::isFP : OS << ":isFP"; break;
560 case EMVT::isUnknown: ; /*OS << ":?";*/ break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000561 case MVT::iPTR: OS << ":iPTR"; break;
Mon P Wange3b3a722008-07-30 04:36:53 +0000562 case MVT::iPTRAny: OS << ":iPTRAny"; break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000563 default: {
564 std::string VTName = llvm::getName(getTypeNum(0));
565 // Strip off MVT:: prefix if present.
566 if (VTName.substr(0,5) == "MVT::")
567 VTName = VTName.substr(5);
568 OS << ":" << VTName;
569 break;
570 }
571 }
572
573 if (!isLeaf()) {
574 if (getNumChildren() != 0) {
575 OS << " ";
576 getChild(0)->print(OS);
577 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
578 OS << ", ";
579 getChild(i)->print(OS);
580 }
581 }
582 OS << ")";
583 }
584
Dan Gohman0540e172008-10-15 06:17:21 +0000585 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
586 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000587 if (TransformFn)
588 OS << "<<X:" << TransformFn->getName() << ">>";
589 if (!getName().empty())
590 OS << ":$" << getName();
591
592}
593void TreePatternNode::dump() const {
594 print(*cerr.stream());
595}
596
Scott Michel327d0652008-03-05 17:49:05 +0000597/// isIsomorphicTo - Return true if this node is recursively
598/// isomorphic to the specified node. For this comparison, the node's
599/// entire state is considered. The assigned name is ignored, since
600/// nodes with differing names are considered isomorphic. However, if
601/// the assigned name is present in the dependent variable set, then
602/// the assigned name is considered significant and the node is
603/// isomorphic if the names match.
604bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
605 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000606 if (N == this) return true;
607 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000608 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000609 getTransformFn() != N->getTransformFn())
610 return false;
611
612 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000613 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
614 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000615 return ((DI->getDef() == NDI->getDef())
616 && (DepVars.find(getName()) == DepVars.end()
617 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000618 }
619 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000620 return getLeafValue() == N->getLeafValue();
621 }
622
623 if (N->getOperator() != getOperator() ||
624 N->getNumChildren() != getNumChildren()) return false;
625 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000626 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000627 return false;
628 return true;
629}
630
631/// clone - Make a copy of this tree and all of its children.
632///
633TreePatternNode *TreePatternNode::clone() const {
634 TreePatternNode *New;
635 if (isLeaf()) {
636 New = new TreePatternNode(getLeafValue());
637 } else {
638 std::vector<TreePatternNode*> CChildren;
639 CChildren.reserve(Children.size());
640 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
641 CChildren.push_back(getChild(i)->clone());
642 New = new TreePatternNode(getOperator(), CChildren);
643 }
644 New->setName(getName());
645 New->setTypes(getExtTypes());
Dan Gohman0540e172008-10-15 06:17:21 +0000646 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000647 New->setTransformFn(getTransformFn());
648 return New;
649}
650
651/// SubstituteFormalArguments - Replace the formal arguments in this tree
652/// with actual values specified by ArgMap.
653void TreePatternNode::
654SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
655 if (isLeaf()) return;
656
657 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
658 TreePatternNode *Child = getChild(i);
659 if (Child->isLeaf()) {
660 Init *Val = Child->getLeafValue();
661 if (dynamic_cast<DefInit*>(Val) &&
662 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
663 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000664 TreePatternNode *NewChild = ArgMap[Child->getName()];
665 assert(NewChild && "Couldn't find formal argument!");
666 assert((Child->getPredicateFns().empty() ||
667 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
668 "Non-empty child predicate clobbered!");
669 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000670 }
671 } else {
672 getChild(i)->SubstituteFormalArguments(ArgMap);
673 }
674 }
675}
676
677
678/// InlinePatternFragments - If this pattern refers to any pattern
679/// fragments, inline them into place, giving us a pattern without any
680/// PatFrag references.
681TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
682 if (isLeaf()) return this; // nothing to do.
683 Record *Op = getOperator();
684
685 if (!Op->isSubClassOf("PatFrag")) {
686 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000687 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
688 TreePatternNode *Child = getChild(i);
689 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
690
691 assert((Child->getPredicateFns().empty() ||
692 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
693 "Non-empty child predicate clobbered!");
694
695 setChild(i, NewChild);
696 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000697 return this;
698 }
699
700 // Otherwise, we found a reference to a fragment. First, look up its
701 // TreePattern record.
702 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
703
704 // Verify that we are passing the right number of operands.
705 if (Frag->getNumArgs() != Children.size())
706 TP.error("'" + Op->getName() + "' fragment requires " +
707 utostr(Frag->getNumArgs()) + " operands!");
708
709 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
710
Dan Gohman0540e172008-10-15 06:17:21 +0000711 std::string Code = Op->getValueAsCode("Predicate");
712 if (!Code.empty())
713 FragTree->addPredicateFn("Predicate_"+Op->getName());
714
Chris Lattner6cefb772008-01-05 22:25:12 +0000715 // Resolve formal arguments to their actual value.
716 if (Frag->getNumArgs()) {
717 // Compute the map of formal to actual arguments.
718 std::map<std::string, TreePatternNode*> ArgMap;
719 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
720 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
721
722 FragTree->SubstituteFormalArguments(ArgMap);
723 }
724
725 FragTree->setName(getName());
726 FragTree->UpdateNodeType(getExtTypes(), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000727
728 // Transfer in the old predicates.
729 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
730 FragTree->addPredicateFn(getPredicateFns()[i]);
731
Chris Lattner6cefb772008-01-05 22:25:12 +0000732 // Get a new copy of this fragment to stitch into here.
733 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000734
735 // The fragment we inlined could have recursive inlining that is needed. See
736 // if there are any pattern fragments in it and inline them as needed.
737 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000738}
739
740/// getImplicitType - Check to see if the specified record has an implicit
741/// type which should be applied to it. This infer the type of register
742/// references from the register file information, for example.
743///
744static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
745 TreePattern &TP) {
746 // Some common return values
Duncan Sands83ec4b62008-06-06 12:08:01 +0000747 std::vector<unsigned char> Unknown(1, EMVT::isUnknown);
Chris Lattner6cefb772008-01-05 22:25:12 +0000748 std::vector<unsigned char> Other(1, MVT::Other);
749
750 // Check to see if this is a register or a register class...
751 if (R->isSubClassOf("RegisterClass")) {
752 if (NotRegisters)
753 return Unknown;
754 const CodeGenRegisterClass &RC =
755 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
756 return ConvertVTs(RC.getValueTypes());
757 } else if (R->isSubClassOf("PatFrag")) {
758 // Pattern fragment types will be resolved when they are inlined.
759 return Unknown;
760 } else if (R->isSubClassOf("Register")) {
761 if (NotRegisters)
762 return Unknown;
763 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
764 return T.getRegisterVTs(R);
765 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
766 // Using a VTSDNode or CondCodeSDNode.
767 return Other;
768 } else if (R->isSubClassOf("ComplexPattern")) {
769 if (NotRegisters)
770 return Unknown;
771 std::vector<unsigned char>
772 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
773 return ComplexPat;
774 } else if (R->getName() == "ptr_rc") {
775 Other[0] = MVT::iPTR;
776 return Other;
777 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
778 R->getName() == "zero_reg") {
779 // Placeholder.
780 return Unknown;
781 }
782
783 TP.error("Unknown node flavor used in pattern: " + R->getName());
784 return Other;
785}
786
Chris Lattnere67bde52008-01-06 05:36:50 +0000787
788/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
789/// CodeGenIntrinsic information for it, otherwise return a null pointer.
790const CodeGenIntrinsic *TreePatternNode::
791getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
792 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
793 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
794 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
795 return 0;
796
797 unsigned IID =
798 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
799 return &CDP.getIntrinsicInfo(IID);
800}
801
Evan Cheng6bd95672008-06-16 20:29:38 +0000802/// isCommutativeIntrinsic - Return true if the node corresponds to a
803/// commutative intrinsic.
804bool
805TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
806 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
807 return Int->isCommutative;
808 return false;
809}
810
Chris Lattnere67bde52008-01-06 05:36:50 +0000811
Bob Wilson6c01ca92009-01-05 17:23:09 +0000812/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +0000813/// this node and its children in the tree. This returns true if it makes a
814/// change, false otherwise. If a type contradiction is found, throw an
815/// exception.
816bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +0000817 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +0000818 if (isLeaf()) {
819 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
820 // If it's a regclass or something else known, include the type.
821 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
822 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
823 // Int inits are always integers. :)
Duncan Sands83ec4b62008-06-06 12:08:01 +0000824 bool MadeChange = UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000825
826 if (hasTypeSet()) {
827 // At some point, it may make sense for this tree pattern to have
828 // multiple types. Assert here that it does not, so we revisit this
829 // code when appropriate.
830 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000831 MVT::SimpleValueType VT = getTypeNum(0);
Chris Lattner6cefb772008-01-05 22:25:12 +0000832 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
833 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
834
835 VT = getTypeNum(0);
Mon P Wange3b3a722008-07-30 04:36:53 +0000836 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000837 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattner6cefb772008-01-05 22:25:12 +0000838 // Make sure that the value is representable for this type.
839 if (Size < 32) {
840 int Val = (II->getValue() << (32-Size)) >> (32-Size);
Scott Michel0123b7d2008-02-15 23:05:48 +0000841 if (Val != II->getValue()) {
Bill Wendling27926af2008-02-26 10:45:29 +0000842 // If sign-extended doesn't fit, does it fit as unsigned?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000843 unsigned ValueMask;
844 unsigned UnsignedVal;
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +0000845 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
Duncan Sands83ec4b62008-06-06 12:08:01 +0000846 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +0000847
Bill Wendling27926af2008-02-26 10:45:29 +0000848 if ((ValueMask & UnsignedVal) != UnsignedVal) {
849 TP.error("Integer value '" + itostr(II->getValue())+
850 "' is out of range for type '" +
851 getEnumName(getTypeNum(0)) + "'!");
852 }
853 }
854 }
855 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000856 }
857
858 return MadeChange;
859 }
860 return false;
861 }
862
863 // special handling for set, which isn't really an SDNode.
864 if (getOperator()->getName() == "set") {
865 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
866 unsigned NC = getNumChildren();
867 bool MadeChange = false;
868 for (unsigned i = 0; i < NC-1; ++i) {
869 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
870 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
871
872 // Types of operands must match.
873 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
874 TP);
875 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
876 TP);
877 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
878 }
879 return MadeChange;
880 } else if (getOperator()->getName() == "implicit" ||
881 getOperator()->getName() == "parallel") {
882 bool MadeChange = false;
883 for (unsigned i = 0; i < getNumChildren(); ++i)
884 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
885 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
886 return MadeChange;
Dan Gohmanf8c73942009-04-13 15:38:05 +0000887 } else if (getOperator()->getName() == "COPY_TO_SUBCLASS") {
888 bool MadeChange = false;
889 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
890 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
891 MadeChange |= UpdateNodeType(getChild(1)->getTypeNum(0), TP);
892 return MadeChange;
Chris Lattnere67bde52008-01-06 05:36:50 +0000893 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000894 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000895
Chris Lattner6cefb772008-01-05 22:25:12 +0000896 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000897 unsigned NumRetVTs = Int->IS.RetVTs.size();
898 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000899
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000900 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
901 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
902
903 if (getNumChildren() != NumParamVTs + NumRetVTs)
Chris Lattnere67bde52008-01-06 05:36:50 +0000904 TP.error("Intrinsic '" + Int->Name + "' expects " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000905 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
906 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000907
908 // Apply type info to the intrinsic ID.
909 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
910
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000911 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
912 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
Chris Lattner6cefb772008-01-05 22:25:12 +0000913 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
914 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
915 }
916 return MadeChange;
917 } else if (getOperator()->isSubClassOf("SDNode")) {
918 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
919
920 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
921 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
922 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
923 // Branch, etc. do not produce results and top-level forms in instr pattern
924 // must have void types.
925 if (NI.getNumResults() == 0)
926 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
927
928 // If this is a vector_shuffle operation, apply types to the build_vector
929 // operation. The types of the integers don't matter, but this ensures they
930 // won't get checked.
931 if (getOperator()->getName() == "vector_shuffle" &&
932 getChild(2)->getOperator()->getName() == "build_vector") {
933 TreePatternNode *BV = getChild(2);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000934 const std::vector<MVT::SimpleValueType> &LegalVTs
Chris Lattner6cefb772008-01-05 22:25:12 +0000935 = CDP.getTargetInfo().getLegalValueTypes();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000936 MVT::SimpleValueType LegalIntVT = MVT::Other;
Chris Lattner6cefb772008-01-05 22:25:12 +0000937 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +0000938 if (isInteger(LegalVTs[i]) && !isVector(LegalVTs[i])) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000939 LegalIntVT = LegalVTs[i];
940 break;
941 }
942 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
943
944 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
945 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
946 }
947 return MadeChange;
948 } else if (getOperator()->isSubClassOf("Instruction")) {
949 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
950 bool MadeChange = false;
951 unsigned NumResults = Inst.getNumResults();
952
953 assert(NumResults <= 1 &&
954 "Only supports zero or one result instrs!");
955
956 CodeGenInstruction &InstInfo =
957 CDP.getTargetInfo().getInstruction(getOperator()->getName());
958 // Apply the result type to the node
959 if (NumResults == 0 || InstInfo.NumDefs == 0) {
Christopher Lamb02f69372008-03-10 04:16:09 +0000960 MadeChange = UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000961 } else {
962 Record *ResultNode = Inst.getResult(0);
963
964 if (ResultNode->getName() == "ptr_rc") {
965 std::vector<unsigned char> VT;
966 VT.push_back(MVT::iPTR);
967 MadeChange = UpdateNodeType(VT, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +0000968 } else if (ResultNode->getName() == "unknown") {
969 std::vector<unsigned char> VT;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000970 VT.push_back(EMVT::isUnknown);
Christopher Lamb5b415372008-03-11 09:33:47 +0000971 MadeChange = UpdateNodeType(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000972 } else {
973 assert(ResultNode->isSubClassOf("RegisterClass") &&
974 "Operands should be register classes!");
975
976 const CodeGenRegisterClass &RC =
977 CDP.getTargetInfo().getRegisterClass(ResultNode);
978 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
979 }
980 }
981
982 unsigned ChildNo = 0;
983 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
984 Record *OperandNode = Inst.getOperand(i);
985
986 // If the instruction expects a predicate or optional def operand, we
987 // codegen this by setting the operand to it's default value if it has a
988 // non-empty DefaultOps field.
989 if ((OperandNode->isSubClassOf("PredicateOperand") ||
990 OperandNode->isSubClassOf("OptionalDefOperand")) &&
991 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
992 continue;
993
994 // Verify that we didn't run out of provided operands.
995 if (ChildNo >= getNumChildren())
996 TP.error("Instruction '" + getOperator()->getName() +
997 "' expects more operands than were provided.");
998
Duncan Sands83ec4b62008-06-06 12:08:01 +0000999 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001000 TreePatternNode *Child = getChild(ChildNo++);
1001 if (OperandNode->isSubClassOf("RegisterClass")) {
1002 const CodeGenRegisterClass &RC =
1003 CDP.getTargetInfo().getRegisterClass(OperandNode);
1004 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1005 } else if (OperandNode->isSubClassOf("Operand")) {
1006 VT = getValueType(OperandNode->getValueAsDef("Type"));
1007 MadeChange |= Child->UpdateNodeType(VT, TP);
1008 } else if (OperandNode->getName() == "ptr_rc") {
1009 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001010 } else if (OperandNode->getName() == "unknown") {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001011 MadeChange |= Child->UpdateNodeType(EMVT::isUnknown, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001012 } else {
1013 assert(0 && "Unknown operand type!");
1014 abort();
1015 }
1016 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1017 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001018
Christopher Lamb02f69372008-03-10 04:16:09 +00001019 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001020 TP.error("Instruction '" + getOperator()->getName() +
1021 "' was provided too many operands!");
1022
1023 return MadeChange;
1024 } else {
1025 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1026
1027 // Node transforms always take one operand.
1028 if (getNumChildren() != 1)
1029 TP.error("Node transform '" + getOperator()->getName() +
1030 "' requires one operand!");
1031
1032 // If either the output or input of the xform does not have exact
1033 // type info. We assume they must be the same. Otherwise, it is perfectly
1034 // legal to transform from one type to a completely different type.
1035 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1036 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1037 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1038 return MadeChange;
1039 }
1040 return false;
1041 }
1042}
1043
1044/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1045/// RHS of a commutative operation, not the on LHS.
1046static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1047 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1048 return true;
1049 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1050 return true;
1051 return false;
1052}
1053
1054
1055/// canPatternMatch - If it is impossible for this pattern to match on this
1056/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001057/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001058/// that can never possibly work), and to prevent the pattern permuter from
1059/// generating stuff that is useless.
1060bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001061 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001062 if (isLeaf()) return true;
1063
1064 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1065 if (!getChild(i)->canPatternMatch(Reason, CDP))
1066 return false;
1067
1068 // If this is an intrinsic, handle cases that would make it not match. For
1069 // example, if an operand is required to be an immediate.
1070 if (getOperator()->isSubClassOf("Intrinsic")) {
1071 // TODO:
1072 return true;
1073 }
1074
1075 // If this node is a commutative operator, check that the LHS isn't an
1076 // immediate.
1077 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001078 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1079 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001080 // Scan all of the operands of the node and make sure that only the last one
1081 // is a constant node, unless the RHS also is.
1082 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001083 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1084 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001085 if (OnlyOnRHSOfCommutative(getChild(i))) {
1086 Reason="Immediate value must be on the RHS of commutative operators!";
1087 return false;
1088 }
1089 }
1090 }
1091
1092 return true;
1093}
1094
1095//===----------------------------------------------------------------------===//
1096// TreePattern implementation
1097//
1098
1099TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001100 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001101 isInputPattern = isInput;
1102 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1103 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1104}
1105
1106TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001107 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001108 isInputPattern = isInput;
1109 Trees.push_back(ParseTreePattern(Pat));
1110}
1111
1112TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001113 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001114 isInputPattern = isInput;
1115 Trees.push_back(Pat);
1116}
1117
1118
1119
1120void TreePattern::error(const std::string &Msg) const {
1121 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001122 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001123}
1124
1125TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1126 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1127 if (!OpDef) error("Pattern has unexpected operator type!");
1128 Record *Operator = OpDef->getDef();
1129
1130 if (Operator->isSubClassOf("ValueType")) {
1131 // If the operator is a ValueType, then this must be "type cast" of a leaf
1132 // node.
1133 if (Dag->getNumArgs() != 1)
1134 error("Type cast only takes one operand!");
1135
1136 Init *Arg = Dag->getArg(0);
1137 TreePatternNode *New;
1138 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1139 Record *R = DI->getDef();
1140 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001141 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001142 std::vector<std::pair<Init*, std::string> >()));
1143 return ParseTreePattern(Dag);
1144 }
1145 New = new TreePatternNode(DI);
1146 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1147 New = ParseTreePattern(DI);
1148 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1149 New = new TreePatternNode(II);
1150 if (!Dag->getArgName(0).empty())
1151 error("Constant int argument should not have a name!");
1152 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1153 // Turn this into an IntInit.
1154 Init *II = BI->convertInitializerTo(new IntRecTy());
1155 if (II == 0 || !dynamic_cast<IntInit*>(II))
1156 error("Bits value must be constants!");
1157
1158 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1159 if (!Dag->getArgName(0).empty())
1160 error("Constant int argument should not have a name!");
1161 } else {
1162 Arg->dump();
1163 error("Unknown leaf value for tree pattern!");
1164 return 0;
1165 }
1166
1167 // Apply the type cast.
1168 New->UpdateNodeType(getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001169 if (New->getNumChildren() == 0)
1170 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001171 return New;
1172 }
1173
1174 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001175 if (!Operator->isSubClassOf("PatFrag") &&
1176 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001177 !Operator->isSubClassOf("Instruction") &&
1178 !Operator->isSubClassOf("SDNodeXForm") &&
1179 !Operator->isSubClassOf("Intrinsic") &&
1180 Operator->getName() != "set" &&
1181 Operator->getName() != "implicit" &&
1182 Operator->getName() != "parallel")
1183 error("Unrecognized node '" + Operator->getName() + "'!");
1184
1185 // Check to see if this is something that is illegal in an input pattern.
1186 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1187 Operator->isSubClassOf("SDNodeXForm")))
1188 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1189
1190 std::vector<TreePatternNode*> Children;
1191
1192 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1193 Init *Arg = Dag->getArg(i);
1194 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1195 Children.push_back(ParseTreePattern(DI));
1196 if (Children.back()->getName().empty())
1197 Children.back()->setName(Dag->getArgName(i));
1198 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1199 Record *R = DefI->getDef();
1200 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1201 // TreePatternNode if its own.
1202 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001203 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001204 std::vector<std::pair<Init*, std::string> >()));
1205 --i; // Revisit this node...
1206 } else {
1207 TreePatternNode *Node = new TreePatternNode(DefI);
1208 Node->setName(Dag->getArgName(i));
1209 Children.push_back(Node);
1210
1211 // Input argument?
1212 if (R->getName() == "node") {
1213 if (Dag->getArgName(i).empty())
1214 error("'node' argument requires a name to match with operand list");
1215 Args.push_back(Dag->getArgName(i));
1216 }
1217 }
1218 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1219 TreePatternNode *Node = new TreePatternNode(II);
1220 if (!Dag->getArgName(i).empty())
1221 error("Constant int argument should not have a name!");
1222 Children.push_back(Node);
1223 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1224 // Turn this into an IntInit.
1225 Init *II = BI->convertInitializerTo(new IntRecTy());
1226 if (II == 0 || !dynamic_cast<IntInit*>(II))
1227 error("Bits value must be constants!");
1228
1229 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1230 if (!Dag->getArgName(i).empty())
1231 error("Constant int argument should not have a name!");
1232 Children.push_back(Node);
1233 } else {
1234 cerr << '"';
1235 Arg->dump();
1236 cerr << "\": ";
1237 error("Unknown leaf value for tree pattern!");
1238 }
1239 }
1240
1241 // If the operator is an intrinsic, then this is just syntactic sugar for for
1242 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1243 // convert the intrinsic name to a number.
1244 if (Operator->isSubClassOf("Intrinsic")) {
1245 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1246 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1247
1248 // If this intrinsic returns void, it must have side-effects and thus a
1249 // chain.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001250 if (Int.IS.RetVTs[0] == MVT::isVoid) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001251 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1252 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1253 // Has side-effects, requires chain.
1254 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1255 } else {
1256 // Otherwise, no chain.
1257 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1258 }
1259
1260 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1261 Children.insert(Children.begin(), IIDNode);
1262 }
1263
Nate Begeman7cee8172009-03-19 05:21:56 +00001264 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1265 Result->setName(Dag->getName());
1266 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001267}
1268
1269/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001270/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001271/// otherwise. Throw an exception if a type contradiction is found.
1272bool TreePattern::InferAllTypes() {
1273 bool MadeChange = true;
1274 while (MadeChange) {
1275 MadeChange = false;
1276 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1277 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1278 }
1279
1280 bool HasUnresolvedTypes = false;
1281 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1282 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1283 return !HasUnresolvedTypes;
1284}
1285
1286void TreePattern::print(std::ostream &OS) const {
1287 OS << getRecord()->getName();
1288 if (!Args.empty()) {
1289 OS << "(" << Args[0];
1290 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1291 OS << ", " << Args[i];
1292 OS << ")";
1293 }
1294 OS << ": ";
1295
1296 if (Trees.size() > 1)
1297 OS << "[\n";
1298 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1299 OS << "\t";
1300 Trees[i]->print(OS);
1301 OS << "\n";
1302 }
1303
1304 if (Trees.size() > 1)
1305 OS << "]\n";
1306}
1307
1308void TreePattern::dump() const { print(*cerr.stream()); }
1309
1310//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001311// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001312//
1313
1314// FIXME: REMOVE OSTREAM ARGUMENT
Chris Lattnerfe718932008-01-06 01:10:31 +00001315CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001316 Intrinsics = LoadIntrinsics(Records, false);
1317 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001318 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001319 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001320 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001321 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001322 ParseDefaultOperands();
1323 ParseInstructions();
1324 ParsePatterns();
1325
1326 // Generate variants. For example, commutative patterns can match
1327 // multiple ways. Add them to PatternsToMatch as well.
1328 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001329
1330 // Infer instruction flags. For example, we can detect loads,
1331 // stores, and side effects in many cases by examining an
1332 // instruction's pattern.
1333 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001334}
1335
Chris Lattnerfe718932008-01-06 01:10:31 +00001336CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001337 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1338 E = PatternFragments.end(); I != E; ++I)
1339 delete I->second;
1340}
1341
1342
Chris Lattnerfe718932008-01-06 01:10:31 +00001343Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001344 Record *N = Records.getDef(Name);
1345 if (!N || !N->isSubClassOf("SDNode")) {
1346 cerr << "Error getting SDNode '" << Name << "'!\n";
1347 exit(1);
1348 }
1349 return N;
1350}
1351
1352// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001353void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001354 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1355 while (!Nodes.empty()) {
1356 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1357 Nodes.pop_back();
1358 }
1359
Jim Grosbachda4231f2009-03-26 16:17:51 +00001360 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001361 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1362 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1363 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1364}
1365
1366/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1367/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001368void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001369 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1370 while (!Xforms.empty()) {
1371 Record *XFormNode = Xforms.back();
1372 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1373 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001374 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001375
1376 Xforms.pop_back();
1377 }
1378}
1379
Chris Lattnerfe718932008-01-06 01:10:31 +00001380void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001381 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1382 while (!AMs.empty()) {
1383 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1384 AMs.pop_back();
1385 }
1386}
1387
1388
1389/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1390/// file, building up the PatternFragments map. After we've collected them all,
1391/// inline fragments together as necessary, so that there are no references left
1392/// inside a pattern fragment to a pattern fragment.
1393///
Chris Lattnerfe718932008-01-06 01:10:31 +00001394void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001395 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1396
Chris Lattnerdc32f982008-01-05 22:43:57 +00001397 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001398 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1399 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1400 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1401 PatternFragments[Fragments[i]] = P;
1402
Chris Lattnerdc32f982008-01-05 22:43:57 +00001403 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001404 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001405 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001406
Chris Lattnerdc32f982008-01-05 22:43:57 +00001407 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001408 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1409
1410 // Parse the operands list.
1411 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1412 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1413 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001414 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001415 if (!OpsOp ||
1416 (OpsOp->getDef()->getName() != "ops" &&
1417 OpsOp->getDef()->getName() != "outs" &&
1418 OpsOp->getDef()->getName() != "ins"))
1419 P->error("Operands list should start with '(ops ... '!");
1420
1421 // Copy over the arguments.
1422 Args.clear();
1423 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1424 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1425 static_cast<DefInit*>(OpsList->getArg(j))->
1426 getDef()->getName() != "node")
1427 P->error("Operands list should all be 'node' values.");
1428 if (OpsList->getArgName(j).empty())
1429 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001430 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001431 P->error("'" + OpsList->getArgName(j) +
1432 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001433 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001434 Args.push_back(OpsList->getArgName(j));
1435 }
1436
Chris Lattnerdc32f982008-01-05 22:43:57 +00001437 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001438 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001439 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001440
Chris Lattnerdc32f982008-01-05 22:43:57 +00001441 // If there is a code init for this fragment, keep track of the fact that
1442 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001443 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001444 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001445 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001446
1447 // If there is a node transformation corresponding to this, keep track of
1448 // it.
1449 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1450 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1451 P->getOnlyTree()->setTransformFn(Transform);
1452 }
1453
Chris Lattner6cefb772008-01-05 22:25:12 +00001454 // Now that we've parsed all of the tree fragments, do a closure on them so
1455 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001456 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1457 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001458 ThePat->InlinePatternFragments();
1459
1460 // Infer as many types as possible. Don't worry about it if we don't infer
1461 // all of them, some may depend on the inputs of the pattern.
1462 try {
1463 ThePat->InferAllTypes();
1464 } catch (...) {
1465 // If this pattern fragment is not supported by this target (no types can
1466 // satisfy its constraints), just ignore it. If the bogus pattern is
1467 // actually used by instructions, the type consistency error will be
1468 // reported there.
1469 }
1470
1471 // If debugging, print out the pattern fragment result.
1472 DEBUG(ThePat->dump());
1473 }
1474}
1475
Chris Lattnerfe718932008-01-06 01:10:31 +00001476void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001477 std::vector<Record*> DefaultOps[2];
1478 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1479 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1480
1481 // Find some SDNode.
1482 assert(!SDNodes.empty() && "No SDNodes parsed?");
1483 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1484
1485 for (unsigned iter = 0; iter != 2; ++iter) {
1486 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1487 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1488
1489 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1490 // SomeSDnode so that we can parse this.
1491 std::vector<std::pair<Init*, std::string> > Ops;
1492 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1493 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1494 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001495 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001496
1497 // Create a TreePattern to parse this.
1498 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1499 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1500
1501 // Copy the operands over into a DAGDefaultOperand.
1502 DAGDefaultOperand DefaultOpInfo;
1503
1504 TreePatternNode *T = P.getTree(0);
1505 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1506 TreePatternNode *TPN = T->getChild(op);
1507 while (TPN->ApplyTypeConstraints(P, false))
1508 /* Resolve all types */;
1509
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001510 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001511 if (iter == 0)
1512 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1513 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1514 else
1515 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1516 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001517 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001518 DefaultOpInfo.DefaultOps.push_back(TPN);
1519 }
1520
1521 // Insert it into the DefaultOperands map so we can find it later.
1522 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1523 }
1524 }
1525}
1526
1527/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1528/// instruction input. Return true if this is a real use.
1529static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1530 std::map<std::string, TreePatternNode*> &InstInputs,
1531 std::vector<Record*> &InstImpInputs) {
1532 // No name -> not interesting.
1533 if (Pat->getName().empty()) {
1534 if (Pat->isLeaf()) {
1535 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1536 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1537 I->error("Input " + DI->getDef()->getName() + " must be named!");
1538 else if (DI && DI->getDef()->isSubClassOf("Register"))
1539 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001540 }
1541 return false;
1542 }
1543
1544 Record *Rec;
1545 if (Pat->isLeaf()) {
1546 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1547 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1548 Rec = DI->getDef();
1549 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001550 Rec = Pat->getOperator();
1551 }
1552
1553 // SRCVALUE nodes are ignored.
1554 if (Rec->getName() == "srcvalue")
1555 return false;
1556
1557 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1558 if (!Slot) {
1559 Slot = Pat;
1560 } else {
1561 Record *SlotRec;
1562 if (Slot->isLeaf()) {
1563 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1564 } else {
1565 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1566 SlotRec = Slot->getOperator();
1567 }
1568
1569 // Ensure that the inputs agree if we've already seen this input.
1570 if (Rec != SlotRec)
1571 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1572 if (Slot->getExtTypes() != Pat->getExtTypes())
1573 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1574 }
1575 return true;
1576}
1577
1578/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1579/// part of "I", the instruction), computing the set of inputs and outputs of
1580/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001581void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001582FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1583 std::map<std::string, TreePatternNode*> &InstInputs,
1584 std::map<std::string, TreePatternNode*>&InstResults,
1585 std::vector<Record*> &InstImpInputs,
1586 std::vector<Record*> &InstImpResults) {
1587 if (Pat->isLeaf()) {
1588 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1589 if (!isUse && Pat->getTransformFn())
1590 I->error("Cannot specify a transform function for a non-input value!");
1591 return;
1592 } else if (Pat->getOperator()->getName() == "implicit") {
1593 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1594 TreePatternNode *Dest = Pat->getChild(i);
1595 if (!Dest->isLeaf())
1596 I->error("implicitly defined value should be a register!");
1597
1598 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1599 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1600 I->error("implicitly defined value should be a register!");
1601 InstImpResults.push_back(Val->getDef());
1602 }
1603 return;
1604 } else if (Pat->getOperator()->getName() != "set") {
1605 // If this is not a set, verify that the children nodes are not void typed,
1606 // and recurse.
1607 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1608 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1609 I->error("Cannot have void nodes inside of patterns!");
1610 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1611 InstImpInputs, InstImpResults);
1612 }
1613
1614 // If this is a non-leaf node with no children, treat it basically as if
1615 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00001616 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00001617
1618 if (!isUse && Pat->getTransformFn())
1619 I->error("Cannot specify a transform function for a non-input value!");
1620 return;
1621 }
1622
1623 // Otherwise, this is a set, validate and collect instruction results.
1624 if (Pat->getNumChildren() == 0)
1625 I->error("set requires operands!");
1626
1627 if (Pat->getTransformFn())
1628 I->error("Cannot specify a transform function on a set node!");
1629
1630 // Check the set destinations.
1631 unsigned NumDests = Pat->getNumChildren()-1;
1632 for (unsigned i = 0; i != NumDests; ++i) {
1633 TreePatternNode *Dest = Pat->getChild(i);
1634 if (!Dest->isLeaf())
1635 I->error("set destination should be a register!");
1636
1637 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1638 if (!Val)
1639 I->error("set destination should be a register!");
1640
1641 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1642 Val->getDef()->getName() == "ptr_rc") {
1643 if (Dest->getName().empty())
1644 I->error("set destination must have a name!");
1645 if (InstResults.count(Dest->getName()))
1646 I->error("cannot set '" + Dest->getName() +"' multiple times");
1647 InstResults[Dest->getName()] = Dest;
1648 } else if (Val->getDef()->isSubClassOf("Register")) {
1649 InstImpResults.push_back(Val->getDef());
1650 } else {
1651 I->error("set destination should be a register!");
1652 }
1653 }
1654
1655 // Verify and collect info from the computation.
1656 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1657 InstInputs, InstResults,
1658 InstImpInputs, InstImpResults);
1659}
1660
Dan Gohmanee4fa192008-04-03 00:02:49 +00001661//===----------------------------------------------------------------------===//
1662// Instruction Analysis
1663//===----------------------------------------------------------------------===//
1664
1665class InstAnalyzer {
1666 const CodeGenDAGPatterns &CDP;
1667 bool &mayStore;
1668 bool &mayLoad;
1669 bool &HasSideEffects;
1670public:
1671 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1672 bool &maystore, bool &mayload, bool &hse)
1673 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1674 }
1675
1676 /// Analyze - Analyze the specified instruction, returning true if the
1677 /// instruction had a pattern.
1678 bool Analyze(Record *InstRecord) {
1679 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1680 if (Pattern == 0) {
1681 HasSideEffects = 1;
1682 return false; // No pattern.
1683 }
1684
1685 // FIXME: Assume only the first tree is the pattern. The others are clobber
1686 // nodes.
1687 AnalyzeNode(Pattern->getTree(0));
1688 return true;
1689 }
1690
1691private:
1692 void AnalyzeNode(const TreePatternNode *N) {
1693 if (N->isLeaf()) {
1694 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1695 Record *LeafRec = DI->getDef();
1696 // Handle ComplexPattern leaves.
1697 if (LeafRec->isSubClassOf("ComplexPattern")) {
1698 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1699 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1700 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1701 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1702 }
1703 }
1704 return;
1705 }
1706
1707 // Analyze children.
1708 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1709 AnalyzeNode(N->getChild(i));
1710
1711 // Ignore set nodes, which are not SDNodes.
1712 if (N->getOperator()->getName() == "set")
1713 return;
1714
1715 // Get information about the SDNode for the operator.
1716 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1717
1718 // Notice properties of the node.
1719 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1720 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1721 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1722
1723 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1724 // If this is an intrinsic, analyze it.
1725 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1726 mayLoad = true;// These may load memory.
1727
1728 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1729 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1730
1731 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1732 // WriteMem intrinsics can have other strange effects.
1733 HasSideEffects = true;
1734 }
1735 }
1736
1737};
1738
1739static void InferFromPattern(const CodeGenInstruction &Inst,
1740 bool &MayStore, bool &MayLoad,
1741 bool &HasSideEffects,
1742 const CodeGenDAGPatterns &CDP) {
1743 MayStore = MayLoad = HasSideEffects = false;
1744
1745 bool HadPattern =
1746 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1747
1748 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1749 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1750 // If we decided that this is a store from the pattern, then the .td file
1751 // entry is redundant.
1752 if (MayStore)
1753 fprintf(stderr,
1754 "Warning: mayStore flag explicitly set on instruction '%s'"
1755 " but flag already inferred from pattern.\n",
1756 Inst.TheDef->getName().c_str());
1757 MayStore = true;
1758 }
1759
1760 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1761 // If we decided that this is a load from the pattern, then the .td file
1762 // entry is redundant.
1763 if (MayLoad)
1764 fprintf(stderr,
1765 "Warning: mayLoad flag explicitly set on instruction '%s'"
1766 " but flag already inferred from pattern.\n",
1767 Inst.TheDef->getName().c_str());
1768 MayLoad = true;
1769 }
1770
1771 if (Inst.neverHasSideEffects) {
1772 if (HadPattern)
1773 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1774 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1775 HasSideEffects = false;
1776 }
1777
1778 if (Inst.hasSideEffects) {
1779 if (HasSideEffects)
1780 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1781 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1782 HasSideEffects = true;
1783 }
1784}
1785
Chris Lattner6cefb772008-01-05 22:25:12 +00001786/// ParseInstructions - Parse all of the instructions, inlining and resolving
1787/// any fragments involved. This populates the Instructions list with fully
1788/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001789void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001790 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1791
1792 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1793 ListInit *LI = 0;
1794
1795 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1796 LI = Instrs[i]->getValueAsListInit("Pattern");
1797
1798 // If there is no pattern, only collect minimal information about the
1799 // instruction for its operand list. We have to assume that there is one
1800 // result, as we have no detailed info.
1801 if (!LI || LI->getSize() == 0) {
1802 std::vector<Record*> Results;
1803 std::vector<Record*> Operands;
1804
1805 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1806
1807 if (InstInfo.OperandList.size() != 0) {
1808 if (InstInfo.NumDefs == 0) {
1809 // These produce no results
1810 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1811 Operands.push_back(InstInfo.OperandList[j].Rec);
1812 } else {
1813 // Assume the first operand is the result.
1814 Results.push_back(InstInfo.OperandList[0].Rec);
1815
1816 // The rest are inputs.
1817 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1818 Operands.push_back(InstInfo.OperandList[j].Rec);
1819 }
1820 }
1821
1822 // Create and insert the instruction.
1823 std::vector<Record*> ImpResults;
1824 std::vector<Record*> ImpOperands;
1825 Instructions.insert(std::make_pair(Instrs[i],
1826 DAGInstruction(0, Results, Operands, ImpResults,
1827 ImpOperands)));
1828 continue; // no pattern.
1829 }
1830
1831 // Parse the instruction.
1832 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1833 // Inline pattern fragments into it.
1834 I->InlinePatternFragments();
1835
1836 // Infer as many types as possible. If we cannot infer all of them, we can
1837 // never do anything with this instruction pattern: report it to the user.
1838 if (!I->InferAllTypes())
1839 I->error("Could not infer all types in pattern!");
1840
1841 // InstInputs - Keep track of all of the inputs of the instruction, along
1842 // with the record they are declared as.
1843 std::map<std::string, TreePatternNode*> InstInputs;
1844
1845 // InstResults - Keep track of all the virtual registers that are 'set'
1846 // in the instruction, including what reg class they are.
1847 std::map<std::string, TreePatternNode*> InstResults;
1848
1849 std::vector<Record*> InstImpInputs;
1850 std::vector<Record*> InstImpResults;
1851
1852 // Verify that the top-level forms in the instruction are of void type, and
1853 // fill in the InstResults map.
1854 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1855 TreePatternNode *Pat = I->getTree(j);
1856 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1857 I->error("Top-level forms in instruction pattern should have"
1858 " void types");
1859
1860 // Find inputs and outputs, and verify the structure of the uses/defs.
1861 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1862 InstImpInputs, InstImpResults);
1863 }
1864
1865 // Now that we have inputs and outputs of the pattern, inspect the operands
1866 // list for the instruction. This determines the order that operands are
1867 // added to the machine instruction the node corresponds to.
1868 unsigned NumResults = InstResults.size();
1869
1870 // Parse the operands list from the (ops) list, validating it.
1871 assert(I->getArgList().empty() && "Args list should still be empty here!");
1872 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1873
1874 // Check that all of the results occur first in the list.
1875 std::vector<Record*> Results;
1876 TreePatternNode *Res0Node = NULL;
1877 for (unsigned i = 0; i != NumResults; ++i) {
1878 if (i == CGI.OperandList.size())
1879 I->error("'" + InstResults.begin()->first +
1880 "' set but does not appear in operand list!");
1881 const std::string &OpName = CGI.OperandList[i].Name;
1882
1883 // Check that it exists in InstResults.
1884 TreePatternNode *RNode = InstResults[OpName];
1885 if (RNode == 0)
1886 I->error("Operand $" + OpName + " does not exist in operand list!");
1887
1888 if (i == 0)
1889 Res0Node = RNode;
1890 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1891 if (R == 0)
1892 I->error("Operand $" + OpName + " should be a set destination: all "
1893 "outputs must occur before inputs in operand list!");
1894
1895 if (CGI.OperandList[i].Rec != R)
1896 I->error("Operand $" + OpName + " class mismatch!");
1897
1898 // Remember the return type.
1899 Results.push_back(CGI.OperandList[i].Rec);
1900
1901 // Okay, this one checks out.
1902 InstResults.erase(OpName);
1903 }
1904
1905 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1906 // the copy while we're checking the inputs.
1907 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1908
1909 std::vector<TreePatternNode*> ResultNodeOperands;
1910 std::vector<Record*> Operands;
1911 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1912 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1913 const std::string &OpName = Op.Name;
1914 if (OpName.empty())
1915 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1916
1917 if (!InstInputsCheck.count(OpName)) {
1918 // If this is an predicate operand or optional def operand with an
1919 // DefaultOps set filled in, we can ignore this. When we codegen it,
1920 // we will do so as always executed.
1921 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1922 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1923 // Does it have a non-empty DefaultOps field? If so, ignore this
1924 // operand.
1925 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1926 continue;
1927 }
1928 I->error("Operand $" + OpName +
1929 " does not appear in the instruction pattern");
1930 }
1931 TreePatternNode *InVal = InstInputsCheck[OpName];
1932 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1933
1934 if (InVal->isLeaf() &&
1935 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1936 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1937 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1938 I->error("Operand $" + OpName + "'s register class disagrees"
1939 " between the operand and pattern");
1940 }
1941 Operands.push_back(Op.Rec);
1942
1943 // Construct the result for the dest-pattern operand list.
1944 TreePatternNode *OpNode = InVal->clone();
1945
1946 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00001947 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001948
1949 // Promote the xform function to be an explicit node if set.
1950 if (Record *Xform = OpNode->getTransformFn()) {
1951 OpNode->setTransformFn(0);
1952 std::vector<TreePatternNode*> Children;
1953 Children.push_back(OpNode);
1954 OpNode = new TreePatternNode(Xform, Children);
1955 }
1956
1957 ResultNodeOperands.push_back(OpNode);
1958 }
1959
1960 if (!InstInputsCheck.empty())
1961 I->error("Input operand $" + InstInputsCheck.begin()->first +
1962 " occurs in pattern but not in operands list!");
1963
1964 TreePatternNode *ResultPattern =
1965 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1966 // Copy fully inferred output node type to instruction result pattern.
1967 if (NumResults > 0)
1968 ResultPattern->setTypes(Res0Node->getExtTypes());
1969
1970 // Create and insert the instruction.
1971 // FIXME: InstImpResults and InstImpInputs should not be part of
1972 // DAGInstruction.
1973 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1974 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1975
1976 // Use a temporary tree pattern to infer all types and make sure that the
1977 // constructed result is correct. This depends on the instruction already
1978 // being inserted into the Instructions map.
1979 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1980 Temp.InferAllTypes();
1981
1982 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1983 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1984
1985 DEBUG(I->dump());
1986 }
1987
1988 // If we can, convert the instructions to be patterns that are matched!
1989 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1990 E = Instructions.end(); II != E; ++II) {
1991 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00001992 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00001993 if (I == 0) continue; // No pattern.
1994
1995 // FIXME: Assume only the first tree is the pattern. The others are clobber
1996 // nodes.
1997 TreePatternNode *Pattern = I->getTree(0);
1998 TreePatternNode *SrcPattern;
1999 if (Pattern->getOperator()->getName() == "set") {
2000 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2001 } else{
2002 // Not a set (store or something?)
2003 SrcPattern = Pattern;
2004 }
2005
2006 std::string Reason;
2007 if (!SrcPattern->canPatternMatch(Reason, *this))
2008 I->error("Instruction can never match: " + Reason);
2009
2010 Record *Instr = II->first;
2011 TreePatternNode *DstPattern = TheInst.getResultPattern();
2012 PatternsToMatch.
2013 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
2014 SrcPattern, DstPattern, TheInst.getImpResults(),
2015 Instr->getValueAsInt("AddedComplexity")));
2016 }
2017}
2018
Dan Gohmanee4fa192008-04-03 00:02:49 +00002019
2020void CodeGenDAGPatterns::InferInstructionFlags() {
2021 std::map<std::string, CodeGenInstruction> &InstrDescs =
2022 Target.getInstructions();
2023 for (std::map<std::string, CodeGenInstruction>::iterator
2024 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2025 CodeGenInstruction &InstInfo = II->second;
2026 // Determine properties of the instruction from its pattern.
2027 bool MayStore, MayLoad, HasSideEffects;
2028 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2029 InstInfo.mayStore = MayStore;
2030 InstInfo.mayLoad = MayLoad;
2031 InstInfo.hasSideEffects = HasSideEffects;
2032 }
2033}
2034
Chris Lattnerfe718932008-01-06 01:10:31 +00002035void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002036 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2037
2038 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2039 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2040 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2041 Record *Operator = OpDef->getDef();
2042 TreePattern *Pattern;
2043 if (Operator->getName() != "parallel")
2044 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2045 else {
2046 std::vector<Init*> Values;
2047 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
2048 Values.push_back(Tree->getArg(j));
2049 ListInit *LI = new ListInit(Values);
2050 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2051 }
2052
2053 // Inline pattern fragments into it.
2054 Pattern->InlinePatternFragments();
2055
2056 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2057 if (LI->getSize() == 0) continue; // no pattern.
2058
2059 // Parse the instruction.
2060 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2061
2062 // Inline pattern fragments into it.
2063 Result->InlinePatternFragments();
2064
2065 if (Result->getNumTrees() != 1)
2066 Result->error("Cannot handle instructions producing instructions "
2067 "with temporaries yet!");
2068
2069 bool IterateInference;
2070 bool InferredAllPatternTypes, InferredAllResultTypes;
2071 do {
2072 // Infer as many types as possible. If we cannot infer all of them, we
2073 // can never do anything with this pattern: report it to the user.
2074 InferredAllPatternTypes = Pattern->InferAllTypes();
2075
2076 // Infer as many types as possible. If we cannot infer all of them, we
2077 // can never do anything with this pattern: report it to the user.
2078 InferredAllResultTypes = Result->InferAllTypes();
2079
2080 // Apply the type of the result to the source pattern. This helps us
2081 // resolve cases where the input type is known to be a pointer type (which
2082 // is considered resolved), but the result knows it needs to be 32- or
2083 // 64-bits. Infer the other way for good measure.
2084 IterateInference = Pattern->getTree(0)->
2085 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2086 IterateInference |= Result->getTree(0)->
2087 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2088 } while (IterateInference);
2089
2090 // Verify that we inferred enough types that we can do something with the
2091 // pattern and result. If these fire the user has to add type casts.
2092 if (!InferredAllPatternTypes)
2093 Pattern->error("Could not infer all types in pattern!");
2094 if (!InferredAllResultTypes)
2095 Result->error("Could not infer all types in pattern result!");
2096
2097 // Validate that the input pattern is correct.
2098 std::map<std::string, TreePatternNode*> InstInputs;
2099 std::map<std::string, TreePatternNode*> InstResults;
2100 std::vector<Record*> InstImpInputs;
2101 std::vector<Record*> InstImpResults;
2102 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2103 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2104 InstInputs, InstResults,
2105 InstImpInputs, InstImpResults);
2106
2107 // Promote the xform function to be an explicit node if set.
2108 TreePatternNode *DstPattern = Result->getOnlyTree();
2109 std::vector<TreePatternNode*> ResultNodeOperands;
2110 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2111 TreePatternNode *OpNode = DstPattern->getChild(ii);
2112 if (Record *Xform = OpNode->getTransformFn()) {
2113 OpNode->setTransformFn(0);
2114 std::vector<TreePatternNode*> Children;
2115 Children.push_back(OpNode);
2116 OpNode = new TreePatternNode(Xform, Children);
2117 }
2118 ResultNodeOperands.push_back(OpNode);
2119 }
2120 DstPattern = Result->getOnlyTree();
2121 if (!DstPattern->isLeaf())
2122 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2123 ResultNodeOperands);
2124 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2125 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2126 Temp.InferAllTypes();
2127
2128 std::string Reason;
2129 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2130 Pattern->error("Pattern can never match: " + Reason);
2131
2132 PatternsToMatch.
2133 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2134 Pattern->getTree(0),
2135 Temp.getOnlyTree(), InstImpResults,
2136 Patterns[i]->getValueAsInt("AddedComplexity")));
2137 }
2138}
2139
2140/// CombineChildVariants - Given a bunch of permutations of each child of the
2141/// 'operator' node, put them together in all possible ways.
2142static void CombineChildVariants(TreePatternNode *Orig,
2143 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2144 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002145 CodeGenDAGPatterns &CDP,
2146 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002147 // Make sure that each operand has at least one variant to choose from.
2148 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2149 if (ChildVariants[i].empty())
2150 return;
2151
2152 // The end result is an all-pairs construction of the resultant pattern.
2153 std::vector<unsigned> Idxs;
2154 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002155 bool NotDone;
2156 do {
2157#ifndef NDEBUG
2158 if (DebugFlag && !Idxs.empty()) {
2159 cerr << Orig->getOperator()->getName() << ": Idxs = [ ";
2160 for (unsigned i = 0; i < Idxs.size(); ++i) {
2161 cerr << Idxs[i] << " ";
2162 }
2163 cerr << "]\n";
2164 }
2165#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002166 // Create the variant and add it to the output list.
2167 std::vector<TreePatternNode*> NewChildren;
2168 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2169 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2170 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2171
2172 // Copy over properties.
2173 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002174 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002175 R->setTransformFn(Orig->getTransformFn());
2176 R->setTypes(Orig->getExtTypes());
2177
Scott Michel327d0652008-03-05 17:49:05 +00002178 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002179 std::string ErrString;
2180 if (!R->canPatternMatch(ErrString, CDP)) {
2181 delete R;
2182 } else {
2183 bool AlreadyExists = false;
2184
2185 // Scan to see if this pattern has already been emitted. We can get
2186 // duplication due to things like commuting:
2187 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2188 // which are the same pattern. Ignore the dups.
2189 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002190 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002191 AlreadyExists = true;
2192 break;
2193 }
2194
2195 if (AlreadyExists)
2196 delete R;
2197 else
2198 OutVariants.push_back(R);
2199 }
2200
Scott Michel327d0652008-03-05 17:49:05 +00002201 // Increment indices to the next permutation by incrementing the
2202 // indicies from last index backward, e.g., generate the sequence
2203 // [0, 0], [0, 1], [1, 0], [1, 1].
2204 int IdxsIdx;
2205 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2206 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2207 Idxs[IdxsIdx] = 0;
2208 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002209 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002210 }
Scott Michel327d0652008-03-05 17:49:05 +00002211 NotDone = (IdxsIdx >= 0);
2212 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002213}
2214
2215/// CombineChildVariants - A helper function for binary operators.
2216///
2217static void CombineChildVariants(TreePatternNode *Orig,
2218 const std::vector<TreePatternNode*> &LHS,
2219 const std::vector<TreePatternNode*> &RHS,
2220 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002221 CodeGenDAGPatterns &CDP,
2222 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002223 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2224 ChildVariants.push_back(LHS);
2225 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002226 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002227}
2228
2229
2230static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2231 std::vector<TreePatternNode *> &Children) {
2232 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2233 Record *Operator = N->getOperator();
2234
2235 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002236 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002237 N->getTransformFn()) {
2238 Children.push_back(N);
2239 return;
2240 }
2241
2242 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2243 Children.push_back(N->getChild(0));
2244 else
2245 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2246
2247 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2248 Children.push_back(N->getChild(1));
2249 else
2250 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2251}
2252
2253/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2254/// the (potentially recursive) pattern by using algebraic laws.
2255///
2256static void GenerateVariantsOf(TreePatternNode *N,
2257 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002258 CodeGenDAGPatterns &CDP,
2259 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002260 // We cannot permute leaves.
2261 if (N->isLeaf()) {
2262 OutVariants.push_back(N);
2263 return;
2264 }
2265
2266 // Look up interesting info about the node.
2267 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2268
Jim Grosbachda4231f2009-03-26 16:17:51 +00002269 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002270 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002271 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002272 std::vector<TreePatternNode*> MaximalChildren;
2273 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2274
2275 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2276 // permutations.
2277 if (MaximalChildren.size() == 3) {
2278 // Find the variants of all of our maximal children.
2279 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002280 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2281 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2282 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002283
2284 // There are only two ways we can permute the tree:
2285 // (A op B) op C and A op (B op C)
2286 // Within these forms, we can also permute A/B/C.
2287
2288 // Generate legal pair permutations of A/B/C.
2289 std::vector<TreePatternNode*> ABVariants;
2290 std::vector<TreePatternNode*> BAVariants;
2291 std::vector<TreePatternNode*> ACVariants;
2292 std::vector<TreePatternNode*> CAVariants;
2293 std::vector<TreePatternNode*> BCVariants;
2294 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002295 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2296 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2297 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2298 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2299 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2300 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002301
2302 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002303 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2304 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2305 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2306 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2307 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2308 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002309
2310 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002311 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2312 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2313 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2314 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2315 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2316 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002317 return;
2318 }
2319 }
2320
2321 // Compute permutations of all children.
2322 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2323 ChildVariants.resize(N->getNumChildren());
2324 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002325 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002326
2327 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002328 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002329
2330 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002331 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2332 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2333 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2334 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002335 // Don't count children which are actually register references.
2336 unsigned NC = 0;
2337 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2338 TreePatternNode *Child = N->getChild(i);
2339 if (Child->isLeaf())
2340 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2341 Record *RR = DI->getDef();
2342 if (RR->isSubClassOf("Register"))
2343 continue;
2344 }
2345 NC++;
2346 }
2347 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002348 if (isCommIntrinsic) {
2349 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2350 // operands are the commutative operands, and there might be more operands
2351 // after those.
2352 assert(NC >= 3 &&
2353 "Commutative intrinsic should have at least 3 childrean!");
2354 std::vector<std::vector<TreePatternNode*> > Variants;
2355 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2356 Variants.push_back(ChildVariants[2]);
2357 Variants.push_back(ChildVariants[1]);
2358 for (unsigned i = 3; i != NC; ++i)
2359 Variants.push_back(ChildVariants[i]);
2360 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2361 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002362 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002363 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002364 }
2365}
2366
2367
2368// GenerateVariants - Generate variants. For example, commutative patterns can
2369// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002370void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002371 DOUT << "Generating instruction variants.\n";
2372
2373 // Loop over all of the patterns we've collected, checking to see if we can
2374 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002375 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002376 // the .td file having to contain tons of variants of instructions.
2377 //
2378 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2379 // intentionally do not reconsider these. Any variants of added patterns have
2380 // already been added.
2381 //
2382 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002383 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002384 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002385 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2386 DOUT << "Dependent/multiply used variables: ";
2387 DEBUG(DumpDepVars(DepVars));
2388 DOUT << "\n";
2389 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002390
2391 assert(!Variants.empty() && "Must create at least original variant!");
2392 Variants.erase(Variants.begin()); // Remove the original pattern.
2393
2394 if (Variants.empty()) // No variants for this pattern.
2395 continue;
2396
2397 DOUT << "FOUND VARIANTS OF: ";
2398 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2399 DOUT << "\n";
2400
2401 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2402 TreePatternNode *Variant = Variants[v];
2403
2404 DOUT << " VAR#" << v << ": ";
2405 DEBUG(Variant->dump());
2406 DOUT << "\n";
2407
2408 // Scan to see if an instruction or explicit pattern already matches this.
2409 bool AlreadyExists = false;
2410 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2411 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002412 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002413 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2414 AlreadyExists = true;
2415 break;
2416 }
2417 }
2418 // If we already have it, ignore the variant.
2419 if (AlreadyExists) continue;
2420
2421 // Otherwise, add it to the list of patterns we have.
2422 PatternsToMatch.
2423 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2424 Variant, PatternsToMatch[i].getDstPattern(),
2425 PatternsToMatch[i].getDstRegs(),
2426 PatternsToMatch[i].getAddedComplexity()));
2427 }
2428
2429 DOUT << "\n";
2430 }
2431}
2432