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