blob: 14b2b80bee65cf24a1736af19d68ef0d4d1b1a4b [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>
30static std::vector<MVT::ValueType>
31FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
32 std::vector<MVT::ValueType> Result;
33 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)
44 if (Filter((MVT::ValueType)InVTs[i]))
45 Result.push_back(InVTs[i]);
46 return Result;
47}
48
49static std::vector<unsigned char>
50ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
51 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
57static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
58 const std::vector<unsigned char> &RHS) {
59 if (LHS.size() > RHS.size()) return false;
60 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
61 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
62 return false;
63 return true;
64}
65
66/// isExtIntegerVT - Return true if the specified extended value type vector
67/// contains isInt or an integer value type.
68namespace llvm {
69namespace MVT {
70bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
71 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
72 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
73}
74
75/// isExtFloatingPointVT - Return true if the specified extended value type
76/// vector contains isFP or a FP value type.
77bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
78 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
79 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
80}
81} // end namespace MVT.
82} // end namespace llvm.
83
84//===----------------------------------------------------------------------===//
85// SDTypeConstraint implementation
86//
87
88SDTypeConstraint::SDTypeConstraint(Record *R) {
89 OperandNo = R->getValueAsInt("OperandNum");
90
91 if (R->isSubClassOf("SDTCisVT")) {
92 ConstraintType = SDTCisVT;
93 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
94 } else if (R->isSubClassOf("SDTCisPtrTy")) {
95 ConstraintType = SDTCisPtrTy;
96 } else if (R->isSubClassOf("SDTCisInt")) {
97 ConstraintType = SDTCisInt;
98 } else if (R->isSubClassOf("SDTCisFP")) {
99 ConstraintType = SDTCisFP;
100 } else if (R->isSubClassOf("SDTCisSameAs")) {
101 ConstraintType = SDTCisSameAs;
102 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
103 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
104 ConstraintType = SDTCisVTSmallerThanOp;
105 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
106 R->getValueAsInt("OtherOperandNum");
107 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
108 ConstraintType = SDTCisOpSmallerThanOp;
109 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
110 R->getValueAsInt("BigOperandNum");
111 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
112 ConstraintType = SDTCisIntVectorOfSameSize;
113 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
114 R->getValueAsInt("OtherOpNum");
115 } else {
116 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
117 exit(1);
118 }
119}
120
121/// getOperandNum - Return the node corresponding to operand #OpNo in tree
122/// N, which has NumResults results.
123TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
124 TreePatternNode *N,
125 unsigned NumResults) const {
126 assert(NumResults <= 1 &&
127 "We only work with nodes with zero or one result so far!");
128
129 if (OpNo >= (NumResults + N->getNumChildren())) {
130 cerr << "Invalid operand number " << OpNo << " ";
131 N->dump();
132 cerr << '\n';
133 exit(1);
134 }
135
136 if (OpNo < NumResults)
137 return N; // FIXME: need value #
138 else
139 return N->getChild(OpNo-NumResults);
140}
141
142/// ApplyTypeConstraint - Given a node in a pattern, apply this type
143/// constraint to the nodes operands. This returns true if it makes a
144/// change, false otherwise. If a type contradiction is found, throw an
145/// exception.
146bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
147 const SDNodeInfo &NodeInfo,
148 TreePattern &TP) const {
149 unsigned NumResults = NodeInfo.getNumResults();
150 assert(NumResults <= 1 &&
151 "We only work with nodes with zero or one result so far!");
152
153 // Check that the number of operands is sane. Negative operands -> varargs.
154 if (NodeInfo.getNumOperands() >= 0) {
155 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
156 TP.error(N->getOperator()->getName() + " node requires exactly " +
157 itostr(NodeInfo.getNumOperands()) + " operands!");
158 }
159
160 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
161
162 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
163
164 switch (ConstraintType) {
165 default: assert(0 && "Unknown constraint type!");
166 case SDTCisVT:
167 // Operand must be a particular type.
168 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
169 case SDTCisPtrTy: {
170 // Operand must be same as target pointer type.
171 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
172 }
173 case SDTCisInt: {
174 // If there is only one integer type supported, this must be it.
175 std::vector<MVT::ValueType> IntVTs =
176 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
177
178 // If we found exactly one supported integer type, apply it.
179 if (IntVTs.size() == 1)
180 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
181 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
182 }
183 case SDTCisFP: {
184 // If there is only one FP type supported, this must be it.
185 std::vector<MVT::ValueType> FPVTs =
186 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
187
188 // If we found exactly one supported FP type, apply it.
189 if (FPVTs.size() == 1)
190 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
191 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
192 }
193 case SDTCisSameAs: {
194 TreePatternNode *OtherNode =
195 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
196 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
197 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
198 }
199 case SDTCisVTSmallerThanOp: {
200 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
201 // have an integer type that is smaller than the VT.
202 if (!NodeToApply->isLeaf() ||
203 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
204 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
205 ->isSubClassOf("ValueType"))
206 TP.error(N->getOperator()->getName() + " expects a VT operand!");
207 MVT::ValueType VT =
208 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
209 if (!MVT::isInteger(VT))
210 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
211
212 TreePatternNode *OtherNode =
213 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
214
215 // It must be integer.
216 bool MadeChange = false;
217 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
218
219 // This code only handles nodes that have one type set. Assert here so
220 // that we can change this if we ever need to deal with multiple value
221 // types at this point.
222 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
223 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
224 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
225 return false;
226 }
227 case SDTCisOpSmallerThanOp: {
228 TreePatternNode *BigOperand =
229 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
230
231 // Both operands must be integer or FP, but we don't care which.
232 bool MadeChange = false;
233
234 // This code does not currently handle nodes which have multiple types,
235 // where some types are integer, and some are fp. Assert that this is not
236 // the case.
237 assert(!(MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
238 MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
239 !(MVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
240 MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
241 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
242 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
243 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
244 else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
245 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
246 if (MVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
247 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
248 else if (MVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
249 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
250
251 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
252
253 if (MVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
254 VTs = FilterVTs(VTs, MVT::isInteger);
255 } else if (MVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
256 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
257 } else {
258 VTs.clear();
259 }
260
261 switch (VTs.size()) {
262 default: // Too many VT's to pick from.
263 case 0: break; // No info yet.
264 case 1:
265 // Only one VT of this flavor. Cannot ever satisify the constraints.
266 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
267 case 2:
268 // If we have exactly two possible types, the little operand must be the
269 // small one, the big operand should be the big one. Common with
270 // float/double for example.
271 assert(VTs[0] < VTs[1] && "Should be sorted!");
272 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
273 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
274 break;
275 }
276 return MadeChange;
277 }
278 case SDTCisIntVectorOfSameSize: {
279 TreePatternNode *OtherOperand =
280 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
281 N, NumResults);
282 if (OtherOperand->hasTypeSet()) {
283 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
284 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
285 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
286 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
287 return NodeToApply->UpdateNodeType(IVT, TP);
288 }
289 return false;
290 }
291 }
292 return false;
293}
294
295//===----------------------------------------------------------------------===//
296// SDNodeInfo implementation
297//
298SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
299 EnumName = R->getValueAsString("Opcode");
300 SDClassName = R->getValueAsString("SDClass");
301 Record *TypeProfile = R->getValueAsDef("TypeProfile");
302 NumResults = TypeProfile->getValueAsInt("NumResults");
303 NumOperands = TypeProfile->getValueAsInt("NumOperands");
304
305 // Parse the properties.
306 Properties = 0;
307 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
308 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
309 if (PropList[i]->getName() == "SDNPCommutative") {
310 Properties |= 1 << SDNPCommutative;
311 } else if (PropList[i]->getName() == "SDNPAssociative") {
312 Properties |= 1 << SDNPAssociative;
313 } else if (PropList[i]->getName() == "SDNPHasChain") {
314 Properties |= 1 << SDNPHasChain;
315 } else if (PropList[i]->getName() == "SDNPOutFlag") {
316 Properties |= 1 << SDNPOutFlag;
317 } else if (PropList[i]->getName() == "SDNPInFlag") {
318 Properties |= 1 << SDNPInFlag;
319 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
320 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000321 } else if (PropList[i]->getName() == "SDNPMayStore") {
322 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000323 } else if (PropList[i]->getName() == "SDNPMayLoad") {
324 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000325 } else if (PropList[i]->getName() == "SDNPSideEffect") {
326 Properties |= 1 << SDNPSideEffect;
Chris Lattner6cefb772008-01-05 22:25:12 +0000327 } else {
328 cerr << "Unknown SD Node property '" << PropList[i]->getName()
329 << "' on node '" << R->getName() << "'!\n";
330 exit(1);
331 }
332 }
333
334
335 // Parse the type constraints.
336 std::vector<Record*> ConstraintList =
337 TypeProfile->getValueAsListOfDefs("Constraints");
338 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
339}
340
341//===----------------------------------------------------------------------===//
342// TreePatternNode implementation
343//
344
345TreePatternNode::~TreePatternNode() {
346#if 0 // FIXME: implement refcounted tree nodes!
347 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
348 delete getChild(i);
349#endif
350}
351
352/// UpdateNodeType - Set the node type of N to VT if VT contains
353/// information. If N already contains a conflicting type, then throw an
354/// exception. This returns true if any information was updated.
355///
356bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
357 TreePattern &TP) {
358 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
359
360 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
361 return false;
362 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
363 setTypes(ExtVTs);
364 return true;
365 }
366
367 if (getExtTypeNum(0) == MVT::iPTR) {
368 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::isInt)
369 return false;
370 if (MVT::isExtIntegerInVTs(ExtVTs)) {
371 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, MVT::isInteger);
372 if (FVTs.size()) {
373 setTypes(ExtVTs);
374 return true;
375 }
376 }
377 }
378
379 if (ExtVTs[0] == MVT::isInt && MVT::isExtIntegerInVTs(getExtTypes())) {
380 assert(hasTypeSet() && "should be handled above!");
381 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
382 if (getExtTypes() == FVTs)
383 return false;
384 setTypes(FVTs);
385 return true;
386 }
387 if (ExtVTs[0] == MVT::iPTR && MVT::isExtIntegerInVTs(getExtTypes())) {
388 //assert(hasTypeSet() && "should be handled above!");
389 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
390 if (getExtTypes() == FVTs)
391 return false;
392 if (FVTs.size()) {
393 setTypes(FVTs);
394 return true;
395 }
396 }
397 if (ExtVTs[0] == MVT::isFP && MVT::isExtFloatingPointInVTs(getExtTypes())) {
398 assert(hasTypeSet() && "should be handled above!");
399 std::vector<unsigned char> FVTs =
400 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
401 if (getExtTypes() == FVTs)
402 return false;
403 setTypes(FVTs);
404 return true;
405 }
406
407 // If we know this is an int or fp type, and we are told it is a specific one,
408 // take the advice.
409 //
410 // Similarly, we should probably set the type here to the intersection of
411 // {isInt|isFP} and ExtVTs
412 if ((getExtTypeNum(0) == MVT::isInt && MVT::isExtIntegerInVTs(ExtVTs)) ||
413 (getExtTypeNum(0) == MVT::isFP && MVT::isExtFloatingPointInVTs(ExtVTs))){
414 setTypes(ExtVTs);
415 return true;
416 }
417 if (getExtTypeNum(0) == MVT::isInt && ExtVTs[0] == MVT::iPTR) {
418 setTypes(ExtVTs);
419 return true;
420 }
421
422 if (isLeaf()) {
423 dump();
424 cerr << " ";
425 TP.error("Type inference contradiction found in node!");
426 } else {
427 TP.error("Type inference contradiction found in node " +
428 getOperator()->getName() + "!");
429 }
430 return true; // unreachable
431}
432
433
434void TreePatternNode::print(std::ostream &OS) const {
435 if (isLeaf()) {
436 OS << *getLeafValue();
437 } else {
438 OS << "(" << getOperator()->getName();
439 }
440
441 // FIXME: At some point we should handle printing all the value types for
442 // nodes that are multiply typed.
443 switch (getExtTypeNum(0)) {
444 case MVT::Other: OS << ":Other"; break;
445 case MVT::isInt: OS << ":isInt"; break;
446 case MVT::isFP : OS << ":isFP"; break;
447 case MVT::isUnknown: ; /*OS << ":?";*/ break;
448 case MVT::iPTR: OS << ":iPTR"; break;
449 default: {
450 std::string VTName = llvm::getName(getTypeNum(0));
451 // Strip off MVT:: prefix if present.
452 if (VTName.substr(0,5) == "MVT::")
453 VTName = VTName.substr(5);
454 OS << ":" << VTName;
455 break;
456 }
457 }
458
459 if (!isLeaf()) {
460 if (getNumChildren() != 0) {
461 OS << " ";
462 getChild(0)->print(OS);
463 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
464 OS << ", ";
465 getChild(i)->print(OS);
466 }
467 }
468 OS << ")";
469 }
470
471 if (!PredicateFn.empty())
472 OS << "<<P:" << PredicateFn << ">>";
473 if (TransformFn)
474 OS << "<<X:" << TransformFn->getName() << ">>";
475 if (!getName().empty())
476 OS << ":$" << getName();
477
478}
479void TreePatternNode::dump() const {
480 print(*cerr.stream());
481}
482
483/// isIsomorphicTo - Return true if this node is recursively isomorphic to
484/// the specified node. For this comparison, all of the state of the node
485/// is considered, except for the assigned name. Nodes with differing names
486/// that are otherwise identical are considered isomorphic.
487bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
488 if (N == this) return true;
489 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
490 getPredicateFn() != N->getPredicateFn() ||
491 getTransformFn() != N->getTransformFn())
492 return false;
493
494 if (isLeaf()) {
495 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
496 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
497 return DI->getDef() == NDI->getDef();
498 return getLeafValue() == N->getLeafValue();
499 }
500
501 if (N->getOperator() != getOperator() ||
502 N->getNumChildren() != getNumChildren()) return false;
503 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
504 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
505 return false;
506 return true;
507}
508
509/// clone - Make a copy of this tree and all of its children.
510///
511TreePatternNode *TreePatternNode::clone() const {
512 TreePatternNode *New;
513 if (isLeaf()) {
514 New = new TreePatternNode(getLeafValue());
515 } else {
516 std::vector<TreePatternNode*> CChildren;
517 CChildren.reserve(Children.size());
518 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
519 CChildren.push_back(getChild(i)->clone());
520 New = new TreePatternNode(getOperator(), CChildren);
521 }
522 New->setName(getName());
523 New->setTypes(getExtTypes());
524 New->setPredicateFn(getPredicateFn());
525 New->setTransformFn(getTransformFn());
526 return New;
527}
528
529/// SubstituteFormalArguments - Replace the formal arguments in this tree
530/// with actual values specified by ArgMap.
531void TreePatternNode::
532SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
533 if (isLeaf()) return;
534
535 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
536 TreePatternNode *Child = getChild(i);
537 if (Child->isLeaf()) {
538 Init *Val = Child->getLeafValue();
539 if (dynamic_cast<DefInit*>(Val) &&
540 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
541 // We found a use of a formal argument, replace it with its value.
542 Child = ArgMap[Child->getName()];
543 assert(Child && "Couldn't find formal argument!");
544 setChild(i, Child);
545 }
546 } else {
547 getChild(i)->SubstituteFormalArguments(ArgMap);
548 }
549 }
550}
551
552
553/// InlinePatternFragments - If this pattern refers to any pattern
554/// fragments, inline them into place, giving us a pattern without any
555/// PatFrag references.
556TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
557 if (isLeaf()) return this; // nothing to do.
558 Record *Op = getOperator();
559
560 if (!Op->isSubClassOf("PatFrag")) {
561 // Just recursively inline children nodes.
562 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
563 setChild(i, getChild(i)->InlinePatternFragments(TP));
564 return this;
565 }
566
567 // Otherwise, we found a reference to a fragment. First, look up its
568 // TreePattern record.
569 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
570
571 // Verify that we are passing the right number of operands.
572 if (Frag->getNumArgs() != Children.size())
573 TP.error("'" + Op->getName() + "' fragment requires " +
574 utostr(Frag->getNumArgs()) + " operands!");
575
576 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
577
578 // Resolve formal arguments to their actual value.
579 if (Frag->getNumArgs()) {
580 // Compute the map of formal to actual arguments.
581 std::map<std::string, TreePatternNode*> ArgMap;
582 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
583 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
584
585 FragTree->SubstituteFormalArguments(ArgMap);
586 }
587
588 FragTree->setName(getName());
589 FragTree->UpdateNodeType(getExtTypes(), TP);
590
591 // Get a new copy of this fragment to stitch into here.
592 //delete this; // FIXME: implement refcounting!
593 return FragTree;
594}
595
596/// getImplicitType - Check to see if the specified record has an implicit
597/// type which should be applied to it. This infer the type of register
598/// references from the register file information, for example.
599///
600static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
601 TreePattern &TP) {
602 // Some common return values
603 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
604 std::vector<unsigned char> Other(1, MVT::Other);
605
606 // Check to see if this is a register or a register class...
607 if (R->isSubClassOf("RegisterClass")) {
608 if (NotRegisters)
609 return Unknown;
610 const CodeGenRegisterClass &RC =
611 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
612 return ConvertVTs(RC.getValueTypes());
613 } else if (R->isSubClassOf("PatFrag")) {
614 // Pattern fragment types will be resolved when they are inlined.
615 return Unknown;
616 } else if (R->isSubClassOf("Register")) {
617 if (NotRegisters)
618 return Unknown;
619 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
620 return T.getRegisterVTs(R);
621 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
622 // Using a VTSDNode or CondCodeSDNode.
623 return Other;
624 } else if (R->isSubClassOf("ComplexPattern")) {
625 if (NotRegisters)
626 return Unknown;
627 std::vector<unsigned char>
628 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
629 return ComplexPat;
630 } else if (R->getName() == "ptr_rc") {
631 Other[0] = MVT::iPTR;
632 return Other;
633 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
634 R->getName() == "zero_reg") {
635 // Placeholder.
636 return Unknown;
637 }
638
639 TP.error("Unknown node flavor used in pattern: " + R->getName());
640 return Other;
641}
642
Chris Lattnere67bde52008-01-06 05:36:50 +0000643
644/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
645/// CodeGenIntrinsic information for it, otherwise return a null pointer.
646const CodeGenIntrinsic *TreePatternNode::
647getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
648 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
649 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
650 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
651 return 0;
652
653 unsigned IID =
654 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
655 return &CDP.getIntrinsicInfo(IID);
656}
657
658
Chris Lattner6cefb772008-01-05 22:25:12 +0000659/// ApplyTypeConstraints - Apply all of the type constraints relevent to
660/// this node and its children in the tree. This returns true if it makes a
661/// change, false otherwise. If a type contradiction is found, throw an
662/// exception.
663bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +0000664 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +0000665 if (isLeaf()) {
666 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
667 // If it's a regclass or something else known, include the type.
668 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
669 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
670 // Int inits are always integers. :)
671 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
672
673 if (hasTypeSet()) {
674 // At some point, it may make sense for this tree pattern to have
675 // multiple types. Assert here that it does not, so we revisit this
676 // code when appropriate.
677 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
678 MVT::ValueType VT = getTypeNum(0);
679 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
680 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
681
682 VT = getTypeNum(0);
683 if (VT != MVT::iPTR) {
684 unsigned Size = MVT::getSizeInBits(VT);
685 // Make sure that the value is representable for this type.
686 if (Size < 32) {
687 int Val = (II->getValue() << (32-Size)) >> (32-Size);
688 if (Val != II->getValue())
689 TP.error("Sign-extended integer value '" + itostr(II->getValue())+
690 "' is out of range for type '" +
691 getEnumName(getTypeNum(0)) + "'!");
692 }
693 }
694 }
695
696 return MadeChange;
697 }
698 return false;
699 }
700
701 // special handling for set, which isn't really an SDNode.
702 if (getOperator()->getName() == "set") {
703 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
704 unsigned NC = getNumChildren();
705 bool MadeChange = false;
706 for (unsigned i = 0; i < NC-1; ++i) {
707 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
708 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
709
710 // Types of operands must match.
711 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
712 TP);
713 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
714 TP);
715 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
716 }
717 return MadeChange;
718 } else if (getOperator()->getName() == "implicit" ||
719 getOperator()->getName() == "parallel") {
720 bool MadeChange = false;
721 for (unsigned i = 0; i < getNumChildren(); ++i)
722 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
723 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
724 return MadeChange;
Chris Lattnere67bde52008-01-06 05:36:50 +0000725 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000726 bool MadeChange = false;
727
728 // Apply the result type to the node.
Chris Lattnere67bde52008-01-06 05:36:50 +0000729 MadeChange = UpdateNodeType(Int->ArgVTs[0], TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000730
Chris Lattnere67bde52008-01-06 05:36:50 +0000731 if (getNumChildren() != Int->ArgVTs.size())
732 TP.error("Intrinsic '" + Int->Name + "' expects " +
733 utostr(Int->ArgVTs.size()-1) + " operands, not " +
Chris Lattner6cefb772008-01-05 22:25:12 +0000734 utostr(getNumChildren()-1) + " operands!");
735
736 // Apply type info to the intrinsic ID.
737 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
738
739 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
Chris Lattnere67bde52008-01-06 05:36:50 +0000740 MVT::ValueType OpVT = Int->ArgVTs[i];
Chris Lattner6cefb772008-01-05 22:25:12 +0000741 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
742 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
743 }
744 return MadeChange;
745 } else if (getOperator()->isSubClassOf("SDNode")) {
746 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
747
748 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
749 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
750 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
751 // Branch, etc. do not produce results and top-level forms in instr pattern
752 // must have void types.
753 if (NI.getNumResults() == 0)
754 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
755
756 // If this is a vector_shuffle operation, apply types to the build_vector
757 // operation. The types of the integers don't matter, but this ensures they
758 // won't get checked.
759 if (getOperator()->getName() == "vector_shuffle" &&
760 getChild(2)->getOperator()->getName() == "build_vector") {
761 TreePatternNode *BV = getChild(2);
762 const std::vector<MVT::ValueType> &LegalVTs
763 = CDP.getTargetInfo().getLegalValueTypes();
764 MVT::ValueType LegalIntVT = MVT::Other;
765 for (unsigned i = 0, e = LegalVTs.size(); i != e; ++i)
766 if (MVT::isInteger(LegalVTs[i]) && !MVT::isVector(LegalVTs[i])) {
767 LegalIntVT = LegalVTs[i];
768 break;
769 }
770 assert(LegalIntVT != MVT::Other && "No legal integer VT?");
771
772 for (unsigned i = 0, e = BV->getNumChildren(); i != e; ++i)
773 MadeChange |= BV->getChild(i)->UpdateNodeType(LegalIntVT, TP);
774 }
775 return MadeChange;
776 } else if (getOperator()->isSubClassOf("Instruction")) {
777 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
778 bool MadeChange = false;
779 unsigned NumResults = Inst.getNumResults();
780
781 assert(NumResults <= 1 &&
782 "Only supports zero or one result instrs!");
783
784 CodeGenInstruction &InstInfo =
785 CDP.getTargetInfo().getInstruction(getOperator()->getName());
786 // Apply the result type to the node
787 if (NumResults == 0 || InstInfo.NumDefs == 0) {
788 MadeChange = UpdateNodeType(MVT::isVoid, TP);
789 } else {
790 Record *ResultNode = Inst.getResult(0);
791
792 if (ResultNode->getName() == "ptr_rc") {
793 std::vector<unsigned char> VT;
794 VT.push_back(MVT::iPTR);
795 MadeChange = UpdateNodeType(VT, TP);
796 } else {
797 assert(ResultNode->isSubClassOf("RegisterClass") &&
798 "Operands should be register classes!");
799
800 const CodeGenRegisterClass &RC =
801 CDP.getTargetInfo().getRegisterClass(ResultNode);
802 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
803 }
804 }
805
806 unsigned ChildNo = 0;
807 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
808 Record *OperandNode = Inst.getOperand(i);
809
810 // If the instruction expects a predicate or optional def operand, we
811 // codegen this by setting the operand to it's default value if it has a
812 // non-empty DefaultOps field.
813 if ((OperandNode->isSubClassOf("PredicateOperand") ||
814 OperandNode->isSubClassOf("OptionalDefOperand")) &&
815 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
816 continue;
817
818 // Verify that we didn't run out of provided operands.
819 if (ChildNo >= getNumChildren())
820 TP.error("Instruction '" + getOperator()->getName() +
821 "' expects more operands than were provided.");
822
823 MVT::ValueType VT;
824 TreePatternNode *Child = getChild(ChildNo++);
825 if (OperandNode->isSubClassOf("RegisterClass")) {
826 const CodeGenRegisterClass &RC =
827 CDP.getTargetInfo().getRegisterClass(OperandNode);
828 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
829 } else if (OperandNode->isSubClassOf("Operand")) {
830 VT = getValueType(OperandNode->getValueAsDef("Type"));
831 MadeChange |= Child->UpdateNodeType(VT, TP);
832 } else if (OperandNode->getName() == "ptr_rc") {
833 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
834 } else {
835 assert(0 && "Unknown operand type!");
836 abort();
837 }
838 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
839 }
840
841 if (ChildNo != getNumChildren())
842 TP.error("Instruction '" + getOperator()->getName() +
843 "' was provided too many operands!");
844
845 return MadeChange;
846 } else {
847 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
848
849 // Node transforms always take one operand.
850 if (getNumChildren() != 1)
851 TP.error("Node transform '" + getOperator()->getName() +
852 "' requires one operand!");
853
854 // If either the output or input of the xform does not have exact
855 // type info. We assume they must be the same. Otherwise, it is perfectly
856 // legal to transform from one type to a completely different type.
857 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
858 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
859 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
860 return MadeChange;
861 }
862 return false;
863 }
864}
865
866/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
867/// RHS of a commutative operation, not the on LHS.
868static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
869 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
870 return true;
871 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
872 return true;
873 return false;
874}
875
876
877/// canPatternMatch - If it is impossible for this pattern to match on this
878/// target, fill in Reason and return false. Otherwise, return true. This is
879/// used as a santity check for .td files (to prevent people from writing stuff
880/// that can never possibly work), and to prevent the pattern permuter from
881/// generating stuff that is useless.
882bool TreePatternNode::canPatternMatch(std::string &Reason,
Chris Lattnerfe718932008-01-06 01:10:31 +0000883 CodeGenDAGPatterns &CDP){
Chris Lattner6cefb772008-01-05 22:25:12 +0000884 if (isLeaf()) return true;
885
886 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
887 if (!getChild(i)->canPatternMatch(Reason, CDP))
888 return false;
889
890 // If this is an intrinsic, handle cases that would make it not match. For
891 // example, if an operand is required to be an immediate.
892 if (getOperator()->isSubClassOf("Intrinsic")) {
893 // TODO:
894 return true;
895 }
896
897 // If this node is a commutative operator, check that the LHS isn't an
898 // immediate.
899 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
900 if (NodeInfo.hasProperty(SDNPCommutative)) {
901 // Scan all of the operands of the node and make sure that only the last one
902 // is a constant node, unless the RHS also is.
903 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
904 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
905 if (OnlyOnRHSOfCommutative(getChild(i))) {
906 Reason="Immediate value must be on the RHS of commutative operators!";
907 return false;
908 }
909 }
910 }
911
912 return true;
913}
914
915//===----------------------------------------------------------------------===//
916// TreePattern implementation
917//
918
919TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +0000920 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +0000921 isInputPattern = isInput;
922 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
923 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
924}
925
926TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +0000927 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +0000928 isInputPattern = isInput;
929 Trees.push_back(ParseTreePattern(Pat));
930}
931
932TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +0000933 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +0000934 isInputPattern = isInput;
935 Trees.push_back(Pat);
936}
937
938
939
940void TreePattern::error(const std::string &Msg) const {
941 dump();
942 throw "In " + TheRecord->getName() + ": " + Msg;
943}
944
945TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
946 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
947 if (!OpDef) error("Pattern has unexpected operator type!");
948 Record *Operator = OpDef->getDef();
949
950 if (Operator->isSubClassOf("ValueType")) {
951 // If the operator is a ValueType, then this must be "type cast" of a leaf
952 // node.
953 if (Dag->getNumArgs() != 1)
954 error("Type cast only takes one operand!");
955
956 Init *Arg = Dag->getArg(0);
957 TreePatternNode *New;
958 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
959 Record *R = DI->getDef();
960 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
961 Dag->setArg(0, new DagInit(DI,
962 std::vector<std::pair<Init*, std::string> >()));
963 return ParseTreePattern(Dag);
964 }
965 New = new TreePatternNode(DI);
966 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
967 New = ParseTreePattern(DI);
968 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
969 New = new TreePatternNode(II);
970 if (!Dag->getArgName(0).empty())
971 error("Constant int argument should not have a name!");
972 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
973 // Turn this into an IntInit.
974 Init *II = BI->convertInitializerTo(new IntRecTy());
975 if (II == 0 || !dynamic_cast<IntInit*>(II))
976 error("Bits value must be constants!");
977
978 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
979 if (!Dag->getArgName(0).empty())
980 error("Constant int argument should not have a name!");
981 } else {
982 Arg->dump();
983 error("Unknown leaf value for tree pattern!");
984 return 0;
985 }
986
987 // Apply the type cast.
988 New->UpdateNodeType(getValueType(Operator), *this);
989 New->setName(Dag->getArgName(0));
990 return New;
991 }
992
993 // Verify that this is something that makes sense for an operator.
994 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
995 !Operator->isSubClassOf("Instruction") &&
996 !Operator->isSubClassOf("SDNodeXForm") &&
997 !Operator->isSubClassOf("Intrinsic") &&
998 Operator->getName() != "set" &&
999 Operator->getName() != "implicit" &&
1000 Operator->getName() != "parallel")
1001 error("Unrecognized node '" + Operator->getName() + "'!");
1002
1003 // Check to see if this is something that is illegal in an input pattern.
1004 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1005 Operator->isSubClassOf("SDNodeXForm")))
1006 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1007
1008 std::vector<TreePatternNode*> Children;
1009
1010 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1011 Init *Arg = Dag->getArg(i);
1012 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1013 Children.push_back(ParseTreePattern(DI));
1014 if (Children.back()->getName().empty())
1015 Children.back()->setName(Dag->getArgName(i));
1016 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1017 Record *R = DefI->getDef();
1018 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1019 // TreePatternNode if its own.
1020 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1021 Dag->setArg(i, new DagInit(DefI,
1022 std::vector<std::pair<Init*, std::string> >()));
1023 --i; // Revisit this node...
1024 } else {
1025 TreePatternNode *Node = new TreePatternNode(DefI);
1026 Node->setName(Dag->getArgName(i));
1027 Children.push_back(Node);
1028
1029 // Input argument?
1030 if (R->getName() == "node") {
1031 if (Dag->getArgName(i).empty())
1032 error("'node' argument requires a name to match with operand list");
1033 Args.push_back(Dag->getArgName(i));
1034 }
1035 }
1036 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1037 TreePatternNode *Node = new TreePatternNode(II);
1038 if (!Dag->getArgName(i).empty())
1039 error("Constant int argument should not have a name!");
1040 Children.push_back(Node);
1041 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1042 // Turn this into an IntInit.
1043 Init *II = BI->convertInitializerTo(new IntRecTy());
1044 if (II == 0 || !dynamic_cast<IntInit*>(II))
1045 error("Bits value must be constants!");
1046
1047 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1048 if (!Dag->getArgName(i).empty())
1049 error("Constant int argument should not have a name!");
1050 Children.push_back(Node);
1051 } else {
1052 cerr << '"';
1053 Arg->dump();
1054 cerr << "\": ";
1055 error("Unknown leaf value for tree pattern!");
1056 }
1057 }
1058
1059 // If the operator is an intrinsic, then this is just syntactic sugar for for
1060 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1061 // convert the intrinsic name to a number.
1062 if (Operator->isSubClassOf("Intrinsic")) {
1063 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1064 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1065
1066 // If this intrinsic returns void, it must have side-effects and thus a
1067 // chain.
1068 if (Int.ArgVTs[0] == MVT::isVoid) {
1069 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1070 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1071 // Has side-effects, requires chain.
1072 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1073 } else {
1074 // Otherwise, no chain.
1075 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1076 }
1077
1078 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1079 Children.insert(Children.begin(), IIDNode);
1080 }
1081
1082 return new TreePatternNode(Operator, Children);
1083}
1084
1085/// InferAllTypes - Infer/propagate as many types throughout the expression
1086/// patterns as possible. Return true if all types are infered, false
1087/// otherwise. Throw an exception if a type contradiction is found.
1088bool TreePattern::InferAllTypes() {
1089 bool MadeChange = true;
1090 while (MadeChange) {
1091 MadeChange = false;
1092 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1093 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1094 }
1095
1096 bool HasUnresolvedTypes = false;
1097 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1098 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1099 return !HasUnresolvedTypes;
1100}
1101
1102void TreePattern::print(std::ostream &OS) const {
1103 OS << getRecord()->getName();
1104 if (!Args.empty()) {
1105 OS << "(" << Args[0];
1106 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1107 OS << ", " << Args[i];
1108 OS << ")";
1109 }
1110 OS << ": ";
1111
1112 if (Trees.size() > 1)
1113 OS << "[\n";
1114 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1115 OS << "\t";
1116 Trees[i]->print(OS);
1117 OS << "\n";
1118 }
1119
1120 if (Trees.size() > 1)
1121 OS << "]\n";
1122}
1123
1124void TreePattern::dump() const { print(*cerr.stream()); }
1125
1126//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001127// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001128//
1129
1130// FIXME: REMOVE OSTREAM ARGUMENT
Chris Lattnerfe718932008-01-06 01:10:31 +00001131CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001132 Intrinsics = LoadIntrinsics(Records);
1133 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001134 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001135 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001136 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001137 ParseDefaultOperands();
1138 ParseInstructions();
1139 ParsePatterns();
1140
1141 // Generate variants. For example, commutative patterns can match
1142 // multiple ways. Add them to PatternsToMatch as well.
1143 GenerateVariants();
1144}
1145
Chris Lattnerfe718932008-01-06 01:10:31 +00001146CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001147 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1148 E = PatternFragments.end(); I != E; ++I)
1149 delete I->second;
1150}
1151
1152
Chris Lattnerfe718932008-01-06 01:10:31 +00001153Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001154 Record *N = Records.getDef(Name);
1155 if (!N || !N->isSubClassOf("SDNode")) {
1156 cerr << "Error getting SDNode '" << Name << "'!\n";
1157 exit(1);
1158 }
1159 return N;
1160}
1161
1162// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001163void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001164 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1165 while (!Nodes.empty()) {
1166 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1167 Nodes.pop_back();
1168 }
1169
1170 // Get the buildin intrinsic nodes.
1171 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1172 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1173 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1174}
1175
1176/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1177/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001178void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001179 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1180 while (!Xforms.empty()) {
1181 Record *XFormNode = Xforms.back();
1182 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1183 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001184 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001185
1186 Xforms.pop_back();
1187 }
1188}
1189
Chris Lattnerfe718932008-01-06 01:10:31 +00001190void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001191 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1192 while (!AMs.empty()) {
1193 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1194 AMs.pop_back();
1195 }
1196}
1197
1198
1199/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1200/// file, building up the PatternFragments map. After we've collected them all,
1201/// inline fragments together as necessary, so that there are no references left
1202/// inside a pattern fragment to a pattern fragment.
1203///
Chris Lattnerfe718932008-01-06 01:10:31 +00001204void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001205 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1206
Chris Lattnerdc32f982008-01-05 22:43:57 +00001207 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001208 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1209 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1210 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1211 PatternFragments[Fragments[i]] = P;
1212
Chris Lattnerdc32f982008-01-05 22:43:57 +00001213 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001214 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001215 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001216
Chris Lattnerdc32f982008-01-05 22:43:57 +00001217 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001218 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1219
1220 // Parse the operands list.
1221 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1222 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1223 // Special cases: ops == outs == ins. Different names are used to
1224 // improve readibility.
1225 if (!OpsOp ||
1226 (OpsOp->getDef()->getName() != "ops" &&
1227 OpsOp->getDef()->getName() != "outs" &&
1228 OpsOp->getDef()->getName() != "ins"))
1229 P->error("Operands list should start with '(ops ... '!");
1230
1231 // Copy over the arguments.
1232 Args.clear();
1233 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1234 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1235 static_cast<DefInit*>(OpsList->getArg(j))->
1236 getDef()->getName() != "node")
1237 P->error("Operands list should all be 'node' values.");
1238 if (OpsList->getArgName(j).empty())
1239 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001240 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001241 P->error("'" + OpsList->getArgName(j) +
1242 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001243 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001244 Args.push_back(OpsList->getArgName(j));
1245 }
1246
Chris Lattnerdc32f982008-01-05 22:43:57 +00001247 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001248 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001249 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001250
Chris Lattnerdc32f982008-01-05 22:43:57 +00001251 // If there is a code init for this fragment, keep track of the fact that
1252 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001253 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001254 if (!Code.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001255 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001256
1257 // If there is a node transformation corresponding to this, keep track of
1258 // it.
1259 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1260 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1261 P->getOnlyTree()->setTransformFn(Transform);
1262 }
1263
Chris Lattner6cefb772008-01-05 22:25:12 +00001264 // Now that we've parsed all of the tree fragments, do a closure on them so
1265 // that there are not references to PatFrags left inside of them.
1266 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1267 E = PatternFragments.end(); I != E; ++I) {
1268 TreePattern *ThePat = I->second;
1269 ThePat->InlinePatternFragments();
1270
1271 // Infer as many types as possible. Don't worry about it if we don't infer
1272 // all of them, some may depend on the inputs of the pattern.
1273 try {
1274 ThePat->InferAllTypes();
1275 } catch (...) {
1276 // If this pattern fragment is not supported by this target (no types can
1277 // satisfy its constraints), just ignore it. If the bogus pattern is
1278 // actually used by instructions, the type consistency error will be
1279 // reported there.
1280 }
1281
1282 // If debugging, print out the pattern fragment result.
1283 DEBUG(ThePat->dump());
1284 }
1285}
1286
Chris Lattnerfe718932008-01-06 01:10:31 +00001287void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001288 std::vector<Record*> DefaultOps[2];
1289 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1290 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1291
1292 // Find some SDNode.
1293 assert(!SDNodes.empty() && "No SDNodes parsed?");
1294 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1295
1296 for (unsigned iter = 0; iter != 2; ++iter) {
1297 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1298 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1299
1300 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1301 // SomeSDnode so that we can parse this.
1302 std::vector<std::pair<Init*, std::string> > Ops;
1303 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1304 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1305 DefaultInfo->getArgName(op)));
1306 DagInit *DI = new DagInit(SomeSDNode, Ops);
1307
1308 // Create a TreePattern to parse this.
1309 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1310 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1311
1312 // Copy the operands over into a DAGDefaultOperand.
1313 DAGDefaultOperand DefaultOpInfo;
1314
1315 TreePatternNode *T = P.getTree(0);
1316 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1317 TreePatternNode *TPN = T->getChild(op);
1318 while (TPN->ApplyTypeConstraints(P, false))
1319 /* Resolve all types */;
1320
1321 if (TPN->ContainsUnresolvedType())
1322 if (iter == 0)
1323 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1324 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1325 else
1326 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1327 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1328
1329 DefaultOpInfo.DefaultOps.push_back(TPN);
1330 }
1331
1332 // Insert it into the DefaultOperands map so we can find it later.
1333 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1334 }
1335 }
1336}
1337
1338/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1339/// instruction input. Return true if this is a real use.
1340static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1341 std::map<std::string, TreePatternNode*> &InstInputs,
1342 std::vector<Record*> &InstImpInputs) {
1343 // No name -> not interesting.
1344 if (Pat->getName().empty()) {
1345 if (Pat->isLeaf()) {
1346 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1347 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1348 I->error("Input " + DI->getDef()->getName() + " must be named!");
1349 else if (DI && DI->getDef()->isSubClassOf("Register"))
1350 InstImpInputs.push_back(DI->getDef());
1351 ;
1352 }
1353 return false;
1354 }
1355
1356 Record *Rec;
1357 if (Pat->isLeaf()) {
1358 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1359 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1360 Rec = DI->getDef();
1361 } else {
1362 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1363 Rec = Pat->getOperator();
1364 }
1365
1366 // SRCVALUE nodes are ignored.
1367 if (Rec->getName() == "srcvalue")
1368 return false;
1369
1370 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1371 if (!Slot) {
1372 Slot = Pat;
1373 } else {
1374 Record *SlotRec;
1375 if (Slot->isLeaf()) {
1376 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1377 } else {
1378 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1379 SlotRec = Slot->getOperator();
1380 }
1381
1382 // Ensure that the inputs agree if we've already seen this input.
1383 if (Rec != SlotRec)
1384 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1385 if (Slot->getExtTypes() != Pat->getExtTypes())
1386 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1387 }
1388 return true;
1389}
1390
1391/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1392/// part of "I", the instruction), computing the set of inputs and outputs of
1393/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001394void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001395FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1396 std::map<std::string, TreePatternNode*> &InstInputs,
1397 std::map<std::string, TreePatternNode*>&InstResults,
1398 std::vector<Record*> &InstImpInputs,
1399 std::vector<Record*> &InstImpResults) {
1400 if (Pat->isLeaf()) {
1401 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1402 if (!isUse && Pat->getTransformFn())
1403 I->error("Cannot specify a transform function for a non-input value!");
1404 return;
1405 } else if (Pat->getOperator()->getName() == "implicit") {
1406 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1407 TreePatternNode *Dest = Pat->getChild(i);
1408 if (!Dest->isLeaf())
1409 I->error("implicitly defined value should be a register!");
1410
1411 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1412 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1413 I->error("implicitly defined value should be a register!");
1414 InstImpResults.push_back(Val->getDef());
1415 }
1416 return;
1417 } else if (Pat->getOperator()->getName() != "set") {
1418 // If this is not a set, verify that the children nodes are not void typed,
1419 // and recurse.
1420 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1421 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1422 I->error("Cannot have void nodes inside of patterns!");
1423 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1424 InstImpInputs, InstImpResults);
1425 }
1426
1427 // If this is a non-leaf node with no children, treat it basically as if
1428 // it were a leaf. This handles nodes like (imm).
1429 bool isUse = false;
1430 if (Pat->getNumChildren() == 0)
1431 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1432
1433 if (!isUse && Pat->getTransformFn())
1434 I->error("Cannot specify a transform function for a non-input value!");
1435 return;
1436 }
1437
1438 // Otherwise, this is a set, validate and collect instruction results.
1439 if (Pat->getNumChildren() == 0)
1440 I->error("set requires operands!");
1441
1442 if (Pat->getTransformFn())
1443 I->error("Cannot specify a transform function on a set node!");
1444
1445 // Check the set destinations.
1446 unsigned NumDests = Pat->getNumChildren()-1;
1447 for (unsigned i = 0; i != NumDests; ++i) {
1448 TreePatternNode *Dest = Pat->getChild(i);
1449 if (!Dest->isLeaf())
1450 I->error("set destination should be a register!");
1451
1452 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1453 if (!Val)
1454 I->error("set destination should be a register!");
1455
1456 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1457 Val->getDef()->getName() == "ptr_rc") {
1458 if (Dest->getName().empty())
1459 I->error("set destination must have a name!");
1460 if (InstResults.count(Dest->getName()))
1461 I->error("cannot set '" + Dest->getName() +"' multiple times");
1462 InstResults[Dest->getName()] = Dest;
1463 } else if (Val->getDef()->isSubClassOf("Register")) {
1464 InstImpResults.push_back(Val->getDef());
1465 } else {
1466 I->error("set destination should be a register!");
1467 }
1468 }
1469
1470 // Verify and collect info from the computation.
1471 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1472 InstInputs, InstResults,
1473 InstImpInputs, InstImpResults);
1474}
1475
1476/// ParseInstructions - Parse all of the instructions, inlining and resolving
1477/// any fragments involved. This populates the Instructions list with fully
1478/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001479void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001480 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1481
1482 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1483 ListInit *LI = 0;
1484
1485 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1486 LI = Instrs[i]->getValueAsListInit("Pattern");
1487
1488 // If there is no pattern, only collect minimal information about the
1489 // instruction for its operand list. We have to assume that there is one
1490 // result, as we have no detailed info.
1491 if (!LI || LI->getSize() == 0) {
1492 std::vector<Record*> Results;
1493 std::vector<Record*> Operands;
1494
1495 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1496
1497 if (InstInfo.OperandList.size() != 0) {
1498 if (InstInfo.NumDefs == 0) {
1499 // These produce no results
1500 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1501 Operands.push_back(InstInfo.OperandList[j].Rec);
1502 } else {
1503 // Assume the first operand is the result.
1504 Results.push_back(InstInfo.OperandList[0].Rec);
1505
1506 // The rest are inputs.
1507 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1508 Operands.push_back(InstInfo.OperandList[j].Rec);
1509 }
1510 }
1511
1512 // Create and insert the instruction.
1513 std::vector<Record*> ImpResults;
1514 std::vector<Record*> ImpOperands;
1515 Instructions.insert(std::make_pair(Instrs[i],
1516 DAGInstruction(0, Results, Operands, ImpResults,
1517 ImpOperands)));
1518 continue; // no pattern.
1519 }
1520
1521 // Parse the instruction.
1522 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1523 // Inline pattern fragments into it.
1524 I->InlinePatternFragments();
1525
1526 // Infer as many types as possible. If we cannot infer all of them, we can
1527 // never do anything with this instruction pattern: report it to the user.
1528 if (!I->InferAllTypes())
1529 I->error("Could not infer all types in pattern!");
1530
1531 // InstInputs - Keep track of all of the inputs of the instruction, along
1532 // with the record they are declared as.
1533 std::map<std::string, TreePatternNode*> InstInputs;
1534
1535 // InstResults - Keep track of all the virtual registers that are 'set'
1536 // in the instruction, including what reg class they are.
1537 std::map<std::string, TreePatternNode*> InstResults;
1538
1539 std::vector<Record*> InstImpInputs;
1540 std::vector<Record*> InstImpResults;
1541
1542 // Verify that the top-level forms in the instruction are of void type, and
1543 // fill in the InstResults map.
1544 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1545 TreePatternNode *Pat = I->getTree(j);
1546 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1547 I->error("Top-level forms in instruction pattern should have"
1548 " void types");
1549
1550 // Find inputs and outputs, and verify the structure of the uses/defs.
1551 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1552 InstImpInputs, InstImpResults);
1553 }
1554
1555 // Now that we have inputs and outputs of the pattern, inspect the operands
1556 // list for the instruction. This determines the order that operands are
1557 // added to the machine instruction the node corresponds to.
1558 unsigned NumResults = InstResults.size();
1559
1560 // Parse the operands list from the (ops) list, validating it.
1561 assert(I->getArgList().empty() && "Args list should still be empty here!");
1562 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1563
1564 // Check that all of the results occur first in the list.
1565 std::vector<Record*> Results;
1566 TreePatternNode *Res0Node = NULL;
1567 for (unsigned i = 0; i != NumResults; ++i) {
1568 if (i == CGI.OperandList.size())
1569 I->error("'" + InstResults.begin()->first +
1570 "' set but does not appear in operand list!");
1571 const std::string &OpName = CGI.OperandList[i].Name;
1572
1573 // Check that it exists in InstResults.
1574 TreePatternNode *RNode = InstResults[OpName];
1575 if (RNode == 0)
1576 I->error("Operand $" + OpName + " does not exist in operand list!");
1577
1578 if (i == 0)
1579 Res0Node = RNode;
1580 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1581 if (R == 0)
1582 I->error("Operand $" + OpName + " should be a set destination: all "
1583 "outputs must occur before inputs in operand list!");
1584
1585 if (CGI.OperandList[i].Rec != R)
1586 I->error("Operand $" + OpName + " class mismatch!");
1587
1588 // Remember the return type.
1589 Results.push_back(CGI.OperandList[i].Rec);
1590
1591 // Okay, this one checks out.
1592 InstResults.erase(OpName);
1593 }
1594
1595 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1596 // the copy while we're checking the inputs.
1597 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1598
1599 std::vector<TreePatternNode*> ResultNodeOperands;
1600 std::vector<Record*> Operands;
1601 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1602 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1603 const std::string &OpName = Op.Name;
1604 if (OpName.empty())
1605 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1606
1607 if (!InstInputsCheck.count(OpName)) {
1608 // If this is an predicate operand or optional def operand with an
1609 // DefaultOps set filled in, we can ignore this. When we codegen it,
1610 // we will do so as always executed.
1611 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1612 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1613 // Does it have a non-empty DefaultOps field? If so, ignore this
1614 // operand.
1615 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1616 continue;
1617 }
1618 I->error("Operand $" + OpName +
1619 " does not appear in the instruction pattern");
1620 }
1621 TreePatternNode *InVal = InstInputsCheck[OpName];
1622 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1623
1624 if (InVal->isLeaf() &&
1625 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1626 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1627 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1628 I->error("Operand $" + OpName + "'s register class disagrees"
1629 " between the operand and pattern");
1630 }
1631 Operands.push_back(Op.Rec);
1632
1633 // Construct the result for the dest-pattern operand list.
1634 TreePatternNode *OpNode = InVal->clone();
1635
1636 // No predicate is useful on the result.
1637 OpNode->setPredicateFn("");
1638
1639 // Promote the xform function to be an explicit node if set.
1640 if (Record *Xform = OpNode->getTransformFn()) {
1641 OpNode->setTransformFn(0);
1642 std::vector<TreePatternNode*> Children;
1643 Children.push_back(OpNode);
1644 OpNode = new TreePatternNode(Xform, Children);
1645 }
1646
1647 ResultNodeOperands.push_back(OpNode);
1648 }
1649
1650 if (!InstInputsCheck.empty())
1651 I->error("Input operand $" + InstInputsCheck.begin()->first +
1652 " occurs in pattern but not in operands list!");
1653
1654 TreePatternNode *ResultPattern =
1655 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1656 // Copy fully inferred output node type to instruction result pattern.
1657 if (NumResults > 0)
1658 ResultPattern->setTypes(Res0Node->getExtTypes());
1659
1660 // Create and insert the instruction.
1661 // FIXME: InstImpResults and InstImpInputs should not be part of
1662 // DAGInstruction.
1663 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1664 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1665
1666 // Use a temporary tree pattern to infer all types and make sure that the
1667 // constructed result is correct. This depends on the instruction already
1668 // being inserted into the Instructions map.
1669 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1670 Temp.InferAllTypes();
1671
1672 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1673 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1674
1675 DEBUG(I->dump());
1676 }
1677
1678 // If we can, convert the instructions to be patterns that are matched!
1679 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1680 E = Instructions.end(); II != E; ++II) {
1681 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00001682 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00001683 if (I == 0) continue; // No pattern.
1684
1685 // FIXME: Assume only the first tree is the pattern. The others are clobber
1686 // nodes.
1687 TreePatternNode *Pattern = I->getTree(0);
1688 TreePatternNode *SrcPattern;
1689 if (Pattern->getOperator()->getName() == "set") {
1690 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1691 } else{
1692 // Not a set (store or something?)
1693 SrcPattern = Pattern;
1694 }
1695
1696 std::string Reason;
1697 if (!SrcPattern->canPatternMatch(Reason, *this))
1698 I->error("Instruction can never match: " + Reason);
1699
1700 Record *Instr = II->first;
1701 TreePatternNode *DstPattern = TheInst.getResultPattern();
1702 PatternsToMatch.
1703 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1704 SrcPattern, DstPattern, TheInst.getImpResults(),
1705 Instr->getValueAsInt("AddedComplexity")));
1706 }
1707}
1708
Chris Lattnerfe718932008-01-06 01:10:31 +00001709void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001710 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1711
1712 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1713 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1714 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
1715 Record *Operator = OpDef->getDef();
1716 TreePattern *Pattern;
1717 if (Operator->getName() != "parallel")
1718 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1719 else {
1720 std::vector<Init*> Values;
1721 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
1722 Values.push_back(Tree->getArg(j));
1723 ListInit *LI = new ListInit(Values);
1724 Pattern = new TreePattern(Patterns[i], LI, true, *this);
1725 }
1726
1727 // Inline pattern fragments into it.
1728 Pattern->InlinePatternFragments();
1729
1730 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1731 if (LI->getSize() == 0) continue; // no pattern.
1732
1733 // Parse the instruction.
1734 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1735
1736 // Inline pattern fragments into it.
1737 Result->InlinePatternFragments();
1738
1739 if (Result->getNumTrees() != 1)
1740 Result->error("Cannot handle instructions producing instructions "
1741 "with temporaries yet!");
1742
1743 bool IterateInference;
1744 bool InferredAllPatternTypes, InferredAllResultTypes;
1745 do {
1746 // Infer as many types as possible. If we cannot infer all of them, we
1747 // can never do anything with this pattern: report it to the user.
1748 InferredAllPatternTypes = Pattern->InferAllTypes();
1749
1750 // Infer as many types as possible. If we cannot infer all of them, we
1751 // can never do anything with this pattern: report it to the user.
1752 InferredAllResultTypes = Result->InferAllTypes();
1753
1754 // Apply the type of the result to the source pattern. This helps us
1755 // resolve cases where the input type is known to be a pointer type (which
1756 // is considered resolved), but the result knows it needs to be 32- or
1757 // 64-bits. Infer the other way for good measure.
1758 IterateInference = Pattern->getTree(0)->
1759 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
1760 IterateInference |= Result->getTree(0)->
1761 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
1762 } while (IterateInference);
1763
1764 // Verify that we inferred enough types that we can do something with the
1765 // pattern and result. If these fire the user has to add type casts.
1766 if (!InferredAllPatternTypes)
1767 Pattern->error("Could not infer all types in pattern!");
1768 if (!InferredAllResultTypes)
1769 Result->error("Could not infer all types in pattern result!");
1770
1771 // Validate that the input pattern is correct.
1772 std::map<std::string, TreePatternNode*> InstInputs;
1773 std::map<std::string, TreePatternNode*> InstResults;
1774 std::vector<Record*> InstImpInputs;
1775 std::vector<Record*> InstImpResults;
1776 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
1777 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
1778 InstInputs, InstResults,
1779 InstImpInputs, InstImpResults);
1780
1781 // Promote the xform function to be an explicit node if set.
1782 TreePatternNode *DstPattern = Result->getOnlyTree();
1783 std::vector<TreePatternNode*> ResultNodeOperands;
1784 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1785 TreePatternNode *OpNode = DstPattern->getChild(ii);
1786 if (Record *Xform = OpNode->getTransformFn()) {
1787 OpNode->setTransformFn(0);
1788 std::vector<TreePatternNode*> Children;
1789 Children.push_back(OpNode);
1790 OpNode = new TreePatternNode(Xform, Children);
1791 }
1792 ResultNodeOperands.push_back(OpNode);
1793 }
1794 DstPattern = Result->getOnlyTree();
1795 if (!DstPattern->isLeaf())
1796 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1797 ResultNodeOperands);
1798 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1799 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1800 Temp.InferAllTypes();
1801
1802 std::string Reason;
1803 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
1804 Pattern->error("Pattern can never match: " + Reason);
1805
1806 PatternsToMatch.
1807 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1808 Pattern->getTree(0),
1809 Temp.getOnlyTree(), InstImpResults,
1810 Patterns[i]->getValueAsInt("AddedComplexity")));
1811 }
1812}
1813
1814/// CombineChildVariants - Given a bunch of permutations of each child of the
1815/// 'operator' node, put them together in all possible ways.
1816static void CombineChildVariants(TreePatternNode *Orig,
1817 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1818 std::vector<TreePatternNode*> &OutVariants,
Chris Lattnerfe718932008-01-06 01:10:31 +00001819 CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001820 // Make sure that each operand has at least one variant to choose from.
1821 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1822 if (ChildVariants[i].empty())
1823 return;
1824
1825 // The end result is an all-pairs construction of the resultant pattern.
1826 std::vector<unsigned> Idxs;
1827 Idxs.resize(ChildVariants.size());
1828 bool NotDone = true;
1829 while (NotDone) {
1830 // Create the variant and add it to the output list.
1831 std::vector<TreePatternNode*> NewChildren;
1832 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1833 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1834 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1835
1836 // Copy over properties.
1837 R->setName(Orig->getName());
1838 R->setPredicateFn(Orig->getPredicateFn());
1839 R->setTransformFn(Orig->getTransformFn());
1840 R->setTypes(Orig->getExtTypes());
1841
1842 // If this pattern cannot every match, do not include it as a variant.
1843 std::string ErrString;
1844 if (!R->canPatternMatch(ErrString, CDP)) {
1845 delete R;
1846 } else {
1847 bool AlreadyExists = false;
1848
1849 // Scan to see if this pattern has already been emitted. We can get
1850 // duplication due to things like commuting:
1851 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1852 // which are the same pattern. Ignore the dups.
1853 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1854 if (R->isIsomorphicTo(OutVariants[i])) {
1855 AlreadyExists = true;
1856 break;
1857 }
1858
1859 if (AlreadyExists)
1860 delete R;
1861 else
1862 OutVariants.push_back(R);
1863 }
1864
1865 // Increment indices to the next permutation.
1866 NotDone = false;
1867 // Look for something we can increment without causing a wrap-around.
1868 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1869 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1870 NotDone = true; // Found something to increment.
1871 break;
1872 }
1873 Idxs[IdxsIdx] = 0;
1874 }
1875 }
1876}
1877
1878/// CombineChildVariants - A helper function for binary operators.
1879///
1880static void CombineChildVariants(TreePatternNode *Orig,
1881 const std::vector<TreePatternNode*> &LHS,
1882 const std::vector<TreePatternNode*> &RHS,
1883 std::vector<TreePatternNode*> &OutVariants,
Chris Lattnerfe718932008-01-06 01:10:31 +00001884 CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001885 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1886 ChildVariants.push_back(LHS);
1887 ChildVariants.push_back(RHS);
1888 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP);
1889}
1890
1891
1892static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1893 std::vector<TreePatternNode *> &Children) {
1894 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1895 Record *Operator = N->getOperator();
1896
1897 // Only permit raw nodes.
1898 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1899 N->getTransformFn()) {
1900 Children.push_back(N);
1901 return;
1902 }
1903
1904 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1905 Children.push_back(N->getChild(0));
1906 else
1907 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1908
1909 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1910 Children.push_back(N->getChild(1));
1911 else
1912 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1913}
1914
1915/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1916/// the (potentially recursive) pattern by using algebraic laws.
1917///
1918static void GenerateVariantsOf(TreePatternNode *N,
1919 std::vector<TreePatternNode*> &OutVariants,
Chris Lattnerfe718932008-01-06 01:10:31 +00001920 CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001921 // We cannot permute leaves.
1922 if (N->isLeaf()) {
1923 OutVariants.push_back(N);
1924 return;
1925 }
1926
1927 // Look up interesting info about the node.
1928 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
1929
1930 // If this node is associative, reassociate.
1931 if (NodeInfo.hasProperty(SDNPAssociative)) {
1932 // Reassociate by pulling together all of the linked operators
1933 std::vector<TreePatternNode*> MaximalChildren;
1934 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1935
1936 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1937 // permutations.
1938 if (MaximalChildren.size() == 3) {
1939 // Find the variants of all of our maximal children.
1940 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1941 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP);
1942 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP);
1943 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP);
1944
1945 // There are only two ways we can permute the tree:
1946 // (A op B) op C and A op (B op C)
1947 // Within these forms, we can also permute A/B/C.
1948
1949 // Generate legal pair permutations of A/B/C.
1950 std::vector<TreePatternNode*> ABVariants;
1951 std::vector<TreePatternNode*> BAVariants;
1952 std::vector<TreePatternNode*> ACVariants;
1953 std::vector<TreePatternNode*> CAVariants;
1954 std::vector<TreePatternNode*> BCVariants;
1955 std::vector<TreePatternNode*> CBVariants;
1956 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP);
1957 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP);
1958 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP);
1959 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP);
1960 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP);
1961 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP);
1962
1963 // Combine those into the result: (x op x) op x
1964 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP);
1965 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP);
1966 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP);
1967 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP);
1968 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP);
1969 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP);
1970
1971 // Combine those into the result: x op (x op x)
1972 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP);
1973 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP);
1974 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP);
1975 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP);
1976 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP);
1977 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP);
1978 return;
1979 }
1980 }
1981
1982 // Compute permutations of all children.
1983 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1984 ChildVariants.resize(N->getNumChildren());
1985 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1986 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP);
1987
1988 // Build all permutations based on how the children were formed.
1989 CombineChildVariants(N, ChildVariants, OutVariants, CDP);
1990
1991 // If this node is commutative, consider the commuted order.
1992 if (NodeInfo.hasProperty(SDNPCommutative)) {
1993 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1994 // Don't count children which are actually register references.
1995 unsigned NC = 0;
1996 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1997 TreePatternNode *Child = N->getChild(i);
1998 if (Child->isLeaf())
1999 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2000 Record *RR = DI->getDef();
2001 if (RR->isSubClassOf("Register"))
2002 continue;
2003 }
2004 NC++;
2005 }
2006 // Consider the commuted order.
2007 if (NC == 2)
2008 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2009 OutVariants, CDP);
2010 }
2011}
2012
2013
2014// GenerateVariants - Generate variants. For example, commutative patterns can
2015// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002016void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002017 DOUT << "Generating instruction variants.\n";
2018
2019 // Loop over all of the patterns we've collected, checking to see if we can
2020 // generate variants of the instruction, through the exploitation of
2021 // identities. This permits the target to provide agressive matching without
2022 // the .td file having to contain tons of variants of instructions.
2023 //
2024 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2025 // intentionally do not reconsider these. Any variants of added patterns have
2026 // already been added.
2027 //
2028 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2029 std::vector<TreePatternNode*> Variants;
2030 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
2031
2032 assert(!Variants.empty() && "Must create at least original variant!");
2033 Variants.erase(Variants.begin()); // Remove the original pattern.
2034
2035 if (Variants.empty()) // No variants for this pattern.
2036 continue;
2037
2038 DOUT << "FOUND VARIANTS OF: ";
2039 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2040 DOUT << "\n";
2041
2042 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2043 TreePatternNode *Variant = Variants[v];
2044
2045 DOUT << " VAR#" << v << ": ";
2046 DEBUG(Variant->dump());
2047 DOUT << "\n";
2048
2049 // Scan to see if an instruction or explicit pattern already matches this.
2050 bool AlreadyExists = false;
2051 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2052 // Check to see if this variant already exists.
2053 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
2054 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2055 AlreadyExists = true;
2056 break;
2057 }
2058 }
2059 // If we already have it, ignore the variant.
2060 if (AlreadyExists) continue;
2061
2062 // Otherwise, add it to the list of patterns we have.
2063 PatternsToMatch.
2064 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2065 Variant, PatternsToMatch[i].getDstPattern(),
2066 PatternsToMatch[i].getDstRegs(),
2067 PatternsToMatch[i].getAddedComplexity()));
2068 }
2069
2070 DOUT << "\n";
2071 }
2072}
2073