1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenDAGPatterns.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Streams.h"
24 //===----------------------------------------------------------------------===//
25 // Helpers for working with extended types.
27 /// FilterVTs - Filter a list of VT's according to a predicate.
30 static std::vector
<MVT::ValueType
>
31 FilterVTs(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
)
35 Result
.push_back(InVTs
[i
]);
40 static std::vector
<unsigned char>
41 FilterEVTs(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
]);
49 static std::vector
<unsigned char>
50 ConvertVTs(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
]);
57 static 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())
66 /// isExtIntegerVT - Return true if the specified extended value type vector
67 /// contains isInt or an integer value type.
70 bool 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());
75 /// isExtFloatingPointVT - Return true if the specified extended value type
76 /// vector contains isFP or a FP value type.
77 bool 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());
81 } // end namespace MVT.
82 } // end namespace llvm.
84 //===----------------------------------------------------------------------===//
85 // SDTypeConstraint implementation
88 SDTypeConstraint::SDTypeConstraint(Record
*R
) {
89 OperandNo
= R
->getValueAsInt("OperandNum");
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");
116 cerr
<< "Unrecognized SDTypeConstraint '" << R
->getName() << "'!\n";
121 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
122 /// N, which has NumResults results.
123 TreePatternNode
*SDTypeConstraint::getOperandNum(unsigned OpNo
,
125 unsigned NumResults
) const {
126 assert(NumResults
<= 1 &&
127 "We only work with nodes with zero or one result so far!");
129 if (OpNo
>= (NumResults
+ N
->getNumChildren())) {
130 cerr
<< "Invalid operand number " << OpNo
<< " ";
136 if (OpNo
< NumResults
)
137 return N
; // FIXME: need value #
139 return N
->getChild(OpNo
-NumResults
);
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
146 bool 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!");
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!");
160 const CodeGenTarget
&CGT
= TP
.getDAGPatterns().getTargetInfo();
162 TreePatternNode
*NodeToApply
= getOperandNum(OperandNo
, N
, NumResults
);
164 switch (ConstraintType
) {
165 default: assert(0 && "Unknown constraint type!");
167 // Operand must be a particular type.
168 return NodeToApply
->UpdateNodeType(x
.SDTCisVT_Info
.VT
, TP
);
170 // Operand must be same as target pointer type.
171 return NodeToApply
->UpdateNodeType(MVT::iPTR
, TP
);
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
);
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
);
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
);
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
);
194 TreePatternNode
*OtherNode
=
195 getOperandNum(x
.SDTCisSameAs_Info
.OtherOperandNum
, N
, NumResults
);
196 return NodeToApply
->UpdateNodeType(OtherNode
->getExtTypes(), TP
) |
197 OtherNode
->UpdateNodeType(NodeToApply
->getExtTypes(), TP
);
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!");
208 getValueType(static_cast<DefInit
*>(NodeToApply
->getLeafValue())->getDef());
209 if (!MVT::isInteger(VT
))
210 TP
.error(N
->getOperator()->getName() + " VT operand must be integer!");
212 TreePatternNode
*OtherNode
=
213 getOperandNum(x
.SDTCisVTSmallerThanOp_Info
.OtherOperandNum
, N
,NumResults
);
215 // It must be integer.
216 bool MadeChange
= false;
217 MadeChange
|= OtherNode
->UpdateNodeType(MVT::isInt
, TP
);
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.
227 case SDTCisOpSmallerThanOp
: {
228 TreePatternNode
*BigOperand
=
229 getOperandNum(x
.SDTCisOpSmallerThanOp_Info
.BigOperandNum
, N
, NumResults
);
231 // Both operands must be integer or FP, but we don't care which.
232 bool MadeChange
= false;
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
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
);
251 std::vector
<MVT::ValueType
> VTs
= CGT
.getLegalValueTypes();
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
);
261 switch (VTs
.size()) {
262 default: // Too many VT's to pick from.
263 case 0: break; // No info yet.
265 // Only one VT of this flavor. Cannot ever satisify the constraints.
266 return NodeToApply
->UpdateNodeType(MVT::Other
, TP
); // throw
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
);
278 case SDTCisIntVectorOfSameSize
: {
279 TreePatternNode
*OtherOperand
=
280 getOperandNum(x
.SDTCisIntVectorOfSameSize_Info
.OtherOperandNum
,
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
);
295 //===----------------------------------------------------------------------===//
296 // SDNodeInfo implementation
298 SDNodeInfo::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");
305 // Parse the properties.
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
;
321 } else if (PropList
[i
]->getName() == "SDNPMayStore") {
322 Properties
|= 1 << SDNPMayStore
;
323 } else if (PropList
[i
]->getName() == "SDNPMayLoad") {
324 Properties
|= 1 << SDNPMayLoad
;
325 } else if (PropList
[i
]->getName() == "SDNPSideEffect") {
326 Properties
|= 1 << SDNPSideEffect
;
328 cerr
<< "Unknown SD Node property '" << PropList
[i
]->getName()
329 << "' on node '" << R
->getName() << "'!\n";
335 // Parse the type constraints.
336 std::vector
<Record
*> ConstraintList
=
337 TypeProfile
->getValueAsListOfDefs("Constraints");
338 TypeConstraints
.assign(ConstraintList
.begin(), ConstraintList
.end());
341 //===----------------------------------------------------------------------===//
342 // TreePatternNode implementation
345 TreePatternNode::~TreePatternNode() {
346 #if 0 // FIXME: implement refcounted tree nodes!
347 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
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.
356 bool TreePatternNode::UpdateNodeType(const std::vector
<unsigned char> &ExtVTs
,
358 assert(!ExtVTs
.empty() && "Cannot update node type with empty type vector!");
360 if (ExtVTs
[0] == MVT::isUnknown
|| LHSIsSubsetOfRHS(getExtTypes(), ExtVTs
))
362 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs
, getExtTypes())) {
367 if (getExtTypeNum(0) == MVT::iPTR
) {
368 if (ExtVTs
[0] == MVT::iPTR
|| ExtVTs
[0] == MVT::isInt
)
370 if (MVT::isExtIntegerInVTs(ExtVTs
)) {
371 std::vector
<unsigned char> FVTs
= FilterEVTs(ExtVTs
, MVT::isInteger
);
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
)
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
)
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
)
407 // If we know this is an int or fp type, and we are told it is a specific one,
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
))){
417 if (getExtTypeNum(0) == MVT::isInt
&& ExtVTs
[0] == MVT::iPTR
) {
425 TP
.error("Type inference contradiction found in node!");
427 TP
.error("Type inference contradiction found in node " +
428 getOperator()->getName() + "!");
430 return true; // unreachable
434 void TreePatternNode::print(std::ostream
&OS
) const {
436 OS
<< *getLeafValue();
438 OS
<< "(" << getOperator()->getName();
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;
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);
460 if (getNumChildren() != 0) {
462 getChild(0)->print(OS
);
463 for (unsigned i
= 1, e
= getNumChildren(); i
!= e
; ++i
) {
465 getChild(i
)->print(OS
);
471 if (!PredicateFn
.empty())
472 OS
<< "<<P:" << PredicateFn
<< ">>";
474 OS
<< "<<X:" << TransformFn
->getName() << ">>";
475 if (!getName().empty())
476 OS
<< ":$" << getName();
479 void TreePatternNode::dump() const {
480 print(*cerr
.stream());
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.
487 bool 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())
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();
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
)))
509 /// clone - Make a copy of this tree and all of its children.
511 TreePatternNode
*TreePatternNode::clone() const {
512 TreePatternNode
*New
;
514 New
= new TreePatternNode(getLeafValue());
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
);
522 New
->setName(getName());
523 New
->setTypes(getExtTypes());
524 New
->setPredicateFn(getPredicateFn());
525 New
->setTransformFn(getTransformFn());
529 /// SubstituteFormalArguments - Replace the formal arguments in this tree
530 /// with actual values specified by ArgMap.
531 void TreePatternNode::
532 SubstituteFormalArguments(std::map
<std::string
, TreePatternNode
*> &ArgMap
) {
533 if (isLeaf()) return;
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!");
547 getChild(i
)->SubstituteFormalArguments(ArgMap
);
553 /// InlinePatternFragments - If this pattern refers to any pattern
554 /// fragments, inline them into place, giving us a pattern without any
555 /// PatFrag references.
556 TreePatternNode
*TreePatternNode::InlinePatternFragments(TreePattern
&TP
) {
557 if (isLeaf()) return this; // nothing to do.
558 Record
*Op
= getOperator();
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
));
567 // Otherwise, we found a reference to a fragment. First, look up its
568 // TreePattern record.
569 TreePattern
*Frag
= TP
.getDAGPatterns().getPatternFragment(Op
);
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!");
576 TreePatternNode
*FragTree
= Frag
->getOnlyTree()->clone();
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
);
585 FragTree
->SubstituteFormalArguments(ArgMap
);
588 FragTree
->setName(getName());
589 FragTree
->UpdateNodeType(getExtTypes(), TP
);
591 // Get a new copy of this fragment to stitch into here.
592 //delete this; // FIXME: implement refcounting!
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.
600 static std::vector
<unsigned char> getImplicitType(Record
*R
, bool NotRegisters
,
602 // Some common return values
603 std::vector
<unsigned char> Unknown(1, MVT::isUnknown
);
604 std::vector
<unsigned char> Other(1, MVT::Other
);
606 // Check to see if this is a register or a register class...
607 if (R
->isSubClassOf("RegisterClass")) {
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.
616 } else if (R
->isSubClassOf("Register")) {
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.
624 } else if (R
->isSubClassOf("ComplexPattern")) {
627 std::vector
<unsigned char>
628 ComplexPat(1, TP
.getDAGPatterns().getComplexPattern(R
).getValueType());
630 } else if (R
->getName() == "ptr_rc") {
631 Other
[0] = MVT::iPTR
;
633 } else if (R
->getName() == "node" || R
->getName() == "srcvalue" ||
634 R
->getName() == "zero_reg") {
639 TP
.error("Unknown node flavor used in pattern: " + R
->getName());
644 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
645 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
646 const CodeGenIntrinsic
*TreePatternNode::
647 getIntrinsicInfo(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())
654 dynamic_cast<IntInit
*>(getChild(0)->getLeafValue())->getValue();
655 return &CDP
.getIntrinsicInfo(IID
);
659 /// 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
663 bool TreePatternNode::ApplyTypeConstraints(TreePattern
&TP
, bool NotRegisters
) {
664 CodeGenDAGPatterns
&CDP
= TP
.getDAGPatterns();
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
);
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!");
683 if (VT
!= MVT::iPTR
) {
684 unsigned Size
= MVT::getSizeInBits(VT
);
685 // Make sure that the value is representable for this type.
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)) + "'!");
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
);
710 // Types of operands must match.
711 MadeChange
|= getChild(i
)->UpdateNodeType(getChild(NC
-1)->getExtTypes(),
713 MadeChange
|= getChild(NC
-1)->UpdateNodeType(getChild(i
)->getExtTypes(),
715 MadeChange
|= UpdateNodeType(MVT::isVoid
, TP
);
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
);
725 } else if (const CodeGenIntrinsic
*Int
= getIntrinsicInfo(CDP
)) {
726 bool MadeChange
= false;
728 // Apply the result type to the node.
729 MadeChange
= UpdateNodeType(Int
->ArgVTs
[0], TP
);
731 if (getNumChildren() != Int
->ArgVTs
.size())
732 TP
.error("Intrinsic '" + Int
->Name
+ "' expects " +
733 utostr(Int
->ArgVTs
.size()-1) + " operands, not " +
734 utostr(getNumChildren()-1) + " operands!");
736 // Apply type info to the intrinsic ID.
737 MadeChange
|= getChild(0)->UpdateNodeType(MVT::iPTR
, TP
);
739 for (unsigned i
= 1, e
= getNumChildren(); i
!= e
; ++i
) {
740 MVT::ValueType OpVT
= Int
->ArgVTs
[i
];
741 MadeChange
|= getChild(i
)->UpdateNodeType(OpVT
, TP
);
742 MadeChange
|= getChild(i
)->ApplyTypeConstraints(TP
, NotRegisters
);
745 } else if (getOperator()->isSubClassOf("SDNode")) {
746 const SDNodeInfo
&NI
= CDP
.getSDNodeInfo(getOperator());
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
);
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
];
770 assert(LegalIntVT
!= MVT::Other
&& "No legal integer VT?");
772 for (unsigned i
= 0, e
= BV
->getNumChildren(); i
!= e
; ++i
)
773 MadeChange
|= BV
->getChild(i
)->UpdateNodeType(LegalIntVT
, TP
);
776 } else if (getOperator()->isSubClassOf("Instruction")) {
777 const DAGInstruction
&Inst
= CDP
.getInstruction(getOperator());
778 bool MadeChange
= false;
779 unsigned NumResults
= Inst
.getNumResults();
781 assert(NumResults
<= 1 &&
782 "Only supports zero or one result instrs!");
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
);
790 Record
*ResultNode
= Inst
.getResult(0);
792 if (ResultNode
->getName() == "ptr_rc") {
793 std::vector
<unsigned char> VT
;
794 VT
.push_back(MVT::iPTR
);
795 MadeChange
= UpdateNodeType(VT
, TP
);
797 assert(ResultNode
->isSubClassOf("RegisterClass") &&
798 "Operands should be register classes!");
800 const CodeGenRegisterClass
&RC
=
801 CDP
.getTargetInfo().getRegisterClass(ResultNode
);
802 MadeChange
= UpdateNodeType(ConvertVTs(RC
.getValueTypes()), TP
);
806 unsigned ChildNo
= 0;
807 for (unsigned i
= 0, e
= Inst
.getNumOperands(); i
!= e
; ++i
) {
808 Record
*OperandNode
= Inst
.getOperand(i
);
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())
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.");
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
);
835 assert(0 && "Unknown operand type!");
838 MadeChange
|= Child
->ApplyTypeConstraints(TP
, NotRegisters
);
841 if (ChildNo
!= getNumChildren())
842 TP
.error("Instruction '" + getOperator()->getName() +
843 "' was provided too many operands!");
847 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
849 // Node transforms always take one operand.
850 if (getNumChildren() != 1)
851 TP
.error("Node transform '" + getOperator()->getName() +
852 "' requires one operand!");
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
);
866 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
867 /// RHS of a commutative operation, not the on LHS.
868 static bool OnlyOnRHSOfCommutative(TreePatternNode
*N
) {
869 if (!N
->isLeaf() && N
->getOperator()->getName() == "imm")
871 if (N
->isLeaf() && dynamic_cast<IntInit
*>(N
->getLeafValue()))
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.
882 bool TreePatternNode::canPatternMatch(std::string
&Reason
,
883 CodeGenDAGPatterns
&CDP
){
884 if (isLeaf()) return true;
886 for (unsigned i
= 0, e
= getNumChildren(); i
!= e
; ++i
)
887 if (!getChild(i
)->canPatternMatch(Reason
, CDP
))
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")) {
897 // If this node is a commutative operator, check that the LHS isn't an
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!";
915 //===----------------------------------------------------------------------===//
916 // TreePattern implementation
919 TreePattern::TreePattern(Record
*TheRec
, ListInit
*RawPat
, bool isInput
,
920 CodeGenDAGPatterns
&cdp
) : TheRecord(TheRec
), CDP(cdp
){
921 isInputPattern
= isInput
;
922 for (unsigned i
= 0, e
= RawPat
->getSize(); i
!= e
; ++i
)
923 Trees
.push_back(ParseTreePattern((DagInit
*)RawPat
->getElement(i
)));
926 TreePattern::TreePattern(Record
*TheRec
, DagInit
*Pat
, bool isInput
,
927 CodeGenDAGPatterns
&cdp
) : TheRecord(TheRec
), CDP(cdp
){
928 isInputPattern
= isInput
;
929 Trees
.push_back(ParseTreePattern(Pat
));
932 TreePattern::TreePattern(Record
*TheRec
, TreePatternNode
*Pat
, bool isInput
,
933 CodeGenDAGPatterns
&cdp
) : TheRecord(TheRec
), CDP(cdp
){
934 isInputPattern
= isInput
;
935 Trees
.push_back(Pat
);
940 void TreePattern::error(const std::string
&Msg
) const {
942 throw "In " + TheRecord
->getName() + ": " + Msg
;
945 TreePatternNode
*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();
950 if (Operator
->isSubClassOf("ValueType")) {
951 // If the operator is a ValueType, then this must be "type cast" of a leaf
953 if (Dag
->getNumArgs() != 1)
954 error("Type cast only takes one operand!");
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
);
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!");
978 New
= new TreePatternNode(dynamic_cast<IntInit
*>(II
));
979 if (!Dag
->getArgName(0).empty())
980 error("Constant int argument should not have a name!");
983 error("Unknown leaf value for tree pattern!");
987 // Apply the type cast.
988 New
->UpdateNodeType(getValueType(Operator
), *this);
989 New
->setName(Dag
->getArgName(0));
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() + "'!");
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!");
1008 std::vector
<TreePatternNode
*> Children
;
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...
1025 TreePatternNode
*Node
= new TreePatternNode(DefI
);
1026 Node
->setName(Dag
->getArgName(i
));
1027 Children
.push_back(Node
);
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
));
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!");
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
);
1055 error("Unknown leaf value for tree pattern!");
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;
1066 // If this intrinsic returns void, it must have side-effects and thus a
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();
1074 // Otherwise, no chain.
1075 Operator
= getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1078 TreePatternNode
*IIDNode
= new TreePatternNode(new IntInit(IID
));
1079 Children
.insert(Children
.begin(), IIDNode
);
1082 return new TreePatternNode(Operator
, Children
);
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.
1088 bool TreePattern::InferAllTypes() {
1089 bool MadeChange
= true;
1090 while (MadeChange
) {
1092 for (unsigned i
= 0, e
= Trees
.size(); i
!= e
; ++i
)
1093 MadeChange
|= Trees
[i
]->ApplyTypeConstraints(*this, false);
1096 bool HasUnresolvedTypes
= false;
1097 for (unsigned i
= 0, e
= Trees
.size(); i
!= e
; ++i
)
1098 HasUnresolvedTypes
|= Trees
[i
]->ContainsUnresolvedType();
1099 return !HasUnresolvedTypes
;
1102 void 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
];
1112 if (Trees
.size() > 1)
1114 for (unsigned i
= 0, e
= Trees
.size(); i
!= e
; ++i
) {
1116 Trees
[i
]->print(OS
);
1120 if (Trees
.size() > 1)
1124 void TreePattern::dump() const { print(*cerr
.stream()); }
1126 //===----------------------------------------------------------------------===//
1127 // CodeGenDAGPatterns implementation
1130 // FIXME: REMOVE OSTREAM ARGUMENT
1131 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper
&R
) : Records(R
) {
1132 Intrinsics
= LoadIntrinsics(Records
);
1134 ParseNodeTransforms();
1135 ParseComplexPatterns();
1136 ParsePatternFragments();
1137 ParseDefaultOperands();
1138 ParseInstructions();
1141 // Generate variants. For example, commutative patterns can match
1142 // multiple ways. Add them to PatternsToMatch as well.
1146 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1147 for (std::map
<Record
*, TreePattern
*>::iterator I
= PatternFragments
.begin(),
1148 E
= PatternFragments
.end(); I
!= E
; ++I
)
1153 Record
*CodeGenDAGPatterns::getSDNodeNamed(const std::string
&Name
) const {
1154 Record
*N
= Records
.getDef(Name
);
1155 if (!N
|| !N
->isSubClassOf("SDNode")) {
1156 cerr
<< "Error getting SDNode '" << Name
<< "'!\n";
1162 // Parse all of the SDNode definitions for the target, populating SDNodes.
1163 void CodeGenDAGPatterns::ParseNodeInfo() {
1164 std::vector
<Record
*> Nodes
= Records
.getAllDerivedDefinitions("SDNode");
1165 while (!Nodes
.empty()) {
1166 SDNodes
.insert(std::make_pair(Nodes
.back(), Nodes
.back()));
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");
1176 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1177 /// map, and emit them to the file as functions.
1178 void CodeGenDAGPatterns::ParseNodeTransforms() {
1179 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");
1184 SDNodeXForms
.insert(std::make_pair(XFormNode
, NodeXForm(SDNode
, Code
)));
1190 void CodeGenDAGPatterns::ParseComplexPatterns() {
1191 std::vector
<Record
*> AMs
= Records
.getAllDerivedDefinitions("ComplexPattern");
1192 while (!AMs
.empty()) {
1193 ComplexPatterns
.insert(std::make_pair(AMs
.back(), AMs
.back()));
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.
1204 void CodeGenDAGPatterns::ParsePatternFragments() {
1205 std::vector
<Record
*> Fragments
= Records
.getAllDerivedDefinitions("PatFrag");
1207 // First step, parse all of the fragments.
1208 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
;
1213 // Validate the argument list, converting it to set, to discard duplicates.
1214 std::vector
<std::string
> &Args
= P
->getArgList();
1215 std::set
<std::string
> OperandsSet(Args
.begin(), Args
.end());
1217 if (OperandsSet
.count(""))
1218 P
->error("Cannot have unnamed 'node' values in pattern fragment!");
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.
1226 (OpsOp
->getDef()->getName() != "ops" &&
1227 OpsOp
->getDef()->getName() != "outs" &&
1228 OpsOp
->getDef()->getName() != "ins"))
1229 P
->error("Operands list should start with '(ops ... '!");
1231 // Copy over the arguments.
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!");
1240 if (!OperandsSet
.count(OpsList
->getArgName(j
)))
1241 P
->error("'" + OpsList
->getArgName(j
) +
1242 "' does not occur in pattern or was multiply specified!");
1243 OperandsSet
.erase(OpsList
->getArgName(j
));
1244 Args
.push_back(OpsList
->getArgName(j
));
1247 if (!OperandsSet
.empty())
1248 P
->error("Operands list does not contain an entry for operand '" +
1249 *OperandsSet
.begin() + "'!");
1251 // If there is a code init for this fragment, keep track of the fact that
1252 // this fragment uses it.
1253 std::string Code
= Fragments
[i
]->getValueAsCode("Predicate");
1255 P
->getOnlyTree()->setPredicateFn("Predicate_"+Fragments
[i
]->getName());
1257 // If there is a node transformation corresponding to this, keep track of
1259 Record
*Transform
= Fragments
[i
]->getValueAsDef("OperandTransform");
1260 if (!getSDNodeTransform(Transform
).second
.empty()) // not noop xform?
1261 P
->getOnlyTree()->setTransformFn(Transform
);
1264 // 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();
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.
1274 ThePat
->InferAllTypes();
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
1282 // If debugging, print out the pattern fragment result.
1283 DEBUG(ThePat
->dump());
1287 void CodeGenDAGPatterns::ParseDefaultOperands() {
1288 std::vector
<Record
*> DefaultOps
[2];
1289 DefaultOps
[0] = Records
.getAllDerivedDefinitions("PredicateOperand");
1290 DefaultOps
[1] = Records
.getAllDerivedDefinitions("OptionalDefOperand");
1292 // Find some SDNode.
1293 assert(!SDNodes
.empty() && "No SDNodes parsed?");
1294 Init
*SomeSDNode
= new DefInit(SDNodes
.begin()->first
);
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");
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
);
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!");
1312 // Copy the operands over into a DAGDefaultOperand.
1313 DAGDefaultOperand DefaultOpInfo
;
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 */;
1321 if (TPN
->ContainsUnresolvedType())
1323 throw "Value #" + utostr(i
) + " of PredicateOperand '" +
1324 DefaultOps
[iter
][i
]->getName() + "' doesn't have a concrete type!";
1326 throw "Value #" + utostr(i
) + " of OptionalDefOperand '" +
1327 DefaultOps
[iter
][i
]->getName() + "' doesn't have a concrete type!";
1329 DefaultOpInfo
.DefaultOps
.push_back(TPN
);
1332 // Insert it into the DefaultOperands map so we can find it later.
1333 DefaultOperands
[DefaultOps
[iter
][i
]] = DefaultOpInfo
;
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.
1340 static 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());
1357 if (Pat
->isLeaf()) {
1358 DefInit
*DI
= dynamic_cast<DefInit
*>(Pat
->getLeafValue());
1359 if (!DI
) I
->error("Input $" + Pat
->getName() + " must be an identifier!");
1362 assert(Pat
->getNumChildren() == 0 && "can't be a use with children!");
1363 Rec
= Pat
->getOperator();
1366 // SRCVALUE nodes are ignored.
1367 if (Rec
->getName() == "srcvalue")
1370 TreePatternNode
*&Slot
= InstInputs
[Pat
->getName()];
1375 if (Slot
->isLeaf()) {
1376 SlotRec
= dynamic_cast<DefInit
*>(Slot
->getLeafValue())->getDef();
1378 assert(Slot
->getNumChildren() == 0 && "can't be a use with children!");
1379 SlotRec
= Slot
->getOperator();
1382 // Ensure that the inputs agree if we've already seen this input.
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");
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.
1394 void CodeGenDAGPatterns::
1395 FindPatternInputsAndOutputs(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!");
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!");
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());
1417 } else if (Pat
->getOperator()->getName() != "set") {
1418 // If this is not a set, verify that the children nodes are not void typed,
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
);
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).
1430 if (Pat
->getNumChildren() == 0)
1431 isUse
= HandleUse(I
, Pat
, InstInputs
, InstImpInputs
);
1433 if (!isUse
&& Pat
->getTransformFn())
1434 I
->error("Cannot specify a transform function for a non-input value!");
1438 // Otherwise, this is a set, validate and collect instruction results.
1439 if (Pat
->getNumChildren() == 0)
1440 I
->error("set requires operands!");
1442 if (Pat
->getTransformFn())
1443 I
->error("Cannot specify a transform function on a set node!");
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!");
1452 DefInit
*Val
= dynamic_cast<DefInit
*>(Dest
->getLeafValue());
1454 I
->error("set destination should be a register!");
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());
1466 I
->error("set destination should be a register!");
1470 // Verify and collect info from the computation.
1471 FindPatternInputsAndOutputs(I
, Pat
->getChild(NumDests
),
1472 InstInputs
, InstResults
,
1473 InstImpInputs
, InstImpResults
);
1476 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1477 /// any fragments involved. This populates the Instructions list with fully
1478 /// resolved instructions.
1479 void CodeGenDAGPatterns::ParseInstructions() {
1480 std::vector
<Record
*> Instrs
= Records
.getAllDerivedDefinitions("Instruction");
1482 for (unsigned i
= 0, e
= Instrs
.size(); i
!= e
; ++i
) {
1485 if (dynamic_cast<ListInit
*>(Instrs
[i
]->getValueInit("Pattern")))
1486 LI
= Instrs
[i
]->getValueAsListInit("Pattern");
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
;
1495 CodeGenInstruction
&InstInfo
=Target
.getInstruction(Instrs
[i
]->getName());
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
);
1503 // Assume the first operand is the result.
1504 Results
.push_back(InstInfo
.OperandList
[0].Rec
);
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
);
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
,
1518 continue; // no pattern.
1521 // Parse the instruction.
1522 TreePattern
*I
= new TreePattern(Instrs
[i
], LI
, true, *this);
1523 // Inline pattern fragments into it.
1524 I
->InlinePatternFragments();
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!");
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
;
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
;
1539 std::vector
<Record
*> InstImpInputs
;
1540 std::vector
<Record
*> InstImpResults
;
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"
1550 // Find inputs and outputs, and verify the structure of the uses/defs.
1551 FindPatternInputsAndOutputs(I
, Pat
, InstInputs
, InstResults
,
1552 InstImpInputs
, InstImpResults
);
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();
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());
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
;
1573 // Check that it exists in InstResults.
1574 TreePatternNode
*RNode
= InstResults
[OpName
];
1576 I
->error("Operand $" + OpName
+ " does not exist in operand list!");
1580 Record
*R
= dynamic_cast<DefInit
*>(RNode
->getLeafValue())->getDef();
1582 I
->error("Operand $" + OpName
+ " should be a set destination: all "
1583 "outputs must occur before inputs in operand list!");
1585 if (CGI
.OperandList
[i
].Rec
!= R
)
1586 I
->error("Operand $" + OpName
+ " class mismatch!");
1588 // Remember the return type.
1589 Results
.push_back(CGI
.OperandList
[i
].Rec
);
1591 // Okay, this one checks out.
1592 InstResults
.erase(OpName
);
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
);
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
;
1605 I
->error("Operand #" + utostr(i
) + " in operands list has no name!");
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
1615 if (!getDefaultOperand(Op
.Rec
).DefaultOps
.empty())
1618 I
->error("Operand $" + OpName
+
1619 " does not appear in the instruction pattern");
1621 TreePatternNode
*InVal
= InstInputsCheck
[OpName
];
1622 InstInputsCheck
.erase(OpName
); // It occurred, remove from map.
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");
1631 Operands
.push_back(Op
.Rec
);
1633 // Construct the result for the dest-pattern operand list.
1634 TreePatternNode
*OpNode
= InVal
->clone();
1636 // No predicate is useful on the result.
1637 OpNode
->setPredicateFn("");
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
);
1647 ResultNodeOperands
.push_back(OpNode
);
1650 if (!InstInputsCheck
.empty())
1651 I
->error("Input operand $" + InstInputsCheck
.begin()->first
+
1652 " occurs in pattern but not in operands list!");
1654 TreePatternNode
*ResultPattern
=
1655 new TreePatternNode(I
->getRecord(), ResultNodeOperands
);
1656 // Copy fully inferred output node type to instruction result pattern.
1658 ResultPattern
->setTypes(Res0Node
->getExtTypes());
1660 // Create and insert the instruction.
1661 // FIXME: InstImpResults and InstImpInputs should not be part of
1663 DAGInstruction
TheInst(I
, Results
, Operands
, InstImpResults
, InstImpInputs
);
1664 Instructions
.insert(std::make_pair(I
->getRecord(), TheInst
));
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();
1672 DAGInstruction
&TheInsertedInst
= Instructions
.find(I
->getRecord())->second
;
1673 TheInsertedInst
.setResultPattern(Temp
.getOnlyTree());
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
;
1682 const TreePattern
*I
= TheInst
.getPattern();
1683 if (I
== 0) continue; // No pattern.
1685 // FIXME: Assume only the first tree is the pattern. The others are clobber
1687 TreePatternNode
*Pattern
= I
->getTree(0);
1688 TreePatternNode
*SrcPattern
;
1689 if (Pattern
->getOperator()->getName() == "set") {
1690 SrcPattern
= Pattern
->getChild(Pattern
->getNumChildren()-1)->clone();
1692 // Not a set (store or something?)
1693 SrcPattern
= Pattern
;
1697 if (!SrcPattern
->canPatternMatch(Reason
, *this))
1698 I
->error("Instruction can never match: " + Reason
);
1700 Record
*Instr
= II
->first
;
1701 TreePatternNode
*DstPattern
= TheInst
.getResultPattern();
1703 push_back(PatternToMatch(Instr
->getValueAsListInit("Predicates"),
1704 SrcPattern
, DstPattern
, TheInst
.getImpResults(),
1705 Instr
->getValueAsInt("AddedComplexity")));
1709 void CodeGenDAGPatterns::ParsePatterns() {
1710 std::vector
<Record
*> Patterns
= Records
.getAllDerivedDefinitions("Pattern");
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);
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);
1727 // Inline pattern fragments into it.
1728 Pattern
->InlinePatternFragments();
1730 ListInit
*LI
= Patterns
[i
]->getValueAsListInit("ResultInstrs");
1731 if (LI
->getSize() == 0) continue; // no pattern.
1733 // Parse the instruction.
1734 TreePattern
*Result
= new TreePattern(Patterns
[i
], LI
, false, *this);
1736 // Inline pattern fragments into it.
1737 Result
->InlinePatternFragments();
1739 if (Result
->getNumTrees() != 1)
1740 Result
->error("Cannot handle instructions producing instructions "
1741 "with temporaries yet!");
1743 bool IterateInference
;
1744 bool InferredAllPatternTypes
, InferredAllResultTypes
;
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();
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();
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
);
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!");
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
);
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
);
1792 ResultNodeOperands
.push_back(OpNode
);
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();
1803 if (!Pattern
->getTree(0)->canPatternMatch(Reason
, *this))
1804 Pattern
->error("Pattern can never match: " + Reason
);
1807 push_back(PatternToMatch(Patterns
[i
]->getValueAsListInit("Predicates"),
1808 Pattern
->getTree(0),
1809 Temp
.getOnlyTree(), InstImpResults
,
1810 Patterns
[i
]->getValueAsInt("AddedComplexity")));
1814 /// CombineChildVariants - Given a bunch of permutations of each child of the
1815 /// 'operator' node, put them together in all possible ways.
1816 static void CombineChildVariants(TreePatternNode
*Orig
,
1817 const std::vector
<std::vector
<TreePatternNode
*> > &ChildVariants
,
1818 std::vector
<TreePatternNode
*> &OutVariants
,
1819 CodeGenDAGPatterns
&CDP
) {
1820 // 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())
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;
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
);
1836 // Copy over properties.
1837 R
->setName(Orig
->getName());
1838 R
->setPredicateFn(Orig
->getPredicateFn());
1839 R
->setTransformFn(Orig
->getTransformFn());
1840 R
->setTypes(Orig
->getExtTypes());
1842 // If this pattern cannot every match, do not include it as a variant.
1843 std::string ErrString
;
1844 if (!R
->canPatternMatch(ErrString
, CDP
)) {
1847 bool AlreadyExists
= false;
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;
1862 OutVariants
.push_back(R
);
1865 // Increment indices to the next permutation.
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.
1878 /// CombineChildVariants - A helper function for binary operators.
1880 static void CombineChildVariants(TreePatternNode
*Orig
,
1881 const std::vector
<TreePatternNode
*> &LHS
,
1882 const std::vector
<TreePatternNode
*> &RHS
,
1883 std::vector
<TreePatternNode
*> &OutVariants
,
1884 CodeGenDAGPatterns
&CDP
) {
1885 std::vector
<std::vector
<TreePatternNode
*> > ChildVariants
;
1886 ChildVariants
.push_back(LHS
);
1887 ChildVariants
.push_back(RHS
);
1888 CombineChildVariants(Orig
, ChildVariants
, OutVariants
, CDP
);
1892 static 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();
1897 // Only permit raw nodes.
1898 if (!N
->getName().empty() || !N
->getPredicateFn().empty() ||
1899 N
->getTransformFn()) {
1900 Children
.push_back(N
);
1904 if (N
->getChild(0)->isLeaf() || N
->getChild(0)->getOperator() != Operator
)
1905 Children
.push_back(N
->getChild(0));
1907 GatherChildrenOfAssociativeOpcode(N
->getChild(0), Children
);
1909 if (N
->getChild(1)->isLeaf() || N
->getChild(1)->getOperator() != Operator
)
1910 Children
.push_back(N
->getChild(1));
1912 GatherChildrenOfAssociativeOpcode(N
->getChild(1), Children
);
1915 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1916 /// the (potentially recursive) pattern by using algebraic laws.
1918 static void GenerateVariantsOf(TreePatternNode
*N
,
1919 std::vector
<TreePatternNode
*> &OutVariants
,
1920 CodeGenDAGPatterns
&CDP
) {
1921 // We cannot permute leaves.
1923 OutVariants
.push_back(N
);
1927 // Look up interesting info about the node.
1928 const SDNodeInfo
&NodeInfo
= CDP
.getSDNodeInfo(N
->getOperator());
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
);
1936 // Only handle child sizes of 3. Otherwise we'll end up trying too many
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
);
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.
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
);
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
);
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
);
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
);
1988 // Build all permutations based on how the children were formed.
1989 CombineChildVariants(N
, ChildVariants
, OutVariants
, CDP
);
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.
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"))
2006 // Consider the commuted order.
2008 CombineChildVariants(N
, ChildVariants
[1], ChildVariants
[0],
2014 // GenerateVariants - Generate variants. For example, commutative patterns can
2015 // match multiple ways. Add them to PatternsToMatch as well.
2016 void CodeGenDAGPatterns::GenerateVariants() {
2017 DOUT
<< "Generating instruction variants.\n";
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.
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.
2028 for (unsigned i
= 0, e
= PatternsToMatch
.size(); i
!= e
; ++i
) {
2029 std::vector
<TreePatternNode
*> Variants
;
2030 GenerateVariantsOf(PatternsToMatch
[i
].getSrcPattern(), Variants
, *this);
2032 assert(!Variants
.empty() && "Must create at least original variant!");
2033 Variants
.erase(Variants
.begin()); // Remove the original pattern.
2035 if (Variants
.empty()) // No variants for this pattern.
2038 DOUT
<< "FOUND VARIANTS OF: ";
2039 DEBUG(PatternsToMatch
[i
].getSrcPattern()->dump());
2042 for (unsigned v
= 0, e
= Variants
.size(); v
!= e
; ++v
) {
2043 TreePatternNode
*Variant
= Variants
[v
];
2045 DOUT
<< " VAR#" << v
<< ": ";
2046 DEBUG(Variant
->dump());
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;
2059 // If we already have it, ignore the variant.
2060 if (AlreadyExists
) continue;
2062 // Otherwise, add it to the list of patterns we have.
2064 push_back(PatternToMatch(PatternsToMatch
[i
].getPredicates(),
2065 Variant
, PatternsToMatch
[i
].getDstPattern(),
2066 PatternsToMatch
[i
].getDstRegs(),
2067 PatternsToMatch
[i
].getAddedComplexity()));