blob: 1e595dd4744a9e68390531118a8ed310ce7a4790 [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Support/Debug.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include "llvm/Support/Streams.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000020#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000021#include <algorithm>
Chris Lattner6cefb772008-01-05 22:25:12 +000022using namespace llvm;
23
24//===----------------------------------------------------------------------===//
25// Helpers for working with extended types.
26
27/// FilterVTs - Filter a list of VT's according to a predicate.
28///
29template<typename T>
Duncan Sands83ec4b62008-06-06 12:08:01 +000030static std::vector<MVT::SimpleValueType>
31FilterVTs(const std::vector<MVT::SimpleValueType> &InVTs, T Filter) {
32 std::vector<MVT::SimpleValueType> Result;
Chris Lattner6cefb772008-01-05 22:25:12 +000033 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
34 if (Filter(InVTs[i]))
35 Result.push_back(InVTs[i]);
36 return Result;
37}
38
39template<typename T>
40static std::vector<unsigned char>
41FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +000044 if (Filter((MVT::SimpleValueType)InVTs[i]))
Chris Lattner6cefb772008-01-05 22:25:12 +000045 Result.push_back(InVTs[i]);
46 return Result;
47}
48
49static std::vector<unsigned char>
Duncan Sands83ec4b62008-06-06 12:08:01 +000050ConvertVTs(const std::vector<MVT::SimpleValueType> &InVTs) {
Chris Lattner6cefb772008-01-05 22:25:12 +000051 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
54 return Result;
55}
56
Duncan Sands83ec4b62008-06-06 12:08:01 +000057static inline bool isInteger(MVT::SimpleValueType VT) {
58 return MVT(VT).isInteger();
59}
60
61static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
62 return MVT(VT).isFloatingPoint();
63}
64
65static inline bool isVector(MVT::SimpleValueType VT) {
66 return MVT(VT).isVector();
67}
68
Chris Lattner6cefb772008-01-05 22:25:12 +000069static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
70 const std::vector<unsigned char> &RHS) {
71 if (LHS.size() > RHS.size()) return false;
72 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
73 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
74 return false;
75 return true;
76}
77
78/// isExtIntegerVT - Return true if the specified extended value type vector
79/// contains isInt or an integer value type.
80namespace llvm {
Duncan Sands83ec4b62008-06-06 12:08:01 +000081namespace EMVT {
Chris Lattner6cefb772008-01-05 22:25:12 +000082bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
83 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
84 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
85}
86
87/// isExtFloatingPointVT - Return true if the specified extended value type
88/// vector contains isFP or a FP value type.
89bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
90 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
91 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
92}
Duncan Sands83ec4b62008-06-06 12:08:01 +000093} // end namespace EMVT.
Chris Lattner6cefb772008-01-05 22:25:12 +000094} // end namespace llvm.
95
Scott Michel327d0652008-03-05 17:49:05 +000096
97/// Dependent variable map for CodeGenDAGPattern variant generation
98typedef std::map<std::string, int> DepVarMap;
99
100/// Const iterator shorthand for DepVarMap
101typedef DepVarMap::const_iterator DepVarMap_citer;
102
103namespace {
104void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
105 if (N->isLeaf()) {
106 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
107 DepMap[N->getName()]++;
108 }
109 } else {
110 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
111 FindDepVarsOf(N->getChild(i), DepMap);
112 }
113}
114
115//! Find dependent variables within child patterns
116/*!
117 */
118void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
119 DepVarMap depcounts;
120 FindDepVarsOf(N, depcounts);
121 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
122 if (i->second > 1) { // std::pair<std::string, int>
123 DepVars.insert(i->first);
124 }
125 }
126}
127
128//! Dump the dependent variable set:
129void DumpDepVars(MultipleUseVarSet &DepVars) {
130 if (DepVars.empty()) {
131 DOUT << "<empty set>";
132 } else {
133 DOUT << "[ ";
134 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
135 i != e; ++i) {
136 DOUT << (*i) << " ";
137 }
138 DOUT << "]";
139 }
140}
141}
142
Chris Lattner6cefb772008-01-05 22:25:12 +0000143//===----------------------------------------------------------------------===//
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:
355 // Only one VT of this flavor. Cannot ever satisify the constraints.
356 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) {
474 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny || ExtVTs[0] == EMVT::isInt)
Chris Lattner6cefb772008-01-05 22:25:12 +0000475 return false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000476 if (EMVT::isExtIntegerInVTs(ExtVTs)) {
477 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000478 if (FVTs.size()) {
479 setTypes(ExtVTs);
480 return true;
481 }
482 }
483 }
484
Duncan Sands83ec4b62008-06-06 12:08:01 +0000485 if (ExtVTs[0] == EMVT::isInt && EMVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000486 assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000487 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000488 if (getExtTypes() == FVTs)
489 return false;
490 setTypes(FVTs);
491 return true;
492 }
Mon P Wange3b3a722008-07-30 04:36:53 +0000493 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
494 EMVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000495 //assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000496 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000497 if (getExtTypes() == FVTs)
498 return false;
499 if (FVTs.size()) {
500 setTypes(FVTs);
501 return true;
502 }
503 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000504 if (ExtVTs[0] == EMVT::isFP && EMVT::isExtFloatingPointInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000505 assert(hasTypeSet() && "should be handled above!");
506 std::vector<unsigned char> FVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000507 FilterEVTs(getExtTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000508 if (getExtTypes() == FVTs)
509 return false;
510 setTypes(FVTs);
511 return true;
512 }
513
514 // If we know this is an int or fp type, and we are told it is a specific one,
515 // take the advice.
516 //
517 // Similarly, we should probably set the type here to the intersection of
518 // {isInt|isFP} and ExtVTs
Duncan Sands83ec4b62008-06-06 12:08:01 +0000519 if ((getExtTypeNum(0) == EMVT::isInt &&
520 EMVT::isExtIntegerInVTs(ExtVTs)) ||
521 (getExtTypeNum(0) == EMVT::isFP &&
522 EMVT::isExtFloatingPointInVTs(ExtVTs))) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000523 setTypes(ExtVTs);
524 return true;
525 }
Mon P Wange3b3a722008-07-30 04:36:53 +0000526 if (getExtTypeNum(0) == EMVT::isInt &&
527 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000528 setTypes(ExtVTs);
529 return true;
530 }
531
532 if (isLeaf()) {
533 dump();
534 cerr << " ";
535 TP.error("Type inference contradiction found in node!");
536 } else {
537 TP.error("Type inference contradiction found in node " +
538 getOperator()->getName() + "!");
539 }
540 return true; // unreachable
541}
542
543
544void TreePatternNode::print(std::ostream &OS) const {
545 if (isLeaf()) {
546 OS << *getLeafValue();
547 } else {
548 OS << "(" << getOperator()->getName();
549 }
550
551 // FIXME: At some point we should handle printing all the value types for
552 // nodes that are multiply typed.
553 switch (getExtTypeNum(0)) {
554 case MVT::Other: OS << ":Other"; break;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000555 case EMVT::isInt: OS << ":isInt"; break;
556 case EMVT::isFP : OS << ":isFP"; break;
557 case EMVT::isUnknown: ; /*OS << ":?";*/ break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000558 case MVT::iPTR: OS << ":iPTR"; break;
Mon P Wange3b3a722008-07-30 04:36:53 +0000559 case MVT::iPTRAny: OS << ":iPTRAny"; break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000560 default: {
561 std::string VTName = llvm::getName(getTypeNum(0));
562 // Strip off MVT:: prefix if present.
563 if (VTName.substr(0,5) == "MVT::")
564 VTName = VTName.substr(5);
565 OS << ":" << VTName;
566 break;
567 }
568 }
569
570 if (!isLeaf()) {
571 if (getNumChildren() != 0) {
572 OS << " ";
573 getChild(0)->print(OS);
574 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
575 OS << ", ";
576 getChild(i)->print(OS);
577 }
578 }
579 OS << ")";
580 }
581
582 if (!PredicateFn.empty())
583 OS << "<<P:" << PredicateFn << ">>";
584 if (TransformFn)
585 OS << "<<X:" << TransformFn->getName() << ">>";
586 if (!getName().empty())
587 OS << ":$" << getName();
588
589}
590void TreePatternNode::dump() const {
591 print(*cerr.stream());
592}
593
Scott Michel327d0652008-03-05 17:49:05 +0000594/// isIsomorphicTo - Return true if this node is recursively
595/// isomorphic to the specified node. For this comparison, the node's
596/// entire state is considered. The assigned name is ignored, since
597/// nodes with differing names are considered isomorphic. However, if
598/// the assigned name is present in the dependent variable set, then
599/// the assigned name is considered significant and the node is
600/// isomorphic if the names match.
601bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
602 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000603 if (N == this) return true;
604 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
605 getPredicateFn() != N->getPredicateFn() ||
606 getTransformFn() != N->getTransformFn())
607 return false;
608
609 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000610 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
611 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000612 return ((DI->getDef() == NDI->getDef())
613 && (DepVars.find(getName()) == DepVars.end()
614 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000615 }
616 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000617 return getLeafValue() == N->getLeafValue();
618 }
619
620 if (N->getOperator() != getOperator() ||
621 N->getNumChildren() != getNumChildren()) return false;
622 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000623 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000624 return false;
625 return true;
626}
627
628/// clone - Make a copy of this tree and all of its children.
629///
630TreePatternNode *TreePatternNode::clone() const {
631 TreePatternNode *New;
632 if (isLeaf()) {
633 New = new TreePatternNode(getLeafValue());
634 } else {
635 std::vector<TreePatternNode*> CChildren;
636 CChildren.reserve(Children.size());
637 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
638 CChildren.push_back(getChild(i)->clone());
639 New = new TreePatternNode(getOperator(), CChildren);
640 }
641 New->setName(getName());
642 New->setTypes(getExtTypes());
643 New->setPredicateFn(getPredicateFn());
644 New->setTransformFn(getTransformFn());
645 return New;
646}
647
648/// SubstituteFormalArguments - Replace the formal arguments in this tree
649/// with actual values specified by ArgMap.
650void TreePatternNode::
651SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
652 if (isLeaf()) return;
653
654 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
655 TreePatternNode *Child = getChild(i);
656 if (Child->isLeaf()) {
657 Init *Val = Child->getLeafValue();
658 if (dynamic_cast<DefInit*>(Val) &&
659 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
660 // We found a use of a formal argument, replace it with its value.
661 Child = ArgMap[Child->getName()];
662 assert(Child && "Couldn't find formal argument!");
663 setChild(i, Child);
664 }
665 } else {
666 getChild(i)->SubstituteFormalArguments(ArgMap);
667 }
668 }
669}
670
671
672/// InlinePatternFragments - If this pattern refers to any pattern
673/// fragments, inline them into place, giving us a pattern without any
674/// PatFrag references.
675TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
676 if (isLeaf()) return this; // nothing to do.
677 Record *Op = getOperator();
678
679 if (!Op->isSubClassOf("PatFrag")) {
680 // Just recursively inline children nodes.
681 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
682 setChild(i, getChild(i)->InlinePatternFragments(TP));
683 return this;
684 }
685
686 // Otherwise, we found a reference to a fragment. First, look up its
687 // TreePattern record.
688 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
689
690 // Verify that we are passing the right number of operands.
691 if (Frag->getNumArgs() != Children.size())
692 TP.error("'" + Op->getName() + "' fragment requires " +
693 utostr(Frag->getNumArgs()) + " operands!");
694
695 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
696
697 // Resolve formal arguments to their actual value.
698 if (Frag->getNumArgs()) {
699 // Compute the map of formal to actual arguments.
700 std::map<std::string, TreePatternNode*> ArgMap;
701 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
702 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
703
704 FragTree->SubstituteFormalArguments(ArgMap);
705 }
706
707 FragTree->setName(getName());
708 FragTree->UpdateNodeType(getExtTypes(), TP);
709
710 // Get a new copy of this fragment to stitch into here.
711 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000712
713 // The fragment we inlined could have recursive inlining that is needed. See
714 // if there are any pattern fragments in it and inline them as needed.
715 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000716}
717
718/// getImplicitType - Check to see if the specified record has an implicit
719/// type which should be applied to it. This infer the type of register
720/// references from the register file information, for example.
721///
722static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
723 TreePattern &TP) {
724 // Some common return values
Duncan Sands83ec4b62008-06-06 12:08:01 +0000725 std::vector<unsigned char> Unknown(1, EMVT::isUnknown);
Chris Lattner6cefb772008-01-05 22:25:12 +0000726 std::vector<unsigned char> Other(1, MVT::Other);
727
728 // Check to see if this is a register or a register class...
729 if (R->isSubClassOf("RegisterClass")) {
730 if (NotRegisters)
731 return Unknown;
732 const CodeGenRegisterClass &RC =
733 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
734 return ConvertVTs(RC.getValueTypes());
735 } else if (R->isSubClassOf("PatFrag")) {
736 // Pattern fragment types will be resolved when they are inlined.
737 return Unknown;
738 } else if (R->isSubClassOf("Register")) {
739 if (NotRegisters)
740 return Unknown;
741 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
742 return T.getRegisterVTs(R);
743 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
744 // Using a VTSDNode or CondCodeSDNode.
745 return Other;
746 } else if (R->isSubClassOf("ComplexPattern")) {
747 if (NotRegisters)
748 return Unknown;
749 std::vector<unsigned char>
750 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
751 return ComplexPat;
752 } else if (R->getName() == "ptr_rc") {
753 Other[0] = MVT::iPTR;
754 return Other;
755 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
756 R->getName() == "zero_reg") {
757 // Placeholder.
758 return Unknown;
759 }
760
761 TP.error("Unknown node flavor used in pattern: " + R->getName());
762 return Other;
763}
764
Chris Lattnere67bde52008-01-06 05:36:50 +0000765
766/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
767/// CodeGenIntrinsic information for it, otherwise return a null pointer.
768const CodeGenIntrinsic *TreePatternNode::
769getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
770 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
771 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
772 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
773 return 0;
774
775 unsigned IID =
776 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
777 return &CDP.getIntrinsicInfo(IID);
778}
779
Evan Cheng6bd95672008-06-16 20:29:38 +0000780/// isCommutativeIntrinsic - Return true if the node corresponds to a
781/// commutative intrinsic.
782bool
783TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
784 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
785 return Int->isCommutative;
786 return false;
787}
788
Chris Lattnere67bde52008-01-06 05:36:50 +0000789
Chris Lattner6cefb772008-01-05 22:25:12 +0000790/// ApplyTypeConstraints - Apply all of the type constraints relevent to
791/// this node and its children in the tree. This returns true if it makes a
792/// change, false otherwise. If a type contradiction is found, throw an
793/// exception.
794bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +0000795 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +0000796 if (isLeaf()) {
797 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
798 // If it's a regclass or something else known, include the type.
799 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
800 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
801 // Int inits are always integers. :)
Duncan Sands83ec4b62008-06-06 12:08:01 +0000802 bool MadeChange = UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000803
804 if (hasTypeSet()) {
805 // At some point, it may make sense for this tree pattern to have
806 // multiple types. Assert here that it does not, so we revisit this
807 // code when appropriate.
808 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000809 MVT::SimpleValueType VT = getTypeNum(0);
Chris Lattner6cefb772008-01-05 22:25:12 +0000810 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
811 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
812
813 VT = getTypeNum(0);
Mon P Wange3b3a722008-07-30 04:36:53 +0000814 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000815 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattner6cefb772008-01-05 22:25:12 +0000816 // Make sure that the value is representable for this type.
817 if (Size < 32) {
818 int Val = (II->getValue() << (32-Size)) >> (32-Size);
Scott Michel0123b7d2008-02-15 23:05:48 +0000819 if (Val != II->getValue()) {
Bill Wendling27926af2008-02-26 10:45:29 +0000820 // If sign-extended doesn't fit, does it fit as unsigned?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000821 unsigned ValueMask;
822 unsigned UnsignedVal;
823 ValueMask = unsigned(MVT(VT).getIntegerVTBitMask());
824 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +0000825
Bill Wendling27926af2008-02-26 10:45:29 +0000826 if ((ValueMask & UnsignedVal) != UnsignedVal) {
827 TP.error("Integer value '" + itostr(II->getValue())+
828 "' is out of range for type '" +
829 getEnumName(getTypeNum(0)) + "'!");
830 }
831 }
832 }
833 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000834 }
835
836 return MadeChange;
837 }
838 return false;
839 }
840
841 // special handling for set, which isn't really an SDNode.
842 if (getOperator()->getName() == "set") {
843 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
844 unsigned NC = getNumChildren();
845 bool MadeChange = false;
846 for (unsigned i = 0; i < NC-1; ++i) {
847 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
848 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
849
850 // Types of operands must match.
851 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
852 TP);
853 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
854 TP);
855 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
856 }
857 return MadeChange;
858 } else if (getOperator()->getName() == "implicit" ||
859 getOperator()->getName() == "parallel") {
860 bool MadeChange = false;
861 for (unsigned i = 0; i < getNumChildren(); ++i)
862 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
863 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
864 return MadeChange;
Chris Lattnere67bde52008-01-06 05:36:50 +0000865 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000866 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000867
Chris Lattner6cefb772008-01-05 22:25:12 +0000868 // Apply the result type to the node.
Chris Lattnere67bde52008-01-06 05:36:50 +0000869 MadeChange = UpdateNodeType(Int->ArgVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000870
Chris Lattnere67bde52008-01-06 05:36:50 +0000871 if (getNumChildren() != Int->ArgVTs.size())
872 TP.error("Intrinsic '" + Int->Name + "' expects " +
873 utostr(Int->ArgVTs.size()-1) + " operands, not " +
Chris Lattner6cefb772008-01-05 22:25:12 +0000874 utostr(getNumChildren()-1) + " operands!");
875
876 // Apply type info to the intrinsic ID.
877 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
878
879 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000880 MVT::SimpleValueType OpVT = Int->ArgVTs[i];
Chris Lattner6cefb772008-01-05 22:25:12 +0000881 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
882 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
883 }
884 return MadeChange;
885 } else if (getOperator()->isSubClassOf("SDNode")) {
886 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
887
888 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
889 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
890 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
891 // Branch, etc. do not produce results and top-level forms in instr pattern
892 // must have void types.
893 if (NI.getNumResults() == 0)
894 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
895
896 // If this is a vector_shuffle operation, apply types to the build_vector
897 // operation. The types of the integers don't matter, but this ensures they
898 // won't get checked.
899 if (getOperator()->getName() == "vector_shuffle" &&
900 getChild(2)->getOperator()->getName() == "build_vector") {
901 TreePatternNode *BV = getChild(2);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000902 const std::vector<MVT::SimpleValueType> &LegalVTs
Chris Lattner6cefb772008-01-05 22:25:12 +0000903 = CDP.getTargetInfo().getLegalValueTypes();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000904 MVT::SimpleValueType LegalIntVT = MVT::Other;
Chris Lattner6cefb772008-01-05 22:25:12 +0000905 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +0000906 if (isInteger(LegalVTs[i]) && !isVector(LegalVTs[i])) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000907 LegalIntVT = LegalVTs[i];
908 break;
909 }
910 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
911
912 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
913 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
914 }
915 return MadeChange;
916 } else if (getOperator()->isSubClassOf("Instruction")) {
917 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
918 bool MadeChange = false;
919 unsigned NumResults = Inst.getNumResults();
920
921 assert(NumResults <= 1 &&
922 "Only supports zero or one result instrs!");
923
924 CodeGenInstruction &InstInfo =
925 CDP.getTargetInfo().getInstruction(getOperator()->getName());
926 // Apply the result type to the node
927 if (NumResults == 0 || InstInfo.NumDefs == 0) {
Christopher Lamb02f69372008-03-10 04:16:09 +0000928 MadeChange = UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000929 } else {
930 Record *ResultNode = Inst.getResult(0);
931
932 if (ResultNode->getName() == "ptr_rc") {
933 std::vector<unsigned char> VT;
934 VT.push_back(MVT::iPTR);
935 MadeChange = UpdateNodeType(VT, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +0000936 } else if (ResultNode->getName() == "unknown") {
937 std::vector<unsigned char> VT;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000938 VT.push_back(EMVT::isUnknown);
Christopher Lamb5b415372008-03-11 09:33:47 +0000939 MadeChange = UpdateNodeType(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000940 } else {
941 assert(ResultNode->isSubClassOf("RegisterClass") &&
942 "Operands should be register classes!");
943
944 const CodeGenRegisterClass &RC =
945 CDP.getTargetInfo().getRegisterClass(ResultNode);
946 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
947 }
948 }
949
950 unsigned ChildNo = 0;
951 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
952 Record *OperandNode = Inst.getOperand(i);
953
954 // If the instruction expects a predicate or optional def operand, we
955 // codegen this by setting the operand to it's default value if it has a
956 // non-empty DefaultOps field.
957 if ((OperandNode->isSubClassOf("PredicateOperand") ||
958 OperandNode->isSubClassOf("OptionalDefOperand")) &&
959 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
960 continue;
961
962 // Verify that we didn't run out of provided operands.
963 if (ChildNo >= getNumChildren())
964 TP.error("Instruction '" + getOperator()->getName() +
965 "' expects more operands than were provided.");
966
Duncan Sands83ec4b62008-06-06 12:08:01 +0000967 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +0000968 TreePatternNode *Child = getChild(ChildNo++);
969 if (OperandNode->isSubClassOf("RegisterClass")) {
970 const CodeGenRegisterClass &RC =
971 CDP.getTargetInfo().getRegisterClass(OperandNode);
972 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
973 } else if (OperandNode->isSubClassOf("Operand")) {
974 VT = getValueType(OperandNode->getValueAsDef("Type"));
975 MadeChange |= Child->UpdateNodeType(VT, TP);
976 } else if (OperandNode->getName() == "ptr_rc") {
977 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +0000978 } else if (OperandNode->getName() == "unknown") {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000979 MadeChange |= Child->UpdateNodeType(EMVT::isUnknown, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000980 } else {
981 assert(0 && "Unknown operand type!");
982 abort();
983 }
984 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
985 }
Christopher Lamb5b415372008-03-11 09:33:47 +0000986
Christopher Lamb02f69372008-03-10 04:16:09 +0000987 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +0000988 TP.error("Instruction '" + getOperator()->getName() +
989 "' was provided too many operands!");
990
991 return MadeChange;
992 } else {
993 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
994
995 // Node transforms always take one operand.
996 if (getNumChildren() != 1)
997 TP.error("Node transform '" + getOperator()->getName() +
998 "' requires one operand!");
999
1000 // If either the output or input of the xform does not have exact
1001 // type info. We assume they must be the same. Otherwise, it is perfectly
1002 // legal to transform from one type to a completely different type.
1003 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1004 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1005 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1006 return MadeChange;
1007 }
1008 return false;
1009 }
1010}
1011
1012/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1013/// RHS of a commutative operation, not the on LHS.
1014static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1015 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1016 return true;
1017 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1018 return true;
1019 return false;
1020}
1021
1022
1023/// canPatternMatch - If it is impossible for this pattern to match on this
1024/// target, fill in Reason and return false. Otherwise, return true. This is
1025/// used as a santity check for .td files (to prevent people from writing stuff
1026/// that can never possibly work), and to prevent the pattern permuter from
1027/// generating stuff that is useless.
1028bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001029 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001030 if (isLeaf()) return true;
1031
1032 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1033 if (!getChild(i)->canPatternMatch(Reason, CDP))
1034 return false;
1035
1036 // If this is an intrinsic, handle cases that would make it not match. For
1037 // example, if an operand is required to be an immediate.
1038 if (getOperator()->isSubClassOf("Intrinsic")) {
1039 // TODO:
1040 return true;
1041 }
1042
1043 // If this node is a commutative operator, check that the LHS isn't an
1044 // immediate.
1045 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001046 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1047 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001048 // Scan all of the operands of the node and make sure that only the last one
1049 // is a constant node, unless the RHS also is.
1050 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001051 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1052 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001053 if (OnlyOnRHSOfCommutative(getChild(i))) {
1054 Reason="Immediate value must be on the RHS of commutative operators!";
1055 return false;
1056 }
1057 }
1058 }
1059
1060 return true;
1061}
1062
1063//===----------------------------------------------------------------------===//
1064// TreePattern implementation
1065//
1066
1067TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001068 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001069 isInputPattern = isInput;
1070 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1071 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1072}
1073
1074TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001075 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001076 isInputPattern = isInput;
1077 Trees.push_back(ParseTreePattern(Pat));
1078}
1079
1080TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001081 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001082 isInputPattern = isInput;
1083 Trees.push_back(Pat);
1084}
1085
1086
1087
1088void TreePattern::error(const std::string &Msg) const {
1089 dump();
1090 throw "In " + TheRecord->getName() + ": " + Msg;
1091}
1092
1093TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1094 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1095 if (!OpDef) error("Pattern has unexpected operator type!");
1096 Record *Operator = OpDef->getDef();
1097
1098 if (Operator->isSubClassOf("ValueType")) {
1099 // If the operator is a ValueType, then this must be "type cast" of a leaf
1100 // node.
1101 if (Dag->getNumArgs() != 1)
1102 error("Type cast only takes one operand!");
1103
1104 Init *Arg = Dag->getArg(0);
1105 TreePatternNode *New;
1106 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1107 Record *R = DI->getDef();
1108 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1109 Dag->setArg(0, new DagInit(DI,
1110 std::vector<std::pair<Init*, std::string> >()));
1111 return ParseTreePattern(Dag);
1112 }
1113 New = new TreePatternNode(DI);
1114 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1115 New = ParseTreePattern(DI);
1116 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1117 New = new TreePatternNode(II);
1118 if (!Dag->getArgName(0).empty())
1119 error("Constant int argument should not have a name!");
1120 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1121 // Turn this into an IntInit.
1122 Init *II = BI->convertInitializerTo(new IntRecTy());
1123 if (II == 0 || !dynamic_cast<IntInit*>(II))
1124 error("Bits value must be constants!");
1125
1126 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1127 if (!Dag->getArgName(0).empty())
1128 error("Constant int argument should not have a name!");
1129 } else {
1130 Arg->dump();
1131 error("Unknown leaf value for tree pattern!");
1132 return 0;
1133 }
1134
1135 // Apply the type cast.
1136 New->UpdateNodeType(getValueType(Operator), *this);
1137 New->setName(Dag->getArgName(0));
1138 return New;
1139 }
1140
1141 // Verify that this is something that makes sense for an operator.
1142 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
1143 !Operator->isSubClassOf("Instruction") &&
1144 !Operator->isSubClassOf("SDNodeXForm") &&
1145 !Operator->isSubClassOf("Intrinsic") &&
1146 Operator->getName() != "set" &&
1147 Operator->getName() != "implicit" &&
1148 Operator->getName() != "parallel")
1149 error("Unrecognized node '" + Operator->getName() + "'!");
1150
1151 // Check to see if this is something that is illegal in an input pattern.
1152 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1153 Operator->isSubClassOf("SDNodeXForm")))
1154 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1155
1156 std::vector<TreePatternNode*> Children;
1157
1158 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1159 Init *Arg = Dag->getArg(i);
1160 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1161 Children.push_back(ParseTreePattern(DI));
1162 if (Children.back()->getName().empty())
1163 Children.back()->setName(Dag->getArgName(i));
1164 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1165 Record *R = DefI->getDef();
1166 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1167 // TreePatternNode if its own.
1168 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1169 Dag->setArg(i, new DagInit(DefI,
1170 std::vector<std::pair<Init*, std::string> >()));
1171 --i; // Revisit this node...
1172 } else {
1173 TreePatternNode *Node = new TreePatternNode(DefI);
1174 Node->setName(Dag->getArgName(i));
1175 Children.push_back(Node);
1176
1177 // Input argument?
1178 if (R->getName() == "node") {
1179 if (Dag->getArgName(i).empty())
1180 error("'node' argument requires a name to match with operand list");
1181 Args.push_back(Dag->getArgName(i));
1182 }
1183 }
1184 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1185 TreePatternNode *Node = new TreePatternNode(II);
1186 if (!Dag->getArgName(i).empty())
1187 error("Constant int argument should not have a name!");
1188 Children.push_back(Node);
1189 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1190 // Turn this into an IntInit.
1191 Init *II = BI->convertInitializerTo(new IntRecTy());
1192 if (II == 0 || !dynamic_cast<IntInit*>(II))
1193 error("Bits value must be constants!");
1194
1195 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1196 if (!Dag->getArgName(i).empty())
1197 error("Constant int argument should not have a name!");
1198 Children.push_back(Node);
1199 } else {
1200 cerr << '"';
1201 Arg->dump();
1202 cerr << "\": ";
1203 error("Unknown leaf value for tree pattern!");
1204 }
1205 }
1206
1207 // If the operator is an intrinsic, then this is just syntactic sugar for for
1208 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1209 // convert the intrinsic name to a number.
1210 if (Operator->isSubClassOf("Intrinsic")) {
1211 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1212 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1213
1214 // If this intrinsic returns void, it must have side-effects and thus a
1215 // chain.
1216 if (Int.ArgVTs[0] == MVT::isVoid) {
1217 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1218 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1219 // Has side-effects, requires chain.
1220 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1221 } else {
1222 // Otherwise, no chain.
1223 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1224 }
1225
1226 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1227 Children.insert(Children.begin(), IIDNode);
1228 }
1229
1230 return new TreePatternNode(Operator, Children);
1231}
1232
1233/// InferAllTypes - Infer/propagate as many types throughout the expression
1234/// patterns as possible. Return true if all types are infered, false
1235/// otherwise. Throw an exception if a type contradiction is found.
1236bool TreePattern::InferAllTypes() {
1237 bool MadeChange = true;
1238 while (MadeChange) {
1239 MadeChange = false;
1240 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1241 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1242 }
1243
1244 bool HasUnresolvedTypes = false;
1245 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1246 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1247 return !HasUnresolvedTypes;
1248}
1249
1250void TreePattern::print(std::ostream &OS) const {
1251 OS << getRecord()->getName();
1252 if (!Args.empty()) {
1253 OS << "(" << Args[0];
1254 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1255 OS << ", " << Args[i];
1256 OS << ")";
1257 }
1258 OS << ": ";
1259
1260 if (Trees.size() > 1)
1261 OS << "[\n";
1262 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1263 OS << "\t";
1264 Trees[i]->print(OS);
1265 OS << "\n";
1266 }
1267
1268 if (Trees.size() > 1)
1269 OS << "]\n";
1270}
1271
1272void TreePattern::dump() const { print(*cerr.stream()); }
1273
1274//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001275// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001276//
1277
1278// FIXME: REMOVE OSTREAM ARGUMENT
Chris Lattnerfe718932008-01-06 01:10:31 +00001279CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001280 Intrinsics = LoadIntrinsics(Records);
1281 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001282 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001283 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001284 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001285 ParseDefaultOperands();
1286 ParseInstructions();
1287 ParsePatterns();
1288
1289 // Generate variants. For example, commutative patterns can match
1290 // multiple ways. Add them to PatternsToMatch as well.
1291 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001292
1293 // Infer instruction flags. For example, we can detect loads,
1294 // stores, and side effects in many cases by examining an
1295 // instruction's pattern.
1296 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001297}
1298
Chris Lattnerfe718932008-01-06 01:10:31 +00001299CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001300 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1301 E = PatternFragments.end(); I != E; ++I)
1302 delete I->second;
1303}
1304
1305
Chris Lattnerfe718932008-01-06 01:10:31 +00001306Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001307 Record *N = Records.getDef(Name);
1308 if (!N || !N->isSubClassOf("SDNode")) {
1309 cerr << "Error getting SDNode '" << Name << "'!\n";
1310 exit(1);
1311 }
1312 return N;
1313}
1314
1315// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001316void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001317 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1318 while (!Nodes.empty()) {
1319 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1320 Nodes.pop_back();
1321 }
1322
1323 // Get the buildin intrinsic nodes.
1324 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1325 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1326 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1327}
1328
1329/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1330/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001331void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001332 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1333 while (!Xforms.empty()) {
1334 Record *XFormNode = Xforms.back();
1335 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1336 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001337 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001338
1339 Xforms.pop_back();
1340 }
1341}
1342
Chris Lattnerfe718932008-01-06 01:10:31 +00001343void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001344 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1345 while (!AMs.empty()) {
1346 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1347 AMs.pop_back();
1348 }
1349}
1350
1351
1352/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1353/// file, building up the PatternFragments map. After we've collected them all,
1354/// inline fragments together as necessary, so that there are no references left
1355/// inside a pattern fragment to a pattern fragment.
1356///
Chris Lattnerfe718932008-01-06 01:10:31 +00001357void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001358 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1359
Chris Lattnerdc32f982008-01-05 22:43:57 +00001360 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001361 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1362 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1363 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1364 PatternFragments[Fragments[i]] = P;
1365
Chris Lattnerdc32f982008-01-05 22:43:57 +00001366 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001367 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001368 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001369
Chris Lattnerdc32f982008-01-05 22:43:57 +00001370 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001371 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1372
1373 // Parse the operands list.
1374 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1375 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1376 // Special cases: ops == outs == ins. Different names are used to
1377 // improve readibility.
1378 if (!OpsOp ||
1379 (OpsOp->getDef()->getName() != "ops" &&
1380 OpsOp->getDef()->getName() != "outs" &&
1381 OpsOp->getDef()->getName() != "ins"))
1382 P->error("Operands list should start with '(ops ... '!");
1383
1384 // Copy over the arguments.
1385 Args.clear();
1386 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1387 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1388 static_cast<DefInit*>(OpsList->getArg(j))->
1389 getDef()->getName() != "node")
1390 P->error("Operands list should all be 'node' values.");
1391 if (OpsList->getArgName(j).empty())
1392 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001393 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001394 P->error("'" + OpsList->getArgName(j) +
1395 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001396 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001397 Args.push_back(OpsList->getArgName(j));
1398 }
1399
Chris Lattnerdc32f982008-01-05 22:43:57 +00001400 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001401 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001402 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001403
Chris Lattnerdc32f982008-01-05 22:43:57 +00001404 // If there is a code init for this fragment, keep track of the fact that
1405 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001406 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001407 if (!Code.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001408 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001409
1410 // If there is a node transformation corresponding to this, keep track of
1411 // it.
1412 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1413 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1414 P->getOnlyTree()->setTransformFn(Transform);
1415 }
1416
Chris Lattner6cefb772008-01-05 22:25:12 +00001417 // Now that we've parsed all of the tree fragments, do a closure on them so
1418 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001419 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1420 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001421 ThePat->InlinePatternFragments();
1422
1423 // Infer as many types as possible. Don't worry about it if we don't infer
1424 // all of them, some may depend on the inputs of the pattern.
1425 try {
1426 ThePat->InferAllTypes();
1427 } catch (...) {
1428 // If this pattern fragment is not supported by this target (no types can
1429 // satisfy its constraints), just ignore it. If the bogus pattern is
1430 // actually used by instructions, the type consistency error will be
1431 // reported there.
1432 }
1433
1434 // If debugging, print out the pattern fragment result.
1435 DEBUG(ThePat->dump());
1436 }
1437}
1438
Chris Lattnerfe718932008-01-06 01:10:31 +00001439void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001440 std::vector<Record*> DefaultOps[2];
1441 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1442 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1443
1444 // Find some SDNode.
1445 assert(!SDNodes.empty() && "No SDNodes parsed?");
1446 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1447
1448 for (unsigned iter = 0; iter != 2; ++iter) {
1449 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1450 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1451
1452 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1453 // SomeSDnode so that we can parse this.
1454 std::vector<std::pair<Init*, std::string> > Ops;
1455 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1456 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1457 DefaultInfo->getArgName(op)));
1458 DagInit *DI = new DagInit(SomeSDNode, Ops);
1459
1460 // Create a TreePattern to parse this.
1461 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1462 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1463
1464 // Copy the operands over into a DAGDefaultOperand.
1465 DAGDefaultOperand DefaultOpInfo;
1466
1467 TreePatternNode *T = P.getTree(0);
1468 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1469 TreePatternNode *TPN = T->getChild(op);
1470 while (TPN->ApplyTypeConstraints(P, false))
1471 /* Resolve all types */;
1472
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001473 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001474 if (iter == 0)
1475 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1476 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1477 else
1478 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1479 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001480 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001481 DefaultOpInfo.DefaultOps.push_back(TPN);
1482 }
1483
1484 // Insert it into the DefaultOperands map so we can find it later.
1485 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1486 }
1487 }
1488}
1489
1490/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1491/// instruction input. Return true if this is a real use.
1492static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1493 std::map<std::string, TreePatternNode*> &InstInputs,
1494 std::vector<Record*> &InstImpInputs) {
1495 // No name -> not interesting.
1496 if (Pat->getName().empty()) {
1497 if (Pat->isLeaf()) {
1498 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1499 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1500 I->error("Input " + DI->getDef()->getName() + " must be named!");
1501 else if (DI && DI->getDef()->isSubClassOf("Register"))
1502 InstImpInputs.push_back(DI->getDef());
1503 ;
1504 }
1505 return false;
1506 }
1507
1508 Record *Rec;
1509 if (Pat->isLeaf()) {
1510 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1511 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1512 Rec = DI->getDef();
1513 } else {
1514 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1515 Rec = Pat->getOperator();
1516 }
1517
1518 // SRCVALUE nodes are ignored.
1519 if (Rec->getName() == "srcvalue")
1520 return false;
1521
1522 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1523 if (!Slot) {
1524 Slot = Pat;
1525 } else {
1526 Record *SlotRec;
1527 if (Slot->isLeaf()) {
1528 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1529 } else {
1530 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1531 SlotRec = Slot->getOperator();
1532 }
1533
1534 // Ensure that the inputs agree if we've already seen this input.
1535 if (Rec != SlotRec)
1536 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1537 if (Slot->getExtTypes() != Pat->getExtTypes())
1538 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1539 }
1540 return true;
1541}
1542
1543/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1544/// part of "I", the instruction), computing the set of inputs and outputs of
1545/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001546void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001547FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1548 std::map<std::string, TreePatternNode*> &InstInputs,
1549 std::map<std::string, TreePatternNode*>&InstResults,
1550 std::vector<Record*> &InstImpInputs,
1551 std::vector<Record*> &InstImpResults) {
1552 if (Pat->isLeaf()) {
1553 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1554 if (!isUse && Pat->getTransformFn())
1555 I->error("Cannot specify a transform function for a non-input value!");
1556 return;
1557 } else if (Pat->getOperator()->getName() == "implicit") {
1558 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1559 TreePatternNode *Dest = Pat->getChild(i);
1560 if (!Dest->isLeaf())
1561 I->error("implicitly defined value should be a register!");
1562
1563 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1564 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1565 I->error("implicitly defined value should be a register!");
1566 InstImpResults.push_back(Val->getDef());
1567 }
1568 return;
1569 } else if (Pat->getOperator()->getName() != "set") {
1570 // If this is not a set, verify that the children nodes are not void typed,
1571 // and recurse.
1572 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1573 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1574 I->error("Cannot have void nodes inside of patterns!");
1575 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1576 InstImpInputs, InstImpResults);
1577 }
1578
1579 // If this is a non-leaf node with no children, treat it basically as if
1580 // it were a leaf. This handles nodes like (imm).
1581 bool isUse = false;
1582 if (Pat->getNumChildren() == 0)
1583 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1584
1585 if (!isUse && Pat->getTransformFn())
1586 I->error("Cannot specify a transform function for a non-input value!");
1587 return;
1588 }
1589
1590 // Otherwise, this is a set, validate and collect instruction results.
1591 if (Pat->getNumChildren() == 0)
1592 I->error("set requires operands!");
1593
1594 if (Pat->getTransformFn())
1595 I->error("Cannot specify a transform function on a set node!");
1596
1597 // Check the set destinations.
1598 unsigned NumDests = Pat->getNumChildren()-1;
1599 for (unsigned i = 0; i != NumDests; ++i) {
1600 TreePatternNode *Dest = Pat->getChild(i);
1601 if (!Dest->isLeaf())
1602 I->error("set destination should be a register!");
1603
1604 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1605 if (!Val)
1606 I->error("set destination should be a register!");
1607
1608 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1609 Val->getDef()->getName() == "ptr_rc") {
1610 if (Dest->getName().empty())
1611 I->error("set destination must have a name!");
1612 if (InstResults.count(Dest->getName()))
1613 I->error("cannot set '" + Dest->getName() +"' multiple times");
1614 InstResults[Dest->getName()] = Dest;
1615 } else if (Val->getDef()->isSubClassOf("Register")) {
1616 InstImpResults.push_back(Val->getDef());
1617 } else {
1618 I->error("set destination should be a register!");
1619 }
1620 }
1621
1622 // Verify and collect info from the computation.
1623 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1624 InstInputs, InstResults,
1625 InstImpInputs, InstImpResults);
1626}
1627
Dan Gohmanee4fa192008-04-03 00:02:49 +00001628//===----------------------------------------------------------------------===//
1629// Instruction Analysis
1630//===----------------------------------------------------------------------===//
1631
1632class InstAnalyzer {
1633 const CodeGenDAGPatterns &CDP;
1634 bool &mayStore;
1635 bool &mayLoad;
1636 bool &HasSideEffects;
1637public:
1638 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1639 bool &maystore, bool &mayload, bool &hse)
1640 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1641 }
1642
1643 /// Analyze - Analyze the specified instruction, returning true if the
1644 /// instruction had a pattern.
1645 bool Analyze(Record *InstRecord) {
1646 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1647 if (Pattern == 0) {
1648 HasSideEffects = 1;
1649 return false; // No pattern.
1650 }
1651
1652 // FIXME: Assume only the first tree is the pattern. The others are clobber
1653 // nodes.
1654 AnalyzeNode(Pattern->getTree(0));
1655 return true;
1656 }
1657
1658private:
1659 void AnalyzeNode(const TreePatternNode *N) {
1660 if (N->isLeaf()) {
1661 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1662 Record *LeafRec = DI->getDef();
1663 // Handle ComplexPattern leaves.
1664 if (LeafRec->isSubClassOf("ComplexPattern")) {
1665 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1666 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1667 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1668 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1669 }
1670 }
1671 return;
1672 }
1673
1674 // Analyze children.
1675 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1676 AnalyzeNode(N->getChild(i));
1677
1678 // Ignore set nodes, which are not SDNodes.
1679 if (N->getOperator()->getName() == "set")
1680 return;
1681
1682 // Get information about the SDNode for the operator.
1683 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1684
1685 // Notice properties of the node.
1686 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1687 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1688 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1689
1690 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1691 // If this is an intrinsic, analyze it.
1692 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1693 mayLoad = true;// These may load memory.
1694
1695 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1696 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1697
1698 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1699 // WriteMem intrinsics can have other strange effects.
1700 HasSideEffects = true;
1701 }
1702 }
1703
1704};
1705
1706static void InferFromPattern(const CodeGenInstruction &Inst,
1707 bool &MayStore, bool &MayLoad,
1708 bool &HasSideEffects,
1709 const CodeGenDAGPatterns &CDP) {
1710 MayStore = MayLoad = HasSideEffects = false;
1711
1712 bool HadPattern =
1713 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1714
1715 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1716 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1717 // If we decided that this is a store from the pattern, then the .td file
1718 // entry is redundant.
1719 if (MayStore)
1720 fprintf(stderr,
1721 "Warning: mayStore flag explicitly set on instruction '%s'"
1722 " but flag already inferred from pattern.\n",
1723 Inst.TheDef->getName().c_str());
1724 MayStore = true;
1725 }
1726
1727 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1728 // If we decided that this is a load from the pattern, then the .td file
1729 // entry is redundant.
1730 if (MayLoad)
1731 fprintf(stderr,
1732 "Warning: mayLoad flag explicitly set on instruction '%s'"
1733 " but flag already inferred from pattern.\n",
1734 Inst.TheDef->getName().c_str());
1735 MayLoad = true;
1736 }
1737
1738 if (Inst.neverHasSideEffects) {
1739 if (HadPattern)
1740 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1741 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1742 HasSideEffects = false;
1743 }
1744
1745 if (Inst.hasSideEffects) {
1746 if (HasSideEffects)
1747 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1748 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1749 HasSideEffects = true;
1750 }
1751}
1752
Chris Lattner6cefb772008-01-05 22:25:12 +00001753/// ParseInstructions - Parse all of the instructions, inlining and resolving
1754/// any fragments involved. This populates the Instructions list with fully
1755/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001756void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001757 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1758
1759 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1760 ListInit *LI = 0;
1761
1762 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1763 LI = Instrs[i]->getValueAsListInit("Pattern");
1764
1765 // If there is no pattern, only collect minimal information about the
1766 // instruction for its operand list. We have to assume that there is one
1767 // result, as we have no detailed info.
1768 if (!LI || LI->getSize() == 0) {
1769 std::vector<Record*> Results;
1770 std::vector<Record*> Operands;
1771
1772 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1773
1774 if (InstInfo.OperandList.size() != 0) {
1775 if (InstInfo.NumDefs == 0) {
1776 // These produce no results
1777 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1778 Operands.push_back(InstInfo.OperandList[j].Rec);
1779 } else {
1780 // Assume the first operand is the result.
1781 Results.push_back(InstInfo.OperandList[0].Rec);
1782
1783 // The rest are inputs.
1784 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1785 Operands.push_back(InstInfo.OperandList[j].Rec);
1786 }
1787 }
1788
1789 // Create and insert the instruction.
1790 std::vector<Record*> ImpResults;
1791 std::vector<Record*> ImpOperands;
1792 Instructions.insert(std::make_pair(Instrs[i],
1793 DAGInstruction(0, Results, Operands, ImpResults,
1794 ImpOperands)));
1795 continue; // no pattern.
1796 }
1797
1798 // Parse the instruction.
1799 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1800 // Inline pattern fragments into it.
1801 I->InlinePatternFragments();
1802
1803 // Infer as many types as possible. If we cannot infer all of them, we can
1804 // never do anything with this instruction pattern: report it to the user.
1805 if (!I->InferAllTypes())
1806 I->error("Could not infer all types in pattern!");
1807
1808 // InstInputs - Keep track of all of the inputs of the instruction, along
1809 // with the record they are declared as.
1810 std::map<std::string, TreePatternNode*> InstInputs;
1811
1812 // InstResults - Keep track of all the virtual registers that are 'set'
1813 // in the instruction, including what reg class they are.
1814 std::map<std::string, TreePatternNode*> InstResults;
1815
1816 std::vector<Record*> InstImpInputs;
1817 std::vector<Record*> InstImpResults;
1818
1819 // Verify that the top-level forms in the instruction are of void type, and
1820 // fill in the InstResults map.
1821 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1822 TreePatternNode *Pat = I->getTree(j);
1823 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1824 I->error("Top-level forms in instruction pattern should have"
1825 " void types");
1826
1827 // Find inputs and outputs, and verify the structure of the uses/defs.
1828 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1829 InstImpInputs, InstImpResults);
1830 }
1831
1832 // Now that we have inputs and outputs of the pattern, inspect the operands
1833 // list for the instruction. This determines the order that operands are
1834 // added to the machine instruction the node corresponds to.
1835 unsigned NumResults = InstResults.size();
1836
1837 // Parse the operands list from the (ops) list, validating it.
1838 assert(I->getArgList().empty() && "Args list should still be empty here!");
1839 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1840
1841 // Check that all of the results occur first in the list.
1842 std::vector<Record*> Results;
1843 TreePatternNode *Res0Node = NULL;
1844 for (unsigned i = 0; i != NumResults; ++i) {
1845 if (i == CGI.OperandList.size())
1846 I->error("'" + InstResults.begin()->first +
1847 "' set but does not appear in operand list!");
1848 const std::string &OpName = CGI.OperandList[i].Name;
1849
1850 // Check that it exists in InstResults.
1851 TreePatternNode *RNode = InstResults[OpName];
1852 if (RNode == 0)
1853 I->error("Operand $" + OpName + " does not exist in operand list!");
1854
1855 if (i == 0)
1856 Res0Node = RNode;
1857 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1858 if (R == 0)
1859 I->error("Operand $" + OpName + " should be a set destination: all "
1860 "outputs must occur before inputs in operand list!");
1861
1862 if (CGI.OperandList[i].Rec != R)
1863 I->error("Operand $" + OpName + " class mismatch!");
1864
1865 // Remember the return type.
1866 Results.push_back(CGI.OperandList[i].Rec);
1867
1868 // Okay, this one checks out.
1869 InstResults.erase(OpName);
1870 }
1871
1872 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1873 // the copy while we're checking the inputs.
1874 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1875
1876 std::vector<TreePatternNode*> ResultNodeOperands;
1877 std::vector<Record*> Operands;
1878 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1879 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1880 const std::string &OpName = Op.Name;
1881 if (OpName.empty())
1882 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1883
1884 if (!InstInputsCheck.count(OpName)) {
1885 // If this is an predicate operand or optional def operand with an
1886 // DefaultOps set filled in, we can ignore this. When we codegen it,
1887 // we will do so as always executed.
1888 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1889 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1890 // Does it have a non-empty DefaultOps field? If so, ignore this
1891 // operand.
1892 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1893 continue;
1894 }
1895 I->error("Operand $" + OpName +
1896 " does not appear in the instruction pattern");
1897 }
1898 TreePatternNode *InVal = InstInputsCheck[OpName];
1899 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1900
1901 if (InVal->isLeaf() &&
1902 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1903 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1904 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1905 I->error("Operand $" + OpName + "'s register class disagrees"
1906 " between the operand and pattern");
1907 }
1908 Operands.push_back(Op.Rec);
1909
1910 // Construct the result for the dest-pattern operand list.
1911 TreePatternNode *OpNode = InVal->clone();
1912
1913 // No predicate is useful on the result.
1914 OpNode->setPredicateFn("");
1915
1916 // Promote the xform function to be an explicit node if set.
1917 if (Record *Xform = OpNode->getTransformFn()) {
1918 OpNode->setTransformFn(0);
1919 std::vector<TreePatternNode*> Children;
1920 Children.push_back(OpNode);
1921 OpNode = new TreePatternNode(Xform, Children);
1922 }
1923
1924 ResultNodeOperands.push_back(OpNode);
1925 }
1926
1927 if (!InstInputsCheck.empty())
1928 I->error("Input operand $" + InstInputsCheck.begin()->first +
1929 " occurs in pattern but not in operands list!");
1930
1931 TreePatternNode *ResultPattern =
1932 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1933 // Copy fully inferred output node type to instruction result pattern.
1934 if (NumResults > 0)
1935 ResultPattern->setTypes(Res0Node->getExtTypes());
1936
1937 // Create and insert the instruction.
1938 // FIXME: InstImpResults and InstImpInputs should not be part of
1939 // DAGInstruction.
1940 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1941 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1942
1943 // Use a temporary tree pattern to infer all types and make sure that the
1944 // constructed result is correct. This depends on the instruction already
1945 // being inserted into the Instructions map.
1946 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1947 Temp.InferAllTypes();
1948
1949 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1950 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1951
1952 DEBUG(I->dump());
1953 }
1954
1955 // If we can, convert the instructions to be patterns that are matched!
1956 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1957 E = Instructions.end(); II != E; ++II) {
1958 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00001959 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00001960 if (I == 0) continue; // No pattern.
1961
1962 // FIXME: Assume only the first tree is the pattern. The others are clobber
1963 // nodes.
1964 TreePatternNode *Pattern = I->getTree(0);
1965 TreePatternNode *SrcPattern;
1966 if (Pattern->getOperator()->getName() == "set") {
1967 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1968 } else{
1969 // Not a set (store or something?)
1970 SrcPattern = Pattern;
1971 }
1972
1973 std::string Reason;
1974 if (!SrcPattern->canPatternMatch(Reason, *this))
1975 I->error("Instruction can never match: " + Reason);
1976
1977 Record *Instr = II->first;
1978 TreePatternNode *DstPattern = TheInst.getResultPattern();
1979 PatternsToMatch.
1980 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1981 SrcPattern, DstPattern, TheInst.getImpResults(),
1982 Instr->getValueAsInt("AddedComplexity")));
1983 }
1984}
1985
Dan Gohmanee4fa192008-04-03 00:02:49 +00001986
1987void CodeGenDAGPatterns::InferInstructionFlags() {
1988 std::map<std::string, CodeGenInstruction> &InstrDescs =
1989 Target.getInstructions();
1990 for (std::map<std::string, CodeGenInstruction>::iterator
1991 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
1992 CodeGenInstruction &InstInfo = II->second;
1993 // Determine properties of the instruction from its pattern.
1994 bool MayStore, MayLoad, HasSideEffects;
1995 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
1996 InstInfo.mayStore = MayStore;
1997 InstInfo.mayLoad = MayLoad;
1998 InstInfo.hasSideEffects = HasSideEffects;
1999 }
2000}
2001
Chris Lattnerfe718932008-01-06 01:10:31 +00002002void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002003 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2004
2005 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2006 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2007 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2008 Record *Operator = OpDef->getDef();
2009 TreePattern *Pattern;
2010 if (Operator->getName() != "parallel")
2011 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2012 else {
2013 std::vector<Init*> Values;
2014 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
2015 Values.push_back(Tree->getArg(j));
2016 ListInit *LI = new ListInit(Values);
2017 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2018 }
2019
2020 // Inline pattern fragments into it.
2021 Pattern->InlinePatternFragments();
2022
2023 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2024 if (LI->getSize() == 0) continue; // no pattern.
2025
2026 // Parse the instruction.
2027 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2028
2029 // Inline pattern fragments into it.
2030 Result->InlinePatternFragments();
2031
2032 if (Result->getNumTrees() != 1)
2033 Result->error("Cannot handle instructions producing instructions "
2034 "with temporaries yet!");
2035
2036 bool IterateInference;
2037 bool InferredAllPatternTypes, InferredAllResultTypes;
2038 do {
2039 // Infer as many types as possible. If we cannot infer all of them, we
2040 // can never do anything with this pattern: report it to the user.
2041 InferredAllPatternTypes = Pattern->InferAllTypes();
2042
2043 // Infer as many types as possible. If we cannot infer all of them, we
2044 // can never do anything with this pattern: report it to the user.
2045 InferredAllResultTypes = Result->InferAllTypes();
2046
2047 // Apply the type of the result to the source pattern. This helps us
2048 // resolve cases where the input type is known to be a pointer type (which
2049 // is considered resolved), but the result knows it needs to be 32- or
2050 // 64-bits. Infer the other way for good measure.
2051 IterateInference = Pattern->getTree(0)->
2052 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2053 IterateInference |= Result->getTree(0)->
2054 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2055 } while (IterateInference);
2056
2057 // Verify that we inferred enough types that we can do something with the
2058 // pattern and result. If these fire the user has to add type casts.
2059 if (!InferredAllPatternTypes)
2060 Pattern->error("Could not infer all types in pattern!");
2061 if (!InferredAllResultTypes)
2062 Result->error("Could not infer all types in pattern result!");
2063
2064 // Validate that the input pattern is correct.
2065 std::map<std::string, TreePatternNode*> InstInputs;
2066 std::map<std::string, TreePatternNode*> InstResults;
2067 std::vector<Record*> InstImpInputs;
2068 std::vector<Record*> InstImpResults;
2069 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2070 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2071 InstInputs, InstResults,
2072 InstImpInputs, InstImpResults);
2073
2074 // Promote the xform function to be an explicit node if set.
2075 TreePatternNode *DstPattern = Result->getOnlyTree();
2076 std::vector<TreePatternNode*> ResultNodeOperands;
2077 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2078 TreePatternNode *OpNode = DstPattern->getChild(ii);
2079 if (Record *Xform = OpNode->getTransformFn()) {
2080 OpNode->setTransformFn(0);
2081 std::vector<TreePatternNode*> Children;
2082 Children.push_back(OpNode);
2083 OpNode = new TreePatternNode(Xform, Children);
2084 }
2085 ResultNodeOperands.push_back(OpNode);
2086 }
2087 DstPattern = Result->getOnlyTree();
2088 if (!DstPattern->isLeaf())
2089 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2090 ResultNodeOperands);
2091 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2092 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2093 Temp.InferAllTypes();
2094
2095 std::string Reason;
2096 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2097 Pattern->error("Pattern can never match: " + Reason);
2098
2099 PatternsToMatch.
2100 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2101 Pattern->getTree(0),
2102 Temp.getOnlyTree(), InstImpResults,
2103 Patterns[i]->getValueAsInt("AddedComplexity")));
2104 }
2105}
2106
2107/// CombineChildVariants - Given a bunch of permutations of each child of the
2108/// 'operator' node, put them together in all possible ways.
2109static void CombineChildVariants(TreePatternNode *Orig,
2110 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2111 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002112 CodeGenDAGPatterns &CDP,
2113 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002114 // Make sure that each operand has at least one variant to choose from.
2115 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2116 if (ChildVariants[i].empty())
2117 return;
2118
2119 // The end result is an all-pairs construction of the resultant pattern.
2120 std::vector<unsigned> Idxs;
2121 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002122 bool NotDone;
2123 do {
2124#ifndef NDEBUG
2125 if (DebugFlag && !Idxs.empty()) {
2126 cerr << Orig->getOperator()->getName() << ": Idxs = [ ";
2127 for (unsigned i = 0; i < Idxs.size(); ++i) {
2128 cerr << Idxs[i] << " ";
2129 }
2130 cerr << "]\n";
2131 }
2132#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002133 // Create the variant and add it to the output list.
2134 std::vector<TreePatternNode*> NewChildren;
2135 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2136 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2137 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2138
2139 // Copy over properties.
2140 R->setName(Orig->getName());
2141 R->setPredicateFn(Orig->getPredicateFn());
2142 R->setTransformFn(Orig->getTransformFn());
2143 R->setTypes(Orig->getExtTypes());
2144
Scott Michel327d0652008-03-05 17:49:05 +00002145 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002146 std::string ErrString;
2147 if (!R->canPatternMatch(ErrString, CDP)) {
2148 delete R;
2149 } else {
2150 bool AlreadyExists = false;
2151
2152 // Scan to see if this pattern has already been emitted. We can get
2153 // duplication due to things like commuting:
2154 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2155 // which are the same pattern. Ignore the dups.
2156 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002157 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002158 AlreadyExists = true;
2159 break;
2160 }
2161
2162 if (AlreadyExists)
2163 delete R;
2164 else
2165 OutVariants.push_back(R);
2166 }
2167
Scott Michel327d0652008-03-05 17:49:05 +00002168 // Increment indices to the next permutation by incrementing the
2169 // indicies from last index backward, e.g., generate the sequence
2170 // [0, 0], [0, 1], [1, 0], [1, 1].
2171 int IdxsIdx;
2172 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2173 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2174 Idxs[IdxsIdx] = 0;
2175 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002176 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002177 }
Scott Michel327d0652008-03-05 17:49:05 +00002178 NotDone = (IdxsIdx >= 0);
2179 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002180}
2181
2182/// CombineChildVariants - A helper function for binary operators.
2183///
2184static void CombineChildVariants(TreePatternNode *Orig,
2185 const std::vector<TreePatternNode*> &LHS,
2186 const std::vector<TreePatternNode*> &RHS,
2187 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002188 CodeGenDAGPatterns &CDP,
2189 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002190 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2191 ChildVariants.push_back(LHS);
2192 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002193 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002194}
2195
2196
2197static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2198 std::vector<TreePatternNode *> &Children) {
2199 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2200 Record *Operator = N->getOperator();
2201
2202 // Only permit raw nodes.
2203 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
2204 N->getTransformFn()) {
2205 Children.push_back(N);
2206 return;
2207 }
2208
2209 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2210 Children.push_back(N->getChild(0));
2211 else
2212 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2213
2214 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2215 Children.push_back(N->getChild(1));
2216 else
2217 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2218}
2219
2220/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2221/// the (potentially recursive) pattern by using algebraic laws.
2222///
2223static void GenerateVariantsOf(TreePatternNode *N,
2224 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002225 CodeGenDAGPatterns &CDP,
2226 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002227 // We cannot permute leaves.
2228 if (N->isLeaf()) {
2229 OutVariants.push_back(N);
2230 return;
2231 }
2232
2233 // Look up interesting info about the node.
2234 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2235
2236 // If this node is associative, reassociate.
2237 if (NodeInfo.hasProperty(SDNPAssociative)) {
2238 // Reassociate by pulling together all of the linked operators
2239 std::vector<TreePatternNode*> MaximalChildren;
2240 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2241
2242 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2243 // permutations.
2244 if (MaximalChildren.size() == 3) {
2245 // Find the variants of all of our maximal children.
2246 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002247 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2248 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2249 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002250
2251 // There are only two ways we can permute the tree:
2252 // (A op B) op C and A op (B op C)
2253 // Within these forms, we can also permute A/B/C.
2254
2255 // Generate legal pair permutations of A/B/C.
2256 std::vector<TreePatternNode*> ABVariants;
2257 std::vector<TreePatternNode*> BAVariants;
2258 std::vector<TreePatternNode*> ACVariants;
2259 std::vector<TreePatternNode*> CAVariants;
2260 std::vector<TreePatternNode*> BCVariants;
2261 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002262 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2263 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2264 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2265 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2266 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2267 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002268
2269 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002270 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2271 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2272 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2273 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2274 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2275 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002276
2277 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002278 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2279 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2280 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2281 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2282 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2283 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002284 return;
2285 }
2286 }
2287
2288 // Compute permutations of all children.
2289 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2290 ChildVariants.resize(N->getNumChildren());
2291 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002292 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002293
2294 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002295 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002296
2297 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002298 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2299 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2300 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2301 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002302 // Don't count children which are actually register references.
2303 unsigned NC = 0;
2304 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2305 TreePatternNode *Child = N->getChild(i);
2306 if (Child->isLeaf())
2307 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2308 Record *RR = DI->getDef();
2309 if (RR->isSubClassOf("Register"))
2310 continue;
2311 }
2312 NC++;
2313 }
2314 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002315 if (isCommIntrinsic) {
2316 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2317 // operands are the commutative operands, and there might be more operands
2318 // after those.
2319 assert(NC >= 3 &&
2320 "Commutative intrinsic should have at least 3 childrean!");
2321 std::vector<std::vector<TreePatternNode*> > Variants;
2322 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2323 Variants.push_back(ChildVariants[2]);
2324 Variants.push_back(ChildVariants[1]);
2325 for (unsigned i = 3; i != NC; ++i)
2326 Variants.push_back(ChildVariants[i]);
2327 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2328 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002329 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002330 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002331 }
2332}
2333
2334
2335// GenerateVariants - Generate variants. For example, commutative patterns can
2336// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002337void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002338 DOUT << "Generating instruction variants.\n";
2339
2340 // Loop over all of the patterns we've collected, checking to see if we can
2341 // generate variants of the instruction, through the exploitation of
2342 // identities. This permits the target to provide agressive matching without
2343 // the .td file having to contain tons of variants of instructions.
2344 //
2345 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2346 // intentionally do not reconsider these. Any variants of added patterns have
2347 // already been added.
2348 //
2349 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002350 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002351 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002352 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2353 DOUT << "Dependent/multiply used variables: ";
2354 DEBUG(DumpDepVars(DepVars));
2355 DOUT << "\n";
2356 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002357
2358 assert(!Variants.empty() && "Must create at least original variant!");
2359 Variants.erase(Variants.begin()); // Remove the original pattern.
2360
2361 if (Variants.empty()) // No variants for this pattern.
2362 continue;
2363
2364 DOUT << "FOUND VARIANTS OF: ";
2365 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2366 DOUT << "\n";
2367
2368 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2369 TreePatternNode *Variant = Variants[v];
2370
2371 DOUT << " VAR#" << v << ": ";
2372 DEBUG(Variant->dump());
2373 DOUT << "\n";
2374
2375 // Scan to see if an instruction or explicit pattern already matches this.
2376 bool AlreadyExists = false;
2377 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2378 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002379 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002380 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2381 AlreadyExists = true;
2382 break;
2383 }
2384 }
2385 // If we already have it, ignore the variant.
2386 if (AlreadyExists) continue;
2387
2388 // Otherwise, add it to the list of patterns we have.
2389 PatternsToMatch.
2390 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2391 Variant, PatternsToMatch[i].getDstPattern(),
2392 PatternsToMatch[i].getDstRegs(),
2393 PatternsToMatch[i].getAddedComplexity()));
2394 }
2395
2396 DOUT << "\n";
2397 }
2398}
2399