1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
22 //===----------------------------------------------------------------------===//
23 // Helpers for working with extended types.
25 /// FilterVTs - Filter a list of VT's according to a predicate.
28 static std::vector<MVT::ValueType>
29 FilterVTs(const std::vector<MVT::ValueType> &InVTs, T Filter) {
30 std::vector<MVT::ValueType> Result;
31 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
33 Result.push_back(InVTs[i]);
38 static std::vector<unsigned char>
39 FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
40 std::vector<unsigned char> Result;
41 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
42 if (Filter((MVT::ValueType)InVTs[i]))
43 Result.push_back(InVTs[i]);
47 static std::vector<unsigned char>
48 ConvertVTs(const std::vector<MVT::ValueType> &InVTs) {
49 std::vector<unsigned char> Result;
50 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
51 Result.push_back(InVTs[i]);
55 static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
56 const std::vector<unsigned char> &RHS) {
57 if (LHS.size() > RHS.size()) return false;
58 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
59 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
64 /// isExtIntegerVT - Return true if the specified extended value type vector
65 /// contains isInt or an integer value type.
66 static bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
67 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
68 return EVTs[0] == MVT::isInt || !(FilterEVTs(EVTs, MVT::isInteger).empty());
71 /// isExtFloatingPointVT - Return true if the specified extended value type
72 /// vector contains isFP or a FP value type.
73 static bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
74 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
75 return EVTs[0] == MVT::isFP ||
76 !(FilterEVTs(EVTs, MVT::isFloatingPoint).empty());
79 //===----------------------------------------------------------------------===//
80 // SDTypeConstraint implementation
83 SDTypeConstraint::SDTypeConstraint(Record *R) {
84 OperandNo = R->getValueAsInt("OperandNum");
86 if (R->isSubClassOf("SDTCisVT")) {
87 ConstraintType = SDTCisVT;
88 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
89 } else if (R->isSubClassOf("SDTCisPtrTy")) {
90 ConstraintType = SDTCisPtrTy;
91 } else if (R->isSubClassOf("SDTCisInt")) {
92 ConstraintType = SDTCisInt;
93 } else if (R->isSubClassOf("SDTCisFP")) {
94 ConstraintType = SDTCisFP;
95 } else if (R->isSubClassOf("SDTCisSameAs")) {
96 ConstraintType = SDTCisSameAs;
97 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
98 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
99 ConstraintType = SDTCisVTSmallerThanOp;
100 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
101 R->getValueAsInt("OtherOperandNum");
102 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
103 ConstraintType = SDTCisOpSmallerThanOp;
104 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
105 R->getValueAsInt("BigOperandNum");
106 } else if (R->isSubClassOf("SDTCisIntVectorOfSameSize")) {
107 ConstraintType = SDTCisIntVectorOfSameSize;
108 x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum =
109 R->getValueAsInt("OtherOpNum");
111 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
116 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
117 /// N, which has NumResults results.
118 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
120 unsigned NumResults) const {
121 assert(NumResults <= 1 &&
122 "We only work with nodes with zero or one result so far!");
124 if (OpNo < NumResults)
125 return N; // FIXME: need value #
127 return N->getChild(OpNo-NumResults);
130 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
131 /// constraint to the nodes operands. This returns true if it makes a
132 /// change, false otherwise. If a type contradiction is found, throw an
134 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
135 const SDNodeInfo &NodeInfo,
136 TreePattern &TP) const {
137 unsigned NumResults = NodeInfo.getNumResults();
138 assert(NumResults <= 1 &&
139 "We only work with nodes with zero or one result so far!");
141 // Check that the number of operands is sane.
142 if (NodeInfo.getNumOperands() >= 0) {
143 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
144 TP.error(N->getOperator()->getName() + " node requires exactly " +
145 itostr(NodeInfo.getNumOperands()) + " operands!");
148 const CodeGenTarget &CGT = TP.getDAGISelEmitter().getTargetInfo();
150 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
152 switch (ConstraintType) {
153 default: assert(0 && "Unknown constraint type!");
155 // Operand must be a particular type.
156 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
158 // Operand must be same as target pointer type.
159 return NodeToApply->UpdateNodeType(CGT.getPointerType(), TP);
162 // If there is only one integer type supported, this must be it.
163 std::vector<MVT::ValueType> IntVTs =
164 FilterVTs(CGT.getLegalValueTypes(), MVT::isInteger);
166 // If we found exactly one supported integer type, apply it.
167 if (IntVTs.size() == 1)
168 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
169 return NodeToApply->UpdateNodeType(MVT::isInt, TP);
172 // If there is only one FP type supported, this must be it.
173 std::vector<MVT::ValueType> FPVTs =
174 FilterVTs(CGT.getLegalValueTypes(), MVT::isFloatingPoint);
176 // If we found exactly one supported FP type, apply it.
177 if (FPVTs.size() == 1)
178 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
179 return NodeToApply->UpdateNodeType(MVT::isFP, TP);
182 TreePatternNode *OtherNode =
183 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
184 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
185 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
187 case SDTCisVTSmallerThanOp: {
188 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
189 // have an integer type that is smaller than the VT.
190 if (!NodeToApply->isLeaf() ||
191 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
192 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
193 ->isSubClassOf("ValueType"))
194 TP.error(N->getOperator()->getName() + " expects a VT operand!");
196 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
197 if (!MVT::isInteger(VT))
198 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
200 TreePatternNode *OtherNode =
201 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
203 // It must be integer.
204 bool MadeChange = false;
205 MadeChange |= OtherNode->UpdateNodeType(MVT::isInt, TP);
207 // This code only handles nodes that have one type set. Assert here so
208 // that we can change this if we ever need to deal with multiple value
209 // types at this point.
210 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
211 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
212 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
215 case SDTCisOpSmallerThanOp: {
216 TreePatternNode *BigOperand =
217 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
219 // Both operands must be integer or FP, but we don't care which.
220 bool MadeChange = false;
222 // This code does not currently handle nodes which have multiple types,
223 // where some types are integer, and some are fp. Assert that this is not
225 assert(!(isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
226 isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
227 !(isExtIntegerInVTs(BigOperand->getExtTypes()) &&
228 isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
229 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
230 if (isExtIntegerInVTs(NodeToApply->getExtTypes()))
231 MadeChange |= BigOperand->UpdateNodeType(MVT::isInt, TP);
232 else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
233 MadeChange |= BigOperand->UpdateNodeType(MVT::isFP, TP);
234 if (isExtIntegerInVTs(BigOperand->getExtTypes()))
235 MadeChange |= NodeToApply->UpdateNodeType(MVT::isInt, TP);
236 else if (isExtFloatingPointInVTs(BigOperand->getExtTypes()))
237 MadeChange |= NodeToApply->UpdateNodeType(MVT::isFP, TP);
239 std::vector<MVT::ValueType> VTs = CGT.getLegalValueTypes();
241 if (isExtIntegerInVTs(NodeToApply->getExtTypes())) {
242 VTs = FilterVTs(VTs, MVT::isInteger);
243 } else if (isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
244 VTs = FilterVTs(VTs, MVT::isFloatingPoint);
249 switch (VTs.size()) {
250 default: // Too many VT's to pick from.
251 case 0: break; // No info yet.
253 // Only one VT of this flavor. Cannot ever satisify the constraints.
254 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
256 // If we have exactly two possible types, the little operand must be the
257 // small one, the big operand should be the big one. Common with
258 // float/double for example.
259 assert(VTs[0] < VTs[1] && "Should be sorted!");
260 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
261 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
266 case SDTCisIntVectorOfSameSize: {
267 TreePatternNode *OtherOperand =
268 getOperandNum(x.SDTCisIntVectorOfSameSize_Info.OtherOperandNum,
270 if (OtherOperand->hasTypeSet()) {
271 if (!MVT::isVector(OtherOperand->getTypeNum(0)))
272 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
273 MVT::ValueType IVT = OtherOperand->getTypeNum(0);
274 IVT = MVT::getIntVectorWithNumElements(MVT::getVectorNumElements(IVT));
275 return NodeToApply->UpdateNodeType(IVT, TP);
284 //===----------------------------------------------------------------------===//
285 // SDNodeInfo implementation
287 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
288 EnumName = R->getValueAsString("Opcode");
289 SDClassName = R->getValueAsString("SDClass");
290 Record *TypeProfile = R->getValueAsDef("TypeProfile");
291 NumResults = TypeProfile->getValueAsInt("NumResults");
292 NumOperands = TypeProfile->getValueAsInt("NumOperands");
294 // Parse the properties.
296 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
297 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
298 if (PropList[i]->getName() == "SDNPCommutative") {
299 Properties |= 1 << SDNPCommutative;
300 } else if (PropList[i]->getName() == "SDNPAssociative") {
301 Properties |= 1 << SDNPAssociative;
302 } else if (PropList[i]->getName() == "SDNPHasChain") {
303 Properties |= 1 << SDNPHasChain;
304 } else if (PropList[i]->getName() == "SDNPOutFlag") {
305 Properties |= 1 << SDNPOutFlag;
306 } else if (PropList[i]->getName() == "SDNPInFlag") {
307 Properties |= 1 << SDNPInFlag;
308 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
309 Properties |= 1 << SDNPOptInFlag;
311 std::cerr << "Unknown SD Node property '" << PropList[i]->getName()
312 << "' on node '" << R->getName() << "'!\n";
318 // Parse the type constraints.
319 std::vector<Record*> ConstraintList =
320 TypeProfile->getValueAsListOfDefs("Constraints");
321 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
324 //===----------------------------------------------------------------------===//
325 // TreePatternNode implementation
328 TreePatternNode::~TreePatternNode() {
329 #if 0 // FIXME: implement refcounted tree nodes!
330 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
335 /// UpdateNodeType - Set the node type of N to VT if VT contains
336 /// information. If N already contains a conflicting type, then throw an
337 /// exception. This returns true if any information was updated.
339 bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
341 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
343 if (ExtVTs[0] == MVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
345 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
350 if (ExtVTs[0] == MVT::isInt && isExtIntegerInVTs(getExtTypes())) {
351 assert(hasTypeSet() && "should be handled above!");
352 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), MVT::isInteger);
353 if (getExtTypes() == FVTs)
358 if (ExtVTs[0] == MVT::isFP && isExtFloatingPointInVTs(getExtTypes())) {
359 assert(hasTypeSet() && "should be handled above!");
360 std::vector<unsigned char> FVTs =
361 FilterEVTs(getExtTypes(), MVT::isFloatingPoint);
362 if (getExtTypes() == FVTs)
368 // If we know this is an int or fp type, and we are told it is a specific one,
371 // Similarly, we should probably set the type here to the intersection of
372 // {isInt|isFP} and ExtVTs
373 if ((getExtTypeNum(0) == MVT::isInt && isExtIntegerInVTs(ExtVTs)) ||
374 (getExtTypeNum(0) == MVT::isFP && isExtFloatingPointInVTs(ExtVTs))) {
382 TP.error("Type inference contradiction found in node!");
384 TP.error("Type inference contradiction found in node " +
385 getOperator()->getName() + "!");
387 return true; // unreachable
391 void TreePatternNode::print(std::ostream &OS) const {
393 OS << *getLeafValue();
395 OS << "(" << getOperator()->getName();
398 // FIXME: At some point we should handle printing all the value types for
399 // nodes that are multiply typed.
400 switch (getExtTypeNum(0)) {
401 case MVT::Other: OS << ":Other"; break;
402 case MVT::isInt: OS << ":isInt"; break;
403 case MVT::isFP : OS << ":isFP"; break;
404 case MVT::isUnknown: ; /*OS << ":?";*/ break;
405 default: OS << ":" << getTypeNum(0); break;
409 if (getNumChildren() != 0) {
411 getChild(0)->print(OS);
412 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
414 getChild(i)->print(OS);
420 if (!PredicateFn.empty())
421 OS << "<<P:" << PredicateFn << ">>";
423 OS << "<<X:" << TransformFn->getName() << ">>";
424 if (!getName().empty())
425 OS << ":$" << getName();
428 void TreePatternNode::dump() const {
432 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
433 /// the specified node. For this comparison, all of the state of the node
434 /// is considered, except for the assigned name. Nodes with differing names
435 /// that are otherwise identical are considered isomorphic.
436 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N) const {
437 if (N == this) return true;
438 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
439 getPredicateFn() != N->getPredicateFn() ||
440 getTransformFn() != N->getTransformFn())
444 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue()))
445 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue()))
446 return DI->getDef() == NDI->getDef();
447 return getLeafValue() == N->getLeafValue();
450 if (N->getOperator() != getOperator() ||
451 N->getNumChildren() != getNumChildren()) return false;
452 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
453 if (!getChild(i)->isIsomorphicTo(N->getChild(i)))
458 /// clone - Make a copy of this tree and all of its children.
460 TreePatternNode *TreePatternNode::clone() const {
461 TreePatternNode *New;
463 New = new TreePatternNode(getLeafValue());
465 std::vector<TreePatternNode*> CChildren;
466 CChildren.reserve(Children.size());
467 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
468 CChildren.push_back(getChild(i)->clone());
469 New = new TreePatternNode(getOperator(), CChildren);
471 New->setName(getName());
472 New->setTypes(getExtTypes());
473 New->setPredicateFn(getPredicateFn());
474 New->setTransformFn(getTransformFn());
478 /// SubstituteFormalArguments - Replace the formal arguments in this tree
479 /// with actual values specified by ArgMap.
480 void TreePatternNode::
481 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
482 if (isLeaf()) return;
484 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
485 TreePatternNode *Child = getChild(i);
486 if (Child->isLeaf()) {
487 Init *Val = Child->getLeafValue();
488 if (dynamic_cast<DefInit*>(Val) &&
489 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
490 // We found a use of a formal argument, replace it with its value.
491 Child = ArgMap[Child->getName()];
492 assert(Child && "Couldn't find formal argument!");
496 getChild(i)->SubstituteFormalArguments(ArgMap);
502 /// InlinePatternFragments - If this pattern refers to any pattern
503 /// fragments, inline them into place, giving us a pattern without any
504 /// PatFrag references.
505 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
506 if (isLeaf()) return this; // nothing to do.
507 Record *Op = getOperator();
509 if (!Op->isSubClassOf("PatFrag")) {
510 // Just recursively inline children nodes.
511 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
512 setChild(i, getChild(i)->InlinePatternFragments(TP));
516 // Otherwise, we found a reference to a fragment. First, look up its
517 // TreePattern record.
518 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
520 // Verify that we are passing the right number of operands.
521 if (Frag->getNumArgs() != Children.size())
522 TP.error("'" + Op->getName() + "' fragment requires " +
523 utostr(Frag->getNumArgs()) + " operands!");
525 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
527 // Resolve formal arguments to their actual value.
528 if (Frag->getNumArgs()) {
529 // Compute the map of formal to actual arguments.
530 std::map<std::string, TreePatternNode*> ArgMap;
531 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
532 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
534 FragTree->SubstituteFormalArguments(ArgMap);
537 FragTree->setName(getName());
538 FragTree->UpdateNodeType(getExtTypes(), TP);
540 // Get a new copy of this fragment to stitch into here.
541 //delete this; // FIXME: implement refcounting!
545 /// getIntrinsicType - Check to see if the specified record has an intrinsic
546 /// type which should be applied to it. This infer the type of register
547 /// references from the register file information, for example.
549 static std::vector<unsigned char> getIntrinsicType(Record *R, bool NotRegisters,
551 // Some common return values
552 std::vector<unsigned char> Unknown(1, MVT::isUnknown);
553 std::vector<unsigned char> Other(1, MVT::Other);
555 // Check to see if this is a register or a register class...
556 if (R->isSubClassOf("RegisterClass")) {
559 const CodeGenRegisterClass &RC =
560 TP.getDAGISelEmitter().getTargetInfo().getRegisterClass(R);
561 return ConvertVTs(RC.getValueTypes());
562 } else if (R->isSubClassOf("PatFrag")) {
563 // Pattern fragment types will be resolved when they are inlined.
565 } else if (R->isSubClassOf("Register")) {
568 // If the register appears in exactly one regclass, and the regclass has one
569 // value type, use it as the known type.
570 const CodeGenTarget &T = TP.getDAGISelEmitter().getTargetInfo();
571 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
572 return ConvertVTs(RC->getValueTypes());
574 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
575 // Using a VTSDNode or CondCodeSDNode.
577 } else if (R->isSubClassOf("ComplexPattern")) {
580 std::vector<unsigned char>
581 ComplexPat(1, TP.getDAGISelEmitter().getComplexPattern(R).getValueType());
583 } else if (R->getName() == "node" || R->getName() == "srcvalue") {
588 TP.error("Unknown node flavor used in pattern: " + R->getName());
592 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
593 /// this node and its children in the tree. This returns true if it makes a
594 /// change, false otherwise. If a type contradiction is found, throw an
596 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
597 DAGISelEmitter &ISE = TP.getDAGISelEmitter();
599 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
600 // If it's a regclass or something else known, include the type.
601 return UpdateNodeType(getIntrinsicType(DI->getDef(), NotRegisters, TP),
603 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
604 // Int inits are always integers. :)
605 bool MadeChange = UpdateNodeType(MVT::isInt, TP);
608 // At some point, it may make sense for this tree pattern to have
609 // multiple types. Assert here that it does not, so we revisit this
610 // code when appropriate.
611 assert(getExtTypes().size() == 1 && "TreePattern has too many types!");
613 unsigned Size = MVT::getSizeInBits(getTypeNum(0));
614 // Make sure that the value is representable for this type.
616 int Val = (II->getValue() << (32-Size)) >> (32-Size);
617 if (Val != II->getValue())
618 TP.error("Sign-extended integer value '" + itostr(II->getValue()) +
619 "' is out of range for type 'MVT::" +
620 getEnumName(getTypeNum(0)) + "'!");
629 // special handling for set, which isn't really an SDNode.
630 if (getOperator()->getName() == "set") {
631 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
632 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
633 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
635 // Types of operands must match.
636 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getExtTypes(), TP);
637 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getExtTypes(), TP);
638 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
640 } else if (getOperator() == ISE.get_intrinsic_void_sdnode() ||
641 getOperator() == ISE.get_intrinsic_w_chain_sdnode() ||
642 getOperator() == ISE.get_intrinsic_wo_chain_sdnode()) {
644 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
645 const CodeGenIntrinsic &Int = ISE.getIntrinsicInfo(IID);
646 bool MadeChange = false;
648 // Apply the result type to the node.
649 MadeChange = UpdateNodeType(Int.ArgVTs[0], TP);
651 if (getNumChildren() != Int.ArgVTs.size())
652 TP.error("Intrinsic '" + Int.Name + "' expects " +
653 utostr(Int.ArgVTs.size()-1) + " operands, not " +
654 utostr(getNumChildren()-1) + " operands!");
656 // Apply type info to the intrinsic ID.
657 MVT::ValueType PtrTy = ISE.getTargetInfo().getPointerType();
658 MadeChange |= getChild(0)->UpdateNodeType(PtrTy, TP);
660 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
661 MVT::ValueType OpVT = Int.ArgVTs[i];
662 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
663 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
666 } else if (getOperator()->isSubClassOf("SDNode")) {
667 const SDNodeInfo &NI = ISE.getSDNodeInfo(getOperator());
669 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
670 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
671 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
672 // Branch, etc. do not produce results and top-level forms in instr pattern
673 // must have void types.
674 if (NI.getNumResults() == 0)
675 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
677 } else if (getOperator()->isSubClassOf("Instruction")) {
678 const DAGInstruction &Inst = ISE.getInstruction(getOperator());
679 bool MadeChange = false;
680 unsigned NumResults = Inst.getNumResults();
682 assert(NumResults <= 1 &&
683 "Only supports zero or one result instrs!");
684 // Apply the result type to the node
685 if (NumResults == 0) {
686 MadeChange = UpdateNodeType(MVT::isVoid, TP);
688 Record *ResultNode = Inst.getResult(0);
689 assert(ResultNode->isSubClassOf("RegisterClass") &&
690 "Operands should be register classes!");
692 const CodeGenRegisterClass &RC =
693 ISE.getTargetInfo().getRegisterClass(ResultNode);
694 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
697 if (getNumChildren() != Inst.getNumOperands())
698 TP.error("Instruction '" + getOperator()->getName() + " expects " +
699 utostr(Inst.getNumOperands()) + " operands, not " +
700 utostr(getNumChildren()) + " operands!");
701 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
702 Record *OperandNode = Inst.getOperand(i);
704 if (OperandNode->isSubClassOf("RegisterClass")) {
705 const CodeGenRegisterClass &RC =
706 ISE.getTargetInfo().getRegisterClass(OperandNode);
707 //VT = RC.getValueTypeNum(0);
708 MadeChange |=getChild(i)->UpdateNodeType(ConvertVTs(RC.getValueTypes()),
710 } else if (OperandNode->isSubClassOf("Operand")) {
711 VT = getValueType(OperandNode->getValueAsDef("Type"));
712 MadeChange |= getChild(i)->UpdateNodeType(VT, TP);
714 assert(0 && "Unknown operand type!");
717 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
721 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
723 // Node transforms always take one operand.
724 if (getNumChildren() != 1)
725 TP.error("Node transform '" + getOperator()->getName() +
726 "' requires one operand!");
728 // If either the output or input of the xform does not have exact
729 // type info. We assume they must be the same. Otherwise, it is perfectly
730 // legal to transform from one type to a completely different type.
731 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
732 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
733 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
740 /// canPatternMatch - If it is impossible for this pattern to match on this
741 /// target, fill in Reason and return false. Otherwise, return true. This is
742 /// used as a santity check for .td files (to prevent people from writing stuff
743 /// that can never possibly work), and to prevent the pattern permuter from
744 /// generating stuff that is useless.
745 bool TreePatternNode::canPatternMatch(std::string &Reason, DAGISelEmitter &ISE){
746 if (isLeaf()) return true;
748 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
749 if (!getChild(i)->canPatternMatch(Reason, ISE))
752 // If this is an intrinsic, handle cases that would make it not match. For
753 // example, if an operand is required to be an immediate.
754 if (getOperator()->isSubClassOf("Intrinsic")) {
759 // If this node is a commutative operator, check that the LHS isn't an
761 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(getOperator());
762 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
763 // Scan all of the operands of the node and make sure that only the last one
764 // is a constant node.
765 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i)
766 if (!getChild(i)->isLeaf() &&
767 getChild(i)->getOperator()->getName() == "imm") {
768 Reason = "Immediate value must be on the RHS of commutative operators!";
776 //===----------------------------------------------------------------------===//
777 // TreePattern implementation
780 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
781 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
782 isInputPattern = isInput;
783 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
784 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
787 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
788 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
789 isInputPattern = isInput;
790 Trees.push_back(ParseTreePattern(Pat));
793 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
794 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
795 isInputPattern = isInput;
796 Trees.push_back(Pat);
801 void TreePattern::error(const std::string &Msg) const {
803 throw "In " + TheRecord->getName() + ": " + Msg;
806 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
807 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
808 if (!OpDef) error("Pattern has unexpected operator type!");
809 Record *Operator = OpDef->getDef();
811 if (Operator->isSubClassOf("ValueType")) {
812 // If the operator is a ValueType, then this must be "type cast" of a leaf
814 if (Dag->getNumArgs() != 1)
815 error("Type cast only takes one operand!");
817 Init *Arg = Dag->getArg(0);
818 TreePatternNode *New;
819 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
820 Record *R = DI->getDef();
821 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
822 Dag->setArg(0, new DagInit(DI,
823 std::vector<std::pair<Init*, std::string> >()));
824 return ParseTreePattern(Dag);
826 New = new TreePatternNode(DI);
827 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
828 New = ParseTreePattern(DI);
829 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
830 New = new TreePatternNode(II);
831 if (!Dag->getArgName(0).empty())
832 error("Constant int argument should not have a name!");
833 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
834 // Turn this into an IntInit.
835 Init *II = BI->convertInitializerTo(new IntRecTy());
836 if (II == 0 || !dynamic_cast<IntInit*>(II))
837 error("Bits value must be constants!");
839 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
840 if (!Dag->getArgName(0).empty())
841 error("Constant int argument should not have a name!");
844 error("Unknown leaf value for tree pattern!");
848 // Apply the type cast.
849 New->UpdateNodeType(getValueType(Operator), *this);
850 New->setName(Dag->getArgName(0));
854 // Verify that this is something that makes sense for an operator.
855 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
856 !Operator->isSubClassOf("Instruction") &&
857 !Operator->isSubClassOf("SDNodeXForm") &&
858 !Operator->isSubClassOf("Intrinsic") &&
859 Operator->getName() != "set")
860 error("Unrecognized node '" + Operator->getName() + "'!");
862 // Check to see if this is something that is illegal in an input pattern.
863 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
864 Operator->isSubClassOf("SDNodeXForm")))
865 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
867 std::vector<TreePatternNode*> Children;
869 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
870 Init *Arg = Dag->getArg(i);
871 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
872 Children.push_back(ParseTreePattern(DI));
873 if (Children.back()->getName().empty())
874 Children.back()->setName(Dag->getArgName(i));
875 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
876 Record *R = DefI->getDef();
877 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
878 // TreePatternNode if its own.
879 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
880 Dag->setArg(i, new DagInit(DefI,
881 std::vector<std::pair<Init*, std::string> >()));
882 --i; // Revisit this node...
884 TreePatternNode *Node = new TreePatternNode(DefI);
885 Node->setName(Dag->getArgName(i));
886 Children.push_back(Node);
889 if (R->getName() == "node") {
890 if (Dag->getArgName(i).empty())
891 error("'node' argument requires a name to match with operand list");
892 Args.push_back(Dag->getArgName(i));
895 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
896 TreePatternNode *Node = new TreePatternNode(II);
897 if (!Dag->getArgName(i).empty())
898 error("Constant int argument should not have a name!");
899 Children.push_back(Node);
900 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
901 // Turn this into an IntInit.
902 Init *II = BI->convertInitializerTo(new IntRecTy());
903 if (II == 0 || !dynamic_cast<IntInit*>(II))
904 error("Bits value must be constants!");
906 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
907 if (!Dag->getArgName(i).empty())
908 error("Constant int argument should not have a name!");
909 Children.push_back(Node);
914 error("Unknown leaf value for tree pattern!");
918 // If the operator is an intrinsic, then this is just syntactic sugar for for
919 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
920 // convert the intrinsic name to a number.
921 if (Operator->isSubClassOf("Intrinsic")) {
922 const CodeGenIntrinsic &Int = getDAGISelEmitter().getIntrinsic(Operator);
923 unsigned IID = getDAGISelEmitter().getIntrinsicID(Operator)+1;
925 // If this intrinsic returns void, it must have side-effects and thus a
927 if (Int.ArgVTs[0] == MVT::isVoid) {
928 Operator = getDAGISelEmitter().get_intrinsic_void_sdnode();
929 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
930 // Has side-effects, requires chain.
931 Operator = getDAGISelEmitter().get_intrinsic_w_chain_sdnode();
933 // Otherwise, no chain.
934 Operator = getDAGISelEmitter().get_intrinsic_wo_chain_sdnode();
937 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
938 Children.insert(Children.begin(), IIDNode);
941 return new TreePatternNode(Operator, Children);
944 /// InferAllTypes - Infer/propagate as many types throughout the expression
945 /// patterns as possible. Return true if all types are infered, false
946 /// otherwise. Throw an exception if a type contradiction is found.
947 bool TreePattern::InferAllTypes() {
948 bool MadeChange = true;
951 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
952 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
955 bool HasUnresolvedTypes = false;
956 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
957 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
958 return !HasUnresolvedTypes;
961 void TreePattern::print(std::ostream &OS) const {
962 OS << getRecord()->getName();
964 OS << "(" << Args[0];
965 for (unsigned i = 1, e = Args.size(); i != e; ++i)
966 OS << ", " << Args[i];
971 if (Trees.size() > 1)
973 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
979 if (Trees.size() > 1)
983 void TreePattern::dump() const { print(std::cerr); }
987 //===----------------------------------------------------------------------===//
988 // DAGISelEmitter implementation
991 // Parse all of the SDNode definitions for the target, populating SDNodes.
992 void DAGISelEmitter::ParseNodeInfo() {
993 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
994 while (!Nodes.empty()) {
995 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
999 // Get the buildin intrinsic nodes.
1000 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1001 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1002 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1005 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1006 /// map, and emit them to the file as functions.
1007 void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
1008 OS << "\n// Node transformations.\n";
1009 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1010 while (!Xforms.empty()) {
1011 Record *XFormNode = Xforms.back();
1012 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1013 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1014 SDNodeXForms.insert(std::make_pair(XFormNode,
1015 std::make_pair(SDNode, Code)));
1017 if (!Code.empty()) {
1018 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
1019 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1021 OS << "inline SDOperand Transform_" << XFormNode->getName()
1022 << "(SDNode *" << C2 << ") {\n";
1023 if (ClassName != "SDNode")
1024 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1025 OS << Code << "\n}\n";
1032 void DAGISelEmitter::ParseComplexPatterns() {
1033 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1034 while (!AMs.empty()) {
1035 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1041 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1042 /// file, building up the PatternFragments map. After we've collected them all,
1043 /// inline fragments together as necessary, so that there are no references left
1044 /// inside a pattern fragment to a pattern fragment.
1046 /// This also emits all of the predicate functions to the output file.
1048 void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
1049 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1051 // First step, parse all of the fragments and emit predicate functions.
1052 OS << "\n// Predicate functions.\n";
1053 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1054 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1055 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1056 PatternFragments[Fragments[i]] = P;
1058 // Validate the argument list, converting it to map, to discard duplicates.
1059 std::vector<std::string> &Args = P->getArgList();
1060 std::set<std::string> OperandsMap(Args.begin(), Args.end());
1062 if (OperandsMap.count(""))
1063 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1065 // Parse the operands list.
1066 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1067 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1068 if (!OpsOp || OpsOp->getDef()->getName() != "ops")
1069 P->error("Operands list should start with '(ops ... '!");
1071 // Copy over the arguments.
1073 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1074 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1075 static_cast<DefInit*>(OpsList->getArg(j))->
1076 getDef()->getName() != "node")
1077 P->error("Operands list should all be 'node' values.");
1078 if (OpsList->getArgName(j).empty())
1079 P->error("Operands list should have names for each operand!");
1080 if (!OperandsMap.count(OpsList->getArgName(j)))
1081 P->error("'" + OpsList->getArgName(j) +
1082 "' does not occur in pattern or was multiply specified!");
1083 OperandsMap.erase(OpsList->getArgName(j));
1084 Args.push_back(OpsList->getArgName(j));
1087 if (!OperandsMap.empty())
1088 P->error("Operands list does not contain an entry for operand '" +
1089 *OperandsMap.begin() + "'!");
1091 // If there is a code init for this fragment, emit the predicate code and
1092 // keep track of the fact that this fragment uses it.
1093 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1094 if (!Code.empty()) {
1095 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
1096 std::string ClassName =
1097 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
1098 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
1100 OS << "inline bool Predicate_" << Fragments[i]->getName()
1101 << "(SDNode *" << C2 << ") {\n";
1102 if (ClassName != "SDNode")
1103 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
1104 OS << Code << "\n}\n";
1105 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
1108 // If there is a node transformation corresponding to this, keep track of
1110 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1111 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1112 P->getOnlyTree()->setTransformFn(Transform);
1117 // Now that we've parsed all of the tree fragments, do a closure on them so
1118 // that there are not references to PatFrags left inside of them.
1119 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1120 E = PatternFragments.end(); I != E; ++I) {
1121 TreePattern *ThePat = I->second;
1122 ThePat->InlinePatternFragments();
1124 // Infer as many types as possible. Don't worry about it if we don't infer
1125 // all of them, some may depend on the inputs of the pattern.
1127 ThePat->InferAllTypes();
1129 // If this pattern fragment is not supported by this target (no types can
1130 // satisfy its constraints), just ignore it. If the bogus pattern is
1131 // actually used by instructions, the type consistency error will be
1135 // If debugging, print out the pattern fragment result.
1136 DEBUG(ThePat->dump());
1140 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1141 /// instruction input. Return true if this is a real use.
1142 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1143 std::map<std::string, TreePatternNode*> &InstInputs,
1144 std::vector<Record*> &InstImpInputs) {
1145 // No name -> not interesting.
1146 if (Pat->getName().empty()) {
1147 if (Pat->isLeaf()) {
1148 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1149 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1150 I->error("Input " + DI->getDef()->getName() + " must be named!");
1151 else if (DI && DI->getDef()->isSubClassOf("Register"))
1152 InstImpInputs.push_back(DI->getDef());
1158 if (Pat->isLeaf()) {
1159 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1160 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1163 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
1164 Rec = Pat->getOperator();
1167 // SRCVALUE nodes are ignored.
1168 if (Rec->getName() == "srcvalue")
1171 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1176 if (Slot->isLeaf()) {
1177 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1179 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1180 SlotRec = Slot->getOperator();
1183 // Ensure that the inputs agree if we've already seen this input.
1185 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1186 if (Slot->getExtTypes() != Pat->getExtTypes())
1187 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1192 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1193 /// part of "I", the instruction), computing the set of inputs and outputs of
1194 /// the pattern. Report errors if we see anything naughty.
1195 void DAGISelEmitter::
1196 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1197 std::map<std::string, TreePatternNode*> &InstInputs,
1198 std::map<std::string, TreePatternNode*>&InstResults,
1199 std::vector<Record*> &InstImpInputs,
1200 std::vector<Record*> &InstImpResults) {
1201 if (Pat->isLeaf()) {
1202 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1203 if (!isUse && Pat->getTransformFn())
1204 I->error("Cannot specify a transform function for a non-input value!");
1206 } else if (Pat->getOperator()->getName() != "set") {
1207 // If this is not a set, verify that the children nodes are not void typed,
1209 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1210 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1211 I->error("Cannot have void nodes inside of patterns!");
1212 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1213 InstImpInputs, InstImpResults);
1216 // If this is a non-leaf node with no children, treat it basically as if
1217 // it were a leaf. This handles nodes like (imm).
1219 if (Pat->getNumChildren() == 0)
1220 isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1222 if (!isUse && Pat->getTransformFn())
1223 I->error("Cannot specify a transform function for a non-input value!");
1227 // Otherwise, this is a set, validate and collect instruction results.
1228 if (Pat->getNumChildren() == 0)
1229 I->error("set requires operands!");
1230 else if (Pat->getNumChildren() & 1)
1231 I->error("set requires an even number of operands");
1233 if (Pat->getTransformFn())
1234 I->error("Cannot specify a transform function on a set node!");
1236 // Check the set destinations.
1237 unsigned NumValues = Pat->getNumChildren()/2;
1238 for (unsigned i = 0; i != NumValues; ++i) {
1239 TreePatternNode *Dest = Pat->getChild(i);
1240 if (!Dest->isLeaf())
1241 I->error("set destination should be a register!");
1243 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1245 I->error("set destination should be a register!");
1247 if (Val->getDef()->isSubClassOf("RegisterClass")) {
1248 if (Dest->getName().empty())
1249 I->error("set destination must have a name!");
1250 if (InstResults.count(Dest->getName()))
1251 I->error("cannot set '" + Dest->getName() +"' multiple times");
1252 InstResults[Dest->getName()] = Dest;
1253 } else if (Val->getDef()->isSubClassOf("Register")) {
1254 InstImpResults.push_back(Val->getDef());
1256 I->error("set destination should be a register!");
1259 // Verify and collect info from the computation.
1260 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
1261 InstInputs, InstResults,
1262 InstImpInputs, InstImpResults);
1266 /// ParseInstructions - Parse all of the instructions, inlining and resolving
1267 /// any fragments involved. This populates the Instructions list with fully
1268 /// resolved instructions.
1269 void DAGISelEmitter::ParseInstructions() {
1270 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1272 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1275 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1276 LI = Instrs[i]->getValueAsListInit("Pattern");
1278 // If there is no pattern, only collect minimal information about the
1279 // instruction for its operand list. We have to assume that there is one
1280 // result, as we have no detailed info.
1281 if (!LI || LI->getSize() == 0) {
1282 std::vector<Record*> Results;
1283 std::vector<Record*> Operands;
1285 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1287 if (InstInfo.OperandList.size() != 0) {
1288 // FIXME: temporary hack...
1289 if (InstInfo.noResults) {
1290 // These produce no results
1291 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1292 Operands.push_back(InstInfo.OperandList[j].Rec);
1294 // Assume the first operand is the result.
1295 Results.push_back(InstInfo.OperandList[0].Rec);
1297 // The rest are inputs.
1298 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1299 Operands.push_back(InstInfo.OperandList[j].Rec);
1303 // Create and insert the instruction.
1304 std::vector<Record*> ImpResults;
1305 std::vector<Record*> ImpOperands;
1306 Instructions.insert(std::make_pair(Instrs[i],
1307 DAGInstruction(0, Results, Operands, ImpResults,
1309 continue; // no pattern.
1312 // Parse the instruction.
1313 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1314 // Inline pattern fragments into it.
1315 I->InlinePatternFragments();
1317 // Infer as many types as possible. If we cannot infer all of them, we can
1318 // never do anything with this instruction pattern: report it to the user.
1319 if (!I->InferAllTypes())
1320 I->error("Could not infer all types in pattern!");
1322 // InstInputs - Keep track of all of the inputs of the instruction, along
1323 // with the record they are declared as.
1324 std::map<std::string, TreePatternNode*> InstInputs;
1326 // InstResults - Keep track of all the virtual registers that are 'set'
1327 // in the instruction, including what reg class they are.
1328 std::map<std::string, TreePatternNode*> InstResults;
1330 std::vector<Record*> InstImpInputs;
1331 std::vector<Record*> InstImpResults;
1333 // Verify that the top-level forms in the instruction are of void type, and
1334 // fill in the InstResults map.
1335 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1336 TreePatternNode *Pat = I->getTree(j);
1337 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1338 I->error("Top-level forms in instruction pattern should have"
1341 // Find inputs and outputs, and verify the structure of the uses/defs.
1342 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1343 InstImpInputs, InstImpResults);
1346 // Now that we have inputs and outputs of the pattern, inspect the operands
1347 // list for the instruction. This determines the order that operands are
1348 // added to the machine instruction the node corresponds to.
1349 unsigned NumResults = InstResults.size();
1351 // Parse the operands list from the (ops) list, validating it.
1352 std::vector<std::string> &Args = I->getArgList();
1353 assert(Args.empty() && "Args list should still be empty here!");
1354 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1356 // Check that all of the results occur first in the list.
1357 std::vector<Record*> Results;
1358 TreePatternNode *Res0Node = NULL;
1359 for (unsigned i = 0; i != NumResults; ++i) {
1360 if (i == CGI.OperandList.size())
1361 I->error("'" + InstResults.begin()->first +
1362 "' set but does not appear in operand list!");
1363 const std::string &OpName = CGI.OperandList[i].Name;
1365 // Check that it exists in InstResults.
1366 TreePatternNode *RNode = InstResults[OpName];
1368 I->error("Operand $" + OpName + " does not exist in operand list!");
1372 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1374 I->error("Operand $" + OpName + " should be a set destination: all "
1375 "outputs must occur before inputs in operand list!");
1377 if (CGI.OperandList[i].Rec != R)
1378 I->error("Operand $" + OpName + " class mismatch!");
1380 // Remember the return type.
1381 Results.push_back(CGI.OperandList[i].Rec);
1383 // Okay, this one checks out.
1384 InstResults.erase(OpName);
1387 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1388 // the copy while we're checking the inputs.
1389 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1391 std::vector<TreePatternNode*> ResultNodeOperands;
1392 std::vector<Record*> Operands;
1393 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1394 const std::string &OpName = CGI.OperandList[i].Name;
1396 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1398 if (!InstInputsCheck.count(OpName))
1399 I->error("Operand $" + OpName +
1400 " does not appear in the instruction pattern");
1401 TreePatternNode *InVal = InstInputsCheck[OpName];
1402 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1404 if (InVal->isLeaf() &&
1405 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1406 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1407 if (CGI.OperandList[i].Rec != InRec &&
1408 !InRec->isSubClassOf("ComplexPattern"))
1409 I->error("Operand $" + OpName + "'s register class disagrees"
1410 " between the operand and pattern");
1412 Operands.push_back(CGI.OperandList[i].Rec);
1414 // Construct the result for the dest-pattern operand list.
1415 TreePatternNode *OpNode = InVal->clone();
1417 // No predicate is useful on the result.
1418 OpNode->setPredicateFn("");
1420 // Promote the xform function to be an explicit node if set.
1421 if (Record *Xform = OpNode->getTransformFn()) {
1422 OpNode->setTransformFn(0);
1423 std::vector<TreePatternNode*> Children;
1424 Children.push_back(OpNode);
1425 OpNode = new TreePatternNode(Xform, Children);
1428 ResultNodeOperands.push_back(OpNode);
1431 if (!InstInputsCheck.empty())
1432 I->error("Input operand $" + InstInputsCheck.begin()->first +
1433 " occurs in pattern but not in operands list!");
1435 TreePatternNode *ResultPattern =
1436 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1437 // Copy fully inferred output node type to instruction result pattern.
1439 ResultPattern->setTypes(Res0Node->getExtTypes());
1441 // Create and insert the instruction.
1442 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1443 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1445 // Use a temporary tree pattern to infer all types and make sure that the
1446 // constructed result is correct. This depends on the instruction already
1447 // being inserted into the Instructions map.
1448 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1449 Temp.InferAllTypes();
1451 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1452 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1457 // If we can, convert the instructions to be patterns that are matched!
1458 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1459 E = Instructions.end(); II != E; ++II) {
1460 DAGInstruction &TheInst = II->second;
1461 TreePattern *I = TheInst.getPattern();
1462 if (I == 0) continue; // No pattern.
1464 if (I->getNumTrees() != 1) {
1465 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
1468 TreePatternNode *Pattern = I->getTree(0);
1469 TreePatternNode *SrcPattern;
1470 if (Pattern->getOperator()->getName() == "set") {
1471 if (Pattern->getNumChildren() != 2)
1472 continue; // Not a set of a single value (not handled so far)
1474 SrcPattern = Pattern->getChild(1)->clone();
1476 // Not a set (store or something?)
1477 SrcPattern = Pattern;
1481 if (!SrcPattern->canPatternMatch(Reason, *this))
1482 I->error("Instruction can never match: " + Reason);
1484 Record *Instr = II->first;
1485 TreePatternNode *DstPattern = TheInst.getResultPattern();
1487 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1488 SrcPattern, DstPattern));
1492 void DAGISelEmitter::ParsePatterns() {
1493 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
1495 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1496 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
1497 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, true, *this);
1499 // Inline pattern fragments into it.
1500 Pattern->InlinePatternFragments();
1502 // Infer as many types as possible. If we cannot infer all of them, we can
1503 // never do anything with this pattern: report it to the user.
1504 if (!Pattern->InferAllTypes())
1505 Pattern->error("Could not infer all types in pattern!");
1507 // Validate that the input pattern is correct.
1509 std::map<std::string, TreePatternNode*> InstInputs;
1510 std::map<std::string, TreePatternNode*> InstResults;
1511 std::vector<Record*> InstImpInputs;
1512 std::vector<Record*> InstImpResults;
1513 FindPatternInputsAndOutputs(Pattern, Pattern->getOnlyTree(),
1514 InstInputs, InstResults,
1515 InstImpInputs, InstImpResults);
1518 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
1519 if (LI->getSize() == 0) continue; // no pattern.
1521 // Parse the instruction.
1522 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
1524 // Inline pattern fragments into it.
1525 Result->InlinePatternFragments();
1527 // Infer as many types as possible. If we cannot infer all of them, we can
1528 // never do anything with this pattern: report it to the user.
1529 if (!Result->InferAllTypes())
1530 Result->error("Could not infer all types in pattern result!");
1532 if (Result->getNumTrees() != 1)
1533 Result->error("Cannot handle instructions producing instructions "
1534 "with temporaries yet!");
1536 // Promote the xform function to be an explicit node if set.
1537 std::vector<TreePatternNode*> ResultNodeOperands;
1538 TreePatternNode *DstPattern = Result->getOnlyTree();
1539 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
1540 TreePatternNode *OpNode = DstPattern->getChild(ii);
1541 if (Record *Xform = OpNode->getTransformFn()) {
1542 OpNode->setTransformFn(0);
1543 std::vector<TreePatternNode*> Children;
1544 Children.push_back(OpNode);
1545 OpNode = new TreePatternNode(Xform, Children);
1547 ResultNodeOperands.push_back(OpNode);
1549 DstPattern = Result->getOnlyTree();
1550 if (!DstPattern->isLeaf())
1551 DstPattern = new TreePatternNode(DstPattern->getOperator(),
1552 ResultNodeOperands);
1553 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
1554 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
1555 Temp.InferAllTypes();
1558 if (!Pattern->getOnlyTree()->canPatternMatch(Reason, *this))
1559 Pattern->error("Pattern can never match: " + Reason);
1562 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
1563 Pattern->getOnlyTree(),
1564 Temp.getOnlyTree()));
1568 /// CombineChildVariants - Given a bunch of permutations of each child of the
1569 /// 'operator' node, put them together in all possible ways.
1570 static void CombineChildVariants(TreePatternNode *Orig,
1571 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
1572 std::vector<TreePatternNode*> &OutVariants,
1573 DAGISelEmitter &ISE) {
1574 // Make sure that each operand has at least one variant to choose from.
1575 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1576 if (ChildVariants[i].empty())
1579 // The end result is an all-pairs construction of the resultant pattern.
1580 std::vector<unsigned> Idxs;
1581 Idxs.resize(ChildVariants.size());
1582 bool NotDone = true;
1584 // Create the variant and add it to the output list.
1585 std::vector<TreePatternNode*> NewChildren;
1586 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
1587 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
1588 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
1590 // Copy over properties.
1591 R->setName(Orig->getName());
1592 R->setPredicateFn(Orig->getPredicateFn());
1593 R->setTransformFn(Orig->getTransformFn());
1594 R->setTypes(Orig->getExtTypes());
1596 // If this pattern cannot every match, do not include it as a variant.
1597 std::string ErrString;
1598 if (!R->canPatternMatch(ErrString, ISE)) {
1601 bool AlreadyExists = false;
1603 // Scan to see if this pattern has already been emitted. We can get
1604 // duplication due to things like commuting:
1605 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
1606 // which are the same pattern. Ignore the dups.
1607 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
1608 if (R->isIsomorphicTo(OutVariants[i])) {
1609 AlreadyExists = true;
1616 OutVariants.push_back(R);
1619 // Increment indices to the next permutation.
1621 // Look for something we can increment without causing a wrap-around.
1622 for (unsigned IdxsIdx = 0; IdxsIdx != Idxs.size(); ++IdxsIdx) {
1623 if (++Idxs[IdxsIdx] < ChildVariants[IdxsIdx].size()) {
1624 NotDone = true; // Found something to increment.
1632 /// CombineChildVariants - A helper function for binary operators.
1634 static void CombineChildVariants(TreePatternNode *Orig,
1635 const std::vector<TreePatternNode*> &LHS,
1636 const std::vector<TreePatternNode*> &RHS,
1637 std::vector<TreePatternNode*> &OutVariants,
1638 DAGISelEmitter &ISE) {
1639 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1640 ChildVariants.push_back(LHS);
1641 ChildVariants.push_back(RHS);
1642 CombineChildVariants(Orig, ChildVariants, OutVariants, ISE);
1646 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
1647 std::vector<TreePatternNode *> &Children) {
1648 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
1649 Record *Operator = N->getOperator();
1651 // Only permit raw nodes.
1652 if (!N->getName().empty() || !N->getPredicateFn().empty() ||
1653 N->getTransformFn()) {
1654 Children.push_back(N);
1658 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
1659 Children.push_back(N->getChild(0));
1661 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
1663 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
1664 Children.push_back(N->getChild(1));
1666 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
1669 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
1670 /// the (potentially recursive) pattern by using algebraic laws.
1672 static void GenerateVariantsOf(TreePatternNode *N,
1673 std::vector<TreePatternNode*> &OutVariants,
1674 DAGISelEmitter &ISE) {
1675 // We cannot permute leaves.
1677 OutVariants.push_back(N);
1681 // Look up interesting info about the node.
1682 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(N->getOperator());
1684 // If this node is associative, reassociate.
1685 if (NodeInfo.hasProperty(SDNodeInfo::SDNPAssociative)) {
1686 // Reassociate by pulling together all of the linked operators
1687 std::vector<TreePatternNode*> MaximalChildren;
1688 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
1690 // Only handle child sizes of 3. Otherwise we'll end up trying too many
1692 if (MaximalChildren.size() == 3) {
1693 // Find the variants of all of our maximal children.
1694 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
1695 GenerateVariantsOf(MaximalChildren[0], AVariants, ISE);
1696 GenerateVariantsOf(MaximalChildren[1], BVariants, ISE);
1697 GenerateVariantsOf(MaximalChildren[2], CVariants, ISE);
1699 // There are only two ways we can permute the tree:
1700 // (A op B) op C and A op (B op C)
1701 // Within these forms, we can also permute A/B/C.
1703 // Generate legal pair permutations of A/B/C.
1704 std::vector<TreePatternNode*> ABVariants;
1705 std::vector<TreePatternNode*> BAVariants;
1706 std::vector<TreePatternNode*> ACVariants;
1707 std::vector<TreePatternNode*> CAVariants;
1708 std::vector<TreePatternNode*> BCVariants;
1709 std::vector<TreePatternNode*> CBVariants;
1710 CombineChildVariants(N, AVariants, BVariants, ABVariants, ISE);
1711 CombineChildVariants(N, BVariants, AVariants, BAVariants, ISE);
1712 CombineChildVariants(N, AVariants, CVariants, ACVariants, ISE);
1713 CombineChildVariants(N, CVariants, AVariants, CAVariants, ISE);
1714 CombineChildVariants(N, BVariants, CVariants, BCVariants, ISE);
1715 CombineChildVariants(N, CVariants, BVariants, CBVariants, ISE);
1717 // Combine those into the result: (x op x) op x
1718 CombineChildVariants(N, ABVariants, CVariants, OutVariants, ISE);
1719 CombineChildVariants(N, BAVariants, CVariants, OutVariants, ISE);
1720 CombineChildVariants(N, ACVariants, BVariants, OutVariants, ISE);
1721 CombineChildVariants(N, CAVariants, BVariants, OutVariants, ISE);
1722 CombineChildVariants(N, BCVariants, AVariants, OutVariants, ISE);
1723 CombineChildVariants(N, CBVariants, AVariants, OutVariants, ISE);
1725 // Combine those into the result: x op (x op x)
1726 CombineChildVariants(N, CVariants, ABVariants, OutVariants, ISE);
1727 CombineChildVariants(N, CVariants, BAVariants, OutVariants, ISE);
1728 CombineChildVariants(N, BVariants, ACVariants, OutVariants, ISE);
1729 CombineChildVariants(N, BVariants, CAVariants, OutVariants, ISE);
1730 CombineChildVariants(N, AVariants, BCVariants, OutVariants, ISE);
1731 CombineChildVariants(N, AVariants, CBVariants, OutVariants, ISE);
1736 // Compute permutations of all children.
1737 std::vector<std::vector<TreePatternNode*> > ChildVariants;
1738 ChildVariants.resize(N->getNumChildren());
1739 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1740 GenerateVariantsOf(N->getChild(i), ChildVariants[i], ISE);
1742 // Build all permutations based on how the children were formed.
1743 CombineChildVariants(N, ChildVariants, OutVariants, ISE);
1745 // If this node is commutative, consider the commuted order.
1746 if (NodeInfo.hasProperty(SDNodeInfo::SDNPCommutative)) {
1747 assert(N->getNumChildren()==2 &&"Commutative but doesn't have 2 children!");
1748 // Consider the commuted order.
1749 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
1755 // GenerateVariants - Generate variants. For example, commutative patterns can
1756 // match multiple ways. Add them to PatternsToMatch as well.
1757 void DAGISelEmitter::GenerateVariants() {
1759 DEBUG(std::cerr << "Generating instruction variants.\n");
1761 // Loop over all of the patterns we've collected, checking to see if we can
1762 // generate variants of the instruction, through the exploitation of
1763 // identities. This permits the target to provide agressive matching without
1764 // the .td file having to contain tons of variants of instructions.
1766 // Note that this loop adds new patterns to the PatternsToMatch list, but we
1767 // intentionally do not reconsider these. Any variants of added patterns have
1768 // already been added.
1770 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
1771 std::vector<TreePatternNode*> Variants;
1772 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this);
1774 assert(!Variants.empty() && "Must create at least original variant!");
1775 Variants.erase(Variants.begin()); // Remove the original pattern.
1777 if (Variants.empty()) // No variants for this pattern.
1780 DEBUG(std::cerr << "FOUND VARIANTS OF: ";
1781 PatternsToMatch[i].getSrcPattern()->dump();
1784 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
1785 TreePatternNode *Variant = Variants[v];
1787 DEBUG(std::cerr << " VAR#" << v << ": ";
1791 // Scan to see if an instruction or explicit pattern already matches this.
1792 bool AlreadyExists = false;
1793 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
1794 // Check to see if this variant already exists.
1795 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern())) {
1796 DEBUG(std::cerr << " *** ALREADY EXISTS, ignoring variant.\n");
1797 AlreadyExists = true;
1801 // If we already have it, ignore the variant.
1802 if (AlreadyExists) continue;
1804 // Otherwise, add it to the list of patterns we have.
1806 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
1807 Variant, PatternsToMatch[i].getDstPattern()));
1810 DEBUG(std::cerr << "\n");
1815 // NodeIsComplexPattern - return true if N is a leaf node and a subclass of
1817 static bool NodeIsComplexPattern(TreePatternNode *N)
1819 return (N->isLeaf() &&
1820 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1821 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1822 isSubClassOf("ComplexPattern"));
1825 // NodeGetComplexPattern - return the pointer to the ComplexPattern if N
1826 // is a leaf node and a subclass of ComplexPattern, else it returns NULL.
1827 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
1828 DAGISelEmitter &ISE)
1831 dynamic_cast<DefInit*>(N->getLeafValue()) &&
1832 static_cast<DefInit*>(N->getLeafValue())->getDef()->
1833 isSubClassOf("ComplexPattern")) {
1834 return &ISE.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
1840 /// getPatternSize - Return the 'size' of this pattern. We want to match large
1841 /// patterns before small ones. This is used to determine the size of a
1843 static unsigned getPatternSize(TreePatternNode *P, DAGISelEmitter &ISE) {
1844 assert(isExtIntegerInVTs(P->getExtTypes()) ||
1845 isExtFloatingPointInVTs(P->getExtTypes()) ||
1846 P->getExtTypeNum(0) == MVT::isVoid ||
1847 P->getExtTypeNum(0) == MVT::Flag &&
1848 "Not a valid pattern node to size!");
1849 unsigned Size = 2; // The node itself.
1850 // If the root node is a ConstantSDNode, increases its size.
1851 // e.g. (set R32:$dst, 0).
1852 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
1855 // FIXME: This is a hack to statically increase the priority of patterns
1856 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
1857 // Later we can allow complexity / cost for each pattern to be (optionally)
1858 // specified. To get best possible pattern match we'll need to dynamically
1859 // calculate the complexity of all patterns a dag can potentially map to.
1860 const ComplexPattern *AM = NodeGetComplexPattern(P, ISE);
1862 Size += AM->getNumOperands() * 2;
1864 // If this node has some predicate function that must match, it adds to the
1865 // complexity of this node.
1866 if (!P->getPredicateFn().empty())
1869 // Count children in the count if they are also nodes.
1870 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1871 TreePatternNode *Child = P->getChild(i);
1872 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
1873 Size += getPatternSize(Child, ISE);
1874 else if (Child->isLeaf()) {
1875 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
1876 Size += 3; // Matches a ConstantSDNode (+2) and a specific value (+1).
1877 else if (NodeIsComplexPattern(Child))
1878 Size += getPatternSize(Child, ISE);
1879 else if (!Child->getPredicateFn().empty())
1887 /// getResultPatternCost - Compute the number of instructions for this pattern.
1888 /// This is a temporary hack. We should really include the instruction
1889 /// latencies in this calculation.
1890 static unsigned getResultPatternCost(TreePatternNode *P, DAGISelEmitter &ISE) {
1891 if (P->isLeaf()) return 0;
1894 Record *Op = P->getOperator();
1895 if (Op->isSubClassOf("Instruction")) {
1897 CodeGenInstruction &II = ISE.getTargetInfo().getInstruction(Op->getName());
1898 if (II.usesCustomDAGSchedInserter)
1901 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
1902 Cost += getResultPatternCost(P->getChild(i), ISE);
1906 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1907 // In particular, we want to match maximal patterns first and lowest cost within
1908 // a particular complexity first.
1909 struct PatternSortingPredicate {
1910 PatternSortingPredicate(DAGISelEmitter &ise) : ISE(ise) {};
1911 DAGISelEmitter &ISE;
1913 bool operator()(PatternToMatch *LHS,
1914 PatternToMatch *RHS) {
1915 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), ISE);
1916 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), ISE);
1917 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1918 if (LHSSize < RHSSize) return false;
1920 // If the patterns have equal complexity, compare generated instruction cost
1921 return getResultPatternCost(LHS->getDstPattern(), ISE) <
1922 getResultPatternCost(RHS->getDstPattern(), ISE);
1926 /// getRegisterValueType - Look up and return the first ValueType of specified
1927 /// RegisterClass record
1928 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
1929 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
1930 return RC->getValueTypeNum(0);
1935 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
1936 /// type information from it.
1937 static void RemoveAllTypes(TreePatternNode *N) {
1940 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1941 RemoveAllTypes(N->getChild(i));
1944 Record *DAGISelEmitter::getSDNodeNamed(const std::string &Name) const {
1945 Record *N = Records.getDef(Name);
1946 if (!N || !N->isSubClassOf("SDNode")) {
1947 std::cerr << "Error getting SDNode '" << Name << "'!\n";
1953 /// NodeHasProperty - return true if TreePatternNode has the specified
1955 static bool NodeHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1956 DAGISelEmitter &ISE)
1958 if (N->isLeaf()) return false;
1959 Record *Operator = N->getOperator();
1960 if (!Operator->isSubClassOf("SDNode")) return false;
1962 const SDNodeInfo &NodeInfo = ISE.getSDNodeInfo(Operator);
1963 return NodeInfo.hasProperty(Property);
1966 static bool PatternHasProperty(TreePatternNode *N, SDNodeInfo::SDNP Property,
1967 DAGISelEmitter &ISE)
1969 if (NodeHasProperty(N, Property, ISE))
1972 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1973 TreePatternNode *Child = N->getChild(i);
1974 if (PatternHasProperty(Child, Property, ISE))
1981 class PatternCodeEmitter {
1983 DAGISelEmitter &ISE;
1986 ListInit *Predicates;
1987 // Instruction selector pattern.
1988 TreePatternNode *Pattern;
1989 // Matched instruction.
1990 TreePatternNode *Instruction;
1992 // Node to name mapping
1993 std::map<std::string, std::string> VariableMap;
1994 // Node to operator mapping
1995 std::map<std::string, Record*> OperatorMap;
1996 // Names of all the folded nodes which produce chains.
1997 std::vector<std::pair<std::string, unsigned> > FoldedChains;
1998 std::set<std::string> Duplicates;
2000 /// GeneratedCode - This is the buffer that we emit code to. The first bool
2001 /// indicates whether this is an exit predicate (something that should be
2002 /// tested, and if true, the match fails) [when true] or normal code to emit
2004 std::vector<std::pair<bool, std::string> > &GeneratedCode;
2005 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
2006 /// the set of patterns for each top-level opcode.
2007 std::set<std::pair<bool, std::string> > &GeneratedDecl;
2009 std::string ChainName;
2014 void emitCheck(const std::string &S) {
2016 GeneratedCode.push_back(std::make_pair(true, S));
2018 void emitCode(const std::string &S) {
2020 GeneratedCode.push_back(std::make_pair(false, S));
2022 void emitDecl(const std::string &S, bool isSDNode=false) {
2023 assert(!S.empty() && "Invalid declaration");
2024 GeneratedDecl.insert(std::make_pair(isSDNode, S));
2027 PatternCodeEmitter(DAGISelEmitter &ise, ListInit *preds,
2028 TreePatternNode *pattern, TreePatternNode *instr,
2029 std::vector<std::pair<bool, std::string> > &gc,
2030 std::set<std::pair<bool, std::string> > &gd,
2032 : ISE(ise), Predicates(preds), Pattern(pattern), Instruction(instr),
2033 GeneratedCode(gc), GeneratedDecl(gd),
2034 NewTF(false), DoReplace(dorep), TmpNo(0) {}
2036 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
2037 /// if the match fails. At this point, we already know that the opcode for N
2038 /// matches, and the SDNode for the result has the RootName specified name.
2039 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
2040 const std::string &RootName, const std::string &ParentName,
2041 const std::string &ChainSuffix, bool &FoundChain) {
2042 bool isRoot = (P == NULL);
2043 // Emit instruction predicates. Each predicate is just a string for now.
2045 std::string PredicateCheck;
2046 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
2047 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
2048 Record *Def = Pred->getDef();
2049 if (!Def->isSubClassOf("Predicate")) {
2051 assert(0 && "Unknown predicate type!");
2053 if (!PredicateCheck.empty())
2054 PredicateCheck += " || ";
2055 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
2059 emitCheck(PredicateCheck);
2063 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2064 emitCheck("cast<ConstantSDNode>(" + RootName +
2065 ")->getSignExtended() == " + itostr(II->getValue()));
2067 } else if (!NodeIsComplexPattern(N)) {
2068 assert(0 && "Cannot match this as a leaf value!");
2073 // If this node has a name associated with it, capture it in VariableMap. If
2074 // we already saw this in the pattern, emit code to verify dagness.
2075 if (!N->getName().empty()) {
2076 std::string &VarMapEntry = VariableMap[N->getName()];
2077 if (VarMapEntry.empty()) {
2078 VarMapEntry = RootName;
2080 // If we get here, this is a second reference to a specific name. Since
2081 // we already have checked that the first reference is valid, we don't
2082 // have to recursively match it, just check that it's the same as the
2083 // previously named thing.
2084 emitCheck(VarMapEntry + " == " + RootName);
2089 OperatorMap[N->getName()] = N->getOperator();
2093 // Emit code to load the child nodes and match their contents recursively.
2095 bool NodeHasChain = NodeHasProperty (N, SDNodeInfo::SDNPHasChain, ISE);
2096 bool HasChain = PatternHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2097 bool HasOutFlag = PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE);
2098 bool EmittedUseCheck = false;
2099 bool EmittedSlctedCheck = false;
2104 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2105 // Multiple uses of actual result?
2106 emitCheck(RootName + ".hasOneUse()");
2107 EmittedUseCheck = true;
2108 // hasOneUse() check is not strong enough. If the original node has
2109 // already been selected, it may have been replaced with another.
2110 for (unsigned j = 0; j != CInfo.getNumResults(); j++)
2111 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2114 EmittedSlctedCheck = true;
2116 // FIXME: Don't fold if 1) the parent node writes a flag, 2) the node
2118 // This a workaround for this problem:
2123 // [XX]--/ \- [flag : cmp]
2128 // cmp + br should be considered as a single node as they are flagged
2129 // together. So, if the ld is folded into the cmp, the XX node in the
2130 // graph is now both an operand and a use of the ld/cmp/br node.
2131 if (NodeHasProperty(P, SDNodeInfo::SDNPOutFlag, ISE))
2132 emitCheck(ParentName + ".Val->isOnlyUse(" + RootName + ".Val)");
2134 // If the immediate use can somehow reach this node through another
2135 // path, then can't fold it either or it will create a cycle.
2136 // e.g. In the following diagram, XX can reach ld through YY. If
2137 // ld is folded into XX, then YY is both a predecessor and a successor
2147 const SDNodeInfo &PInfo = ISE.getSDNodeInfo(P->getOperator());
2148 if (PInfo.getNumOperands() > 1 ||
2149 PInfo.hasProperty(SDNodeInfo::SDNPHasChain) ||
2150 PInfo.hasProperty(SDNodeInfo::SDNPInFlag) ||
2151 PInfo.hasProperty(SDNodeInfo::SDNPOptInFlag))
2152 if (PInfo.getNumOperands() > 1) {
2153 emitCheck("!isNonImmUse(" + ParentName + ".Val, " + RootName +
2156 emitCheck("(" + ParentName + ".getNumOperands() == 1 || !" +
2157 "isNonImmUse(" + ParentName + ".Val, " + RootName +
2164 ChainName = "Chain" + ChainSuffix;
2165 emitDecl(ChainName);
2167 // FIXME: temporary workaround for a common case where chain
2168 // is a TokenFactor and the previous "inner" chain is an operand.
2170 emitDecl("OldTF", true);
2171 emitCheck("(" + ChainName + " = UpdateFoldedChain(CurDAG, " +
2172 RootName + ".Val, Chain.Val, OldTF)).Val");
2175 emitCode(ChainName + " = " + RootName + ".getOperand(0);");
2180 // Don't fold any node which reads or writes a flag and has multiple uses.
2181 // FIXME: We really need to separate the concepts of flag and "glue". Those
2182 // real flag results, e.g. X86CMP output, can have multiple uses.
2183 // FIXME: If the optional incoming flag does not exist. Then it is ok to
2186 (PatternHasProperty(N, SDNodeInfo::SDNPInFlag, ISE) ||
2187 PatternHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE) ||
2188 PatternHasProperty(N, SDNodeInfo::SDNPOutFlag, ISE))) {
2189 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(N->getOperator());
2190 if (!EmittedUseCheck) {
2191 // Multiple uses of actual result?
2192 emitCheck(RootName + ".hasOneUse()");
2194 if (!EmittedSlctedCheck)
2195 // hasOneUse() check is not strong enough. If the original node has
2196 // already been selected, it may have been replaced with another.
2197 for (unsigned j = 0; j < CInfo.getNumResults(); j++)
2198 emitCheck("!CodeGenMap.count(" + RootName + ".getValue(" + utostr(j) +
2202 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2203 emitDecl(RootName + utostr(OpNo));
2204 emitCode(RootName + utostr(OpNo) + " = " +
2205 RootName + ".getOperand(" +utostr(OpNo) + ");");
2206 TreePatternNode *Child = N->getChild(i);
2208 if (!Child->isLeaf()) {
2209 // If it's not a leaf, recursively match.
2210 const SDNodeInfo &CInfo = ISE.getSDNodeInfo(Child->getOperator());
2211 emitCheck(RootName + utostr(OpNo) + ".getOpcode() == " +
2212 CInfo.getEnumName());
2213 EmitMatchCode(Child, N, RootName + utostr(OpNo), RootName,
2214 ChainSuffix + utostr(OpNo), FoundChain);
2215 if (NodeHasProperty(Child, SDNodeInfo::SDNPHasChain, ISE))
2216 FoldedChains.push_back(std::make_pair(RootName + utostr(OpNo),
2217 CInfo.getNumResults()));
2219 // If this child has a name associated with it, capture it in VarMap. If
2220 // we already saw this in the pattern, emit code to verify dagness.
2221 if (!Child->getName().empty()) {
2222 std::string &VarMapEntry = VariableMap[Child->getName()];
2223 if (VarMapEntry.empty()) {
2224 VarMapEntry = RootName + utostr(OpNo);
2226 // If we get here, this is a second reference to a specific name.
2227 // Since we already have checked that the first reference is valid,
2228 // we don't have to recursively match it, just check that it's the
2229 // same as the previously named thing.
2230 emitCheck(VarMapEntry + " == " + RootName + utostr(OpNo));
2231 Duplicates.insert(RootName + utostr(OpNo));
2236 // Handle leaves of various types.
2237 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2238 Record *LeafRec = DI->getDef();
2239 if (LeafRec->isSubClassOf("RegisterClass")) {
2240 // Handle register references. Nothing to do here.
2241 } else if (LeafRec->isSubClassOf("Register")) {
2242 // Handle register references.
2243 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
2244 // Handle complex pattern. Nothing to do here.
2245 } else if (LeafRec->getName() == "srcvalue") {
2246 // Place holder for SRCVALUE nodes. Nothing to do here.
2247 } else if (LeafRec->isSubClassOf("ValueType")) {
2248 // Make sure this is the specified value type.
2249 emitCheck("cast<VTSDNode>(" + RootName + utostr(OpNo) +
2250 ")->getVT() == MVT::" + LeafRec->getName());
2251 } else if (LeafRec->isSubClassOf("CondCode")) {
2252 // Make sure this is the specified cond code.
2253 emitCheck("cast<CondCodeSDNode>(" + RootName + utostr(OpNo) +
2254 ")->get() == ISD::" + LeafRec->getName());
2258 assert(0 && "Unknown leaf type!");
2260 } else if (IntInit *II =
2261 dynamic_cast<IntInit*>(Child->getLeafValue())) {
2262 emitCheck("isa<ConstantSDNode>(" + RootName + utostr(OpNo) + ")");
2263 unsigned CTmp = TmpNo++;
2264 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
2265 RootName + utostr(OpNo) + ")->getSignExtended();");
2267 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
2270 assert(0 && "Unknown leaf type!");
2275 // If there is a node predicate for this, emit the call.
2276 if (!N->getPredicateFn().empty())
2277 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
2280 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
2281 /// we actually have to build a DAG!
2282 std::pair<unsigned, unsigned>
2283 EmitResultCode(TreePatternNode *N, bool LikeLeaf = false,
2284 bool isRoot = false) {
2285 // This is something selected from the pattern we matched.
2286 if (!N->getName().empty()) {
2287 std::string &Val = VariableMap[N->getName()];
2288 assert(!Val.empty() &&
2289 "Variable referenced but not defined and not caught earlier!");
2290 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
2291 // Already selected this operand, just return the tmpval.
2292 return std::make_pair(1, atoi(Val.c_str()+3));
2295 const ComplexPattern *CP;
2296 unsigned ResNo = TmpNo++;
2297 unsigned NumRes = 1;
2298 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
2299 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2300 std::string CastType;
2301 switch (N->getTypeNum(0)) {
2302 default: assert(0 && "Unknown type for constant node!");
2303 case MVT::i1: CastType = "bool"; break;
2304 case MVT::i8: CastType = "unsigned char"; break;
2305 case MVT::i16: CastType = "unsigned short"; break;
2306 case MVT::i32: CastType = "unsigned"; break;
2307 case MVT::i64: CastType = "uint64_t"; break;
2309 emitCode(CastType + " Tmp" + utostr(ResNo) + "C = (" + CastType +
2310 ")cast<ConstantSDNode>(" + Val + ")->getValue();");
2311 emitDecl("Tmp" + utostr(ResNo));
2312 emitCode("Tmp" + utostr(ResNo) +
2313 " = CurDAG->getTargetConstant(Tmp" + utostr(ResNo) +
2314 "C, MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2315 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2316 Record *Op = OperatorMap[N->getName()];
2317 // Transform ExternalSymbol to TargetExternalSymbol
2318 if (Op && Op->getName() == "externalsym") {
2319 emitDecl("Tmp" + utostr(ResNo));
2320 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2321 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
2322 Val + ")->getSymbol(), MVT::" +
2323 getEnumName(N->getTypeNum(0)) + ");");
2325 emitDecl("Tmp" + utostr(ResNo));
2326 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2328 } else if (!N->isLeaf() && N->getOperator()->getName() == "tglobaladdr") {
2329 Record *Op = OperatorMap[N->getName()];
2330 // Transform GlobalAddress to TargetGlobalAddress
2331 if (Op && Op->getName() == "globaladdr") {
2332 emitDecl("Tmp" + utostr(ResNo));
2333 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
2334 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
2335 ")->getGlobal(), MVT::" + getEnumName(N->getTypeNum(0)) +
2338 emitDecl("Tmp" + utostr(ResNo));
2339 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2341 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
2342 emitDecl("Tmp" + utostr(ResNo));
2343 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2344 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
2345 emitDecl("Tmp" + utostr(ResNo));
2346 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2347 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, ISE))) {
2348 std::string Fn = CP->getSelectFunc();
2349 NumRes = CP->getNumOperands();
2350 for (unsigned i = 0; i < NumRes; ++i)
2351 emitDecl("Tmp" + utostr(i+ResNo));
2353 std::string Code = Fn + "(" + Val;
2354 for (unsigned i = 0; i < NumRes; i++)
2355 Code += ", Tmp" + utostr(i + ResNo);
2356 emitCheck(Code + ")");
2358 for (unsigned i = 0; i < NumRes; ++i)
2359 emitCode("Select(Tmp" + utostr(i+ResNo) + ", Tmp" +
2360 utostr(i+ResNo) + ");");
2362 TmpNo = ResNo + NumRes;
2364 emitDecl("Tmp" + utostr(ResNo));
2365 // This node, probably wrapped in a SDNodeXForms, behaves like a leaf
2366 // node even if it isn't one. Don't select it.
2368 emitCode("Tmp" + utostr(ResNo) + " = " + Val + ";");
2370 emitCode("Select(Tmp" + utostr(ResNo) + ", " + Val + ");");
2372 if (isRoot && N->isLeaf()) {
2373 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2374 emitCode("return;");
2377 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
2378 // value if used multiple times by this pattern result.
2379 Val = "Tmp"+utostr(ResNo);
2380 return std::make_pair(NumRes, ResNo);
2383 // If this is an explicit register reference, handle it.
2384 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2385 unsigned ResNo = TmpNo++;
2386 if (DI->getDef()->isSubClassOf("Register")) {
2387 emitDecl("Tmp" + utostr(ResNo));
2388 emitCode("Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
2389 ISE.getQualifiedName(DI->getDef()) + ", MVT::" +
2390 getEnumName(N->getTypeNum(0)) + ");");
2391 return std::make_pair(1, ResNo);
2393 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
2394 unsigned ResNo = TmpNo++;
2395 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
2396 emitDecl("Tmp" + utostr(ResNo));
2397 emitCode("Tmp" + utostr(ResNo) +
2398 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
2399 ", MVT::" + getEnumName(N->getTypeNum(0)) + ");");
2400 return std::make_pair(1, ResNo);
2404 assert(0 && "Unknown leaf type!");
2405 return std::make_pair(1, ~0U);
2408 Record *Op = N->getOperator();
2409 if (Op->isSubClassOf("Instruction")) {
2410 const CodeGenTarget &CGT = ISE.getTargetInfo();
2411 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2412 const DAGInstruction &Inst = ISE.getInstruction(Op);
2413 bool HasImpInputs = Inst.getNumImpOperands() > 0;
2414 bool HasImpResults = Inst.getNumImpResults() > 0;
2415 bool HasOptInFlag = isRoot &&
2416 PatternHasProperty(Pattern, SDNodeInfo::SDNPOptInFlag, ISE);
2417 bool HasInFlag = isRoot &&
2418 PatternHasProperty(Pattern, SDNodeInfo::SDNPInFlag, ISE);
2419 bool NodeHasOutFlag = HasImpResults ||
2420 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPOutFlag, ISE));
2422 NodeHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE);
2423 bool HasChain = II.hasCtrlDep ||
2424 (isRoot && PatternHasProperty(Pattern, SDNodeInfo::SDNPHasChain, ISE));
2426 if (HasInFlag || NodeHasOutFlag || HasOptInFlag || HasImpInputs)
2429 emitCode("bool HasOptInFlag = false;");
2431 // How many results is this pattern expected to produce?
2432 unsigned PatResults = 0;
2433 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
2434 MVT::ValueType VT = Pattern->getTypeNum(i);
2435 if (VT != MVT::isVoid && VT != MVT::Flag)
2439 // Determine operand emission order. Complex pattern first.
2440 std::vector<std::pair<unsigned, TreePatternNode*> > EmitOrder;
2441 std::vector<std::pair<unsigned, TreePatternNode*> >::iterator OI;
2442 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2443 TreePatternNode *Child = N->getChild(i);
2445 EmitOrder.push_back(std::make_pair(i, Child));
2446 OI = EmitOrder.begin();
2447 } else if (NodeIsComplexPattern(Child)) {
2448 OI = EmitOrder.insert(OI, std::make_pair(i, Child));
2450 EmitOrder.push_back(std::make_pair(i, Child));
2454 // Emit all of the operands.
2455 std::vector<std::pair<unsigned, unsigned> > NumTemps(EmitOrder.size());
2456 for (unsigned i = 0, e = EmitOrder.size(); i != e; ++i) {
2457 unsigned OpOrder = EmitOrder[i].first;
2458 TreePatternNode *Child = EmitOrder[i].second;
2459 std::pair<unsigned, unsigned> NumTemp = EmitResultCode(Child);
2460 NumTemps[OpOrder] = NumTemp;
2463 // List all the operands in the right order.
2464 std::vector<unsigned> Ops;
2465 for (unsigned i = 0, e = NumTemps.size(); i != e; i++) {
2466 for (unsigned j = 0; j < NumTemps[i].first; j++)
2467 Ops.push_back(NumTemps[i].second + j);
2470 // Emit all the chain and CopyToReg stuff.
2471 bool ChainEmitted = HasChain;
2473 emitCode("Select(" + ChainName + ", " + ChainName + ");");
2474 if (HasInFlag || HasOptInFlag || HasImpInputs)
2475 EmitInFlagSelectCode(Pattern, "N", ChainEmitted, true);
2477 unsigned NumResults = Inst.getNumResults();
2478 unsigned ResNo = TmpNo++;
2480 emitDecl("Tmp" + utostr(ResNo));
2482 "Tmp" + utostr(ResNo) + " = SDOperand(CurDAG->getTargetNode(" +
2483 II.Namespace + "::" + II.TheDef->getName();
2484 if (N->getTypeNum(0) != MVT::isVoid)
2485 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2487 Code += ", MVT::Flag";
2489 unsigned LastOp = 0;
2490 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2492 Code += ", Tmp" + utostr(LastOp);
2494 emitCode(Code + "), 0);");
2496 // Must have at least one result
2497 emitCode(ChainName + " = Tmp" + utostr(LastOp) + ".getValue(" +
2498 utostr(NumResults) + ");");
2500 } else if (HasChain || NodeHasOutFlag) {
2502 unsigned FlagNo = (unsigned) NodeHasChain + Pattern->getNumChildren();
2503 emitDecl("ResNode", true);
2504 emitCode("if (HasOptInFlag)");
2505 std::string Code = " ResNode = CurDAG->getTargetNode(" +
2506 II.Namespace + "::" + II.TheDef->getName();
2508 // Output order: results, chain, flags
2510 if (NumResults > 0) {
2511 if (N->getTypeNum(0) != MVT::isVoid)
2512 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2515 Code += ", MVT::Other";
2517 Code += ", MVT::Flag";
2520 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2521 Code += ", Tmp" + utostr(Ops[i]);
2522 if (HasChain) Code += ", " + ChainName;
2523 emitCode(Code + ", InFlag);");
2526 Code = " ResNode = CurDAG->getTargetNode(" + II.Namespace + "::" +
2527 II.TheDef->getName();
2529 // Output order: results, chain, flags
2531 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2532 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2534 Code += ", MVT::Other";
2536 Code += ", MVT::Flag";
2539 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2540 Code += ", Tmp" + utostr(Ops[i]);
2541 if (HasChain) Code += ", " + ChainName + ");";
2544 emitDecl("ResNode", true);
2545 std::string Code = "ResNode = CurDAG->getTargetNode(" +
2546 II.Namespace + "::" + II.TheDef->getName();
2548 // Output order: results, chain, flags
2550 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid)
2551 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2553 Code += ", MVT::Other";
2555 Code += ", MVT::Flag";
2558 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2559 Code += ", Tmp" + utostr(Ops[i]);
2560 if (HasChain) Code += ", " + ChainName;
2561 if (HasInFlag || HasImpInputs) Code += ", InFlag";
2562 emitCode(Code + ");");
2566 emitCode("if (OldTF) "
2567 "SelectionDAG::InsertISelMapEntry(CodeGenMap, OldTF, 0, " +
2568 ChainName + ".Val, 0);");
2570 for (unsigned i = 0; i < NumResults; i++)
2571 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2572 utostr(i) + ", ResNode, " + utostr(i) + ");");
2575 emitCode("InFlag = SDOperand(ResNode, " +
2576 utostr(NumResults + (unsigned)HasChain) + ");");
2578 if (HasImpResults && EmitCopyFromRegs(N, ChainEmitted)) {
2579 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
2585 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2586 utostr(PatResults) + ", ResNode, " +
2587 utostr(NumResults) + ");");
2589 emitCode("if (N.ResNo == 0) AddHandleReplacement(N.Val, " +
2590 utostr(PatResults) + ", " + "ResNode, " +
2591 utostr(NumResults) + ");");
2594 if (FoldedChains.size() > 0) {
2596 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
2597 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, " +
2598 FoldedChains[j].first + ".Val, " +
2599 utostr(FoldedChains[j].second) + ", ResNode, " +
2600 utostr(NumResults) + ");");
2602 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
2604 FoldedChains[j].first + ".Val, " +
2605 utostr(FoldedChains[j].second) + ", ";
2606 emitCode("AddHandleReplacement(" + Code + "ResNode, " +
2607 utostr(NumResults) + ");");
2612 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, " +
2613 utostr(PatResults + (unsigned)NodeHasChain) +
2614 ", InFlag.Val, InFlag.ResNo);");
2616 // User does not expect the instruction would produce a chain!
2617 bool AddedChain = HasChain && !NodeHasChain;
2618 if (AddedChain && NodeHasOutFlag) {
2619 if (PatResults == 0) {
2620 emitCode("Result = SDOperand(ResNode, N.ResNo+1);");
2622 emitCode("if (N.ResNo < " + utostr(PatResults) + ")");
2623 emitCode(" Result = SDOperand(ResNode, N.ResNo);");
2625 emitCode(" Result = SDOperand(ResNode, N.ResNo+1);");
2628 emitCode("Result = SDOperand(ResNode, N.ResNo);");
2631 // If this instruction is the root, and if there is only one use of it,
2632 // use SelectNodeTo instead of getTargetNode to avoid an allocation.
2633 emitCode("if (N.Val->hasOneUse()) {");
2634 std::string Code = " Result = CurDAG->SelectNodeTo(N.Val, " +
2635 II.Namespace + "::" + II.TheDef->getName();
2636 if (N->getTypeNum(0) != MVT::isVoid)
2637 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2639 Code += ", MVT::Flag";
2640 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2641 Code += ", Tmp" + utostr(Ops[i]);
2642 if (HasInFlag || HasImpInputs)
2644 emitCode(Code + ");");
2645 emitCode("} else {");
2646 emitDecl("ResNode", true);
2647 Code = " ResNode = CurDAG->getTargetNode(" +
2648 II.Namespace + "::" + II.TheDef->getName();
2649 if (N->getTypeNum(0) != MVT::isVoid)
2650 Code += ", MVT::" + getEnumName(N->getTypeNum(0));
2652 Code += ", MVT::Flag";
2653 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2654 Code += ", Tmp" + utostr(Ops[i]);
2655 if (HasInFlag || HasImpInputs)
2657 emitCode(Code + ");");
2658 emitCode(" SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
2660 emitCode(" Result = SDOperand(ResNode, 0);");
2665 emitCode("return;");
2666 return std::make_pair(1, ResNo);
2667 } else if (Op->isSubClassOf("SDNodeXForm")) {
2668 assert(N->getNumChildren() == 1 && "node xform should have one child!");
2669 // PatLeaf node - the operand may or may not be a leaf node. But it should
2671 unsigned OpVal = EmitResultCode(N->getChild(0), true).second;
2672 unsigned ResNo = TmpNo++;
2673 emitDecl("Tmp" + utostr(ResNo));
2674 emitCode("Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
2675 + "(Tmp" + utostr(OpVal) + ".Val);");
2677 emitCode("SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val,"
2678 "N.ResNo, Tmp" + utostr(ResNo) + ".Val, Tmp" +
2679 utostr(ResNo) + ".ResNo);");
2680 emitCode("Result = Tmp" + utostr(ResNo) + ";");
2681 emitCode("return;");
2683 return std::make_pair(1, ResNo);
2687 throw std::string("Unknown node in result pattern!");
2691 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
2692 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
2693 /// 'Pat' may be missing types. If we find an unresolved type to add a check
2694 /// for, this returns true otherwise false if Pat has all types.
2695 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
2696 const std::string &Prefix) {
2698 if (!Pat->hasTypeSet()) {
2699 // Move a type over from 'other' to 'pat'.
2700 Pat->setTypes(Other->getExtTypes());
2701 emitCheck(Prefix + ".Val->getValueType(0) == MVT::" +
2702 getName(Pat->getTypeNum(0)));
2707 (unsigned) NodeHasProperty(Pat, SDNodeInfo::SDNPHasChain, ISE);
2708 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
2709 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
2710 Prefix + utostr(OpNo)))
2716 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
2718 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
2719 bool &ChainEmitted, bool isRoot = false) {
2720 const CodeGenTarget &T = ISE.getTargetInfo();
2722 (unsigned) NodeHasProperty(N, SDNodeInfo::SDNPHasChain, ISE);
2723 bool HasInFlag = NodeHasProperty(N, SDNodeInfo::SDNPInFlag, ISE);
2724 bool HasOptInFlag = NodeHasProperty(N, SDNodeInfo::SDNPOptInFlag, ISE);
2725 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
2726 TreePatternNode *Child = N->getChild(i);
2727 if (!Child->isLeaf()) {
2728 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted);
2730 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2731 if (!Child->getName().empty()) {
2732 std::string Name = RootName + utostr(OpNo);
2733 if (Duplicates.find(Name) != Duplicates.end())
2734 // A duplicate! Do not emit a copy for this node.
2738 Record *RR = DI->getDef();
2739 if (RR->isSubClassOf("Register")) {
2740 MVT::ValueType RVT = getRegisterValueType(RR, T);
2741 if (RVT == MVT::Flag) {
2742 emitCode("Select(InFlag, " + RootName + utostr(OpNo) + ");");
2744 if (!ChainEmitted) {
2746 emitCode("Chain = CurDAG->getEntryNode();");
2747 ChainName = "Chain";
2748 ChainEmitted = true;
2750 emitCode("Select(" + RootName + utostr(OpNo) + ", " +
2751 RootName + utostr(OpNo) + ");");
2752 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
2753 ", CurDAG->getRegister(" + ISE.getQualifiedName(RR) +
2754 ", MVT::" + getEnumName(RVT) + "), " +
2755 RootName + utostr(OpNo) + ", InFlag).Val;");
2756 emitCode(ChainName + " = SDOperand(ResNode, 0);");
2757 emitCode("InFlag = SDOperand(ResNode, 1);");
2764 if (HasInFlag || HasOptInFlag) {
2767 emitCode("if (" + RootName + ".getNumOperands() == " + utostr(OpNo+1) +
2771 emitCode(Code + "Select(InFlag, " + RootName +
2772 ".getOperand(" + utostr(OpNo) + "));");
2774 emitCode(" HasOptInFlag = true;");
2780 /// EmitCopyFromRegs - Emit code to copy result to physical registers
2781 /// as specified by the instruction. It returns true if any copy is
2783 bool EmitCopyFromRegs(TreePatternNode *N, bool &ChainEmitted) {
2784 bool RetVal = false;
2785 Record *Op = N->getOperator();
2786 if (Op->isSubClassOf("Instruction")) {
2787 const DAGInstruction &Inst = ISE.getInstruction(Op);
2788 const CodeGenTarget &CGT = ISE.getTargetInfo();
2789 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
2790 unsigned NumImpResults = Inst.getNumImpResults();
2791 for (unsigned i = 0; i < NumImpResults; i++) {
2792 Record *RR = Inst.getImpResult(i);
2793 if (RR->isSubClassOf("Register")) {
2794 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
2795 if (RVT != MVT::Flag) {
2796 if (!ChainEmitted) {
2798 emitCode("Chain = CurDAG->getEntryNode();");
2799 ChainEmitted = true;
2800 ChainName = "Chain";
2802 emitCode("ResNode = CurDAG->getCopyFromReg(" + ChainName + ", " +
2803 ISE.getQualifiedName(RR) + ", MVT::" + getEnumName(RVT) +
2805 emitCode(ChainName + " = SDOperand(ResNode, 1);");
2806 emitCode("InFlag = SDOperand(ResNode, 2);");
2816 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
2817 /// stream to match the pattern, and generate the code for the match if it
2818 /// succeeds. Returns true if the pattern is not guaranteed to match.
2819 void DAGISelEmitter::GenerateCodeForPattern(PatternToMatch &Pattern,
2820 std::vector<std::pair<bool, std::string> > &GeneratedCode,
2821 std::set<std::pair<bool, std::string> > &GeneratedDecl,
2823 PatternCodeEmitter Emitter(*this, Pattern.getPredicates(),
2824 Pattern.getSrcPattern(), Pattern.getDstPattern(),
2825 GeneratedCode, GeneratedDecl, DoReplace);
2827 // Emit the matcher, capturing named arguments in VariableMap.
2828 bool FoundChain = false;
2829 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", "", FoundChain);
2831 // TP - Get *SOME* tree pattern, we don't care which.
2832 TreePattern &TP = *PatternFragments.begin()->second;
2834 // At this point, we know that we structurally match the pattern, but the
2835 // types of the nodes may not match. Figure out the fewest number of type
2836 // comparisons we need to emit. For example, if there is only one integer
2837 // type supported by a target, there should be no type comparisons at all for
2838 // integer patterns!
2840 // To figure out the fewest number of type checks needed, clone the pattern,
2841 // remove the types, then perform type inference on the pattern as a whole.
2842 // If there are unresolved types, emit an explicit check for those types,
2843 // apply the type to the tree, then rerun type inference. Iterate until all
2844 // types are resolved.
2846 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
2847 RemoveAllTypes(Pat);
2850 // Resolve/propagate as many types as possible.
2852 bool MadeChange = true;
2854 MadeChange = Pat->ApplyTypeConstraints(TP,
2855 true/*Ignore reg constraints*/);
2857 assert(0 && "Error: could not find consistent types for something we"
2858 " already decided was ok!");
2862 // Insert a check for an unresolved type and add it to the tree. If we find
2863 // an unresolved type to add a check for, this returns true and we iterate,
2864 // otherwise we are done.
2865 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N"));
2867 Emitter.EmitResultCode(Pattern.getDstPattern(), false, true /*the root*/);
2871 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
2872 /// a line causes any of them to be empty, remove them and return true when
2874 static bool EraseCodeLine(std::vector<std::pair<PatternToMatch*,
2875 std::vector<std::pair<bool, std::string> > > >
2877 bool ErasedPatterns = false;
2878 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2879 Patterns[i].second.pop_back();
2880 if (Patterns[i].second.empty()) {
2881 Patterns.erase(Patterns.begin()+i);
2883 ErasedPatterns = true;
2886 return ErasedPatterns;
2889 /// EmitPatterns - Emit code for at least one pattern, but try to group common
2890 /// code together between the patterns.
2891 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<PatternToMatch*,
2892 std::vector<std::pair<bool, std::string> > > >
2893 &Patterns, unsigned Indent,
2895 typedef std::pair<bool, std::string> CodeLine;
2896 typedef std::vector<CodeLine> CodeList;
2897 typedef std::vector<std::pair<PatternToMatch*, CodeList> > PatternList;
2899 if (Patterns.empty()) return;
2901 // Figure out how many patterns share the next code line. Explicitly copy
2902 // FirstCodeLine so that we don't invalidate a reference when changing
2904 const CodeLine FirstCodeLine = Patterns.back().second.back();
2905 unsigned LastMatch = Patterns.size()-1;
2906 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
2909 // If not all patterns share this line, split the list into two pieces. The
2910 // first chunk will use this line, the second chunk won't.
2911 if (LastMatch != 0) {
2912 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
2913 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
2915 // FIXME: Emit braces?
2916 if (Shared.size() == 1) {
2917 PatternToMatch &Pattern = *Shared.back().first;
2918 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2919 Pattern.getSrcPattern()->print(OS);
2920 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2921 Pattern.getDstPattern()->print(OS);
2923 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2924 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
2925 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
2927 if (!FirstCodeLine.first) {
2928 OS << std::string(Indent, ' ') << "{\n";
2931 EmitPatterns(Shared, Indent, OS);
2932 if (!FirstCodeLine.first) {
2934 OS << std::string(Indent, ' ') << "}\n";
2937 if (Other.size() == 1) {
2938 PatternToMatch &Pattern = *Other.back().first;
2939 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
2940 Pattern.getSrcPattern()->print(OS);
2941 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
2942 Pattern.getDstPattern()->print(OS);
2944 OS << std::string(Indent, ' ') << "// Pattern complexity = "
2945 << getPatternSize(Pattern.getSrcPattern(), *this) << " cost = "
2946 << getResultPatternCost(Pattern.getDstPattern(), *this) << "\n";
2948 EmitPatterns(Other, Indent, OS);
2952 // Remove this code from all of the patterns that share it.
2953 bool ErasedPatterns = EraseCodeLine(Patterns);
2955 bool isPredicate = FirstCodeLine.first;
2957 // Otherwise, every pattern in the list has this line. Emit it.
2960 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
2962 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
2964 // If the next code line is another predicate, and if all of the pattern
2965 // in this group share the same next line, emit it inline now. Do this
2966 // until we run out of common predicates.
2967 while (!ErasedPatterns && Patterns.back().second.back().first) {
2968 // Check that all of fhe patterns in Patterns end with the same predicate.
2969 bool AllEndWithSamePredicate = true;
2970 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
2971 if (Patterns[i].second.back() != Patterns.back().second.back()) {
2972 AllEndWithSamePredicate = false;
2975 // If all of the predicates aren't the same, we can't share them.
2976 if (!AllEndWithSamePredicate) break;
2978 // Otherwise we can. Emit it shared now.
2979 OS << " &&\n" << std::string(Indent+4, ' ')
2980 << Patterns.back().second.back().second;
2981 ErasedPatterns = EraseCodeLine(Patterns);
2988 EmitPatterns(Patterns, Indent, OS);
2991 OS << std::string(Indent-2, ' ') << "}\n";
2997 /// CompareByRecordName - An ordering predicate that implements less-than by
2998 /// comparing the names records.
2999 struct CompareByRecordName {
3000 bool operator()(const Record *LHS, const Record *RHS) const {
3001 // Sort by name first.
3002 if (LHS->getName() < RHS->getName()) return true;
3003 // If both names are equal, sort by pointer.
3004 return LHS->getName() == RHS->getName() && LHS < RHS;
3009 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
3010 std::string InstNS = Target.inst_begin()->second.Namespace;
3011 if (!InstNS.empty()) InstNS += "::";
3013 // Group the patterns by their top-level opcodes.
3014 std::map<Record*, std::vector<PatternToMatch*>,
3015 CompareByRecordName> PatternsByOpcode;
3016 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3017 TreePatternNode *Node = PatternsToMatch[i].getSrcPattern();
3018 if (!Node->isLeaf()) {
3019 PatternsByOpcode[Node->getOperator()].push_back(&PatternsToMatch[i]);
3021 const ComplexPattern *CP;
3023 dynamic_cast<IntInit*>(Node->getLeafValue())) {
3024 PatternsByOpcode[getSDNodeNamed("imm")].push_back(&PatternsToMatch[i]);
3025 } else if ((CP = NodeGetComplexPattern(Node, *this))) {
3026 std::vector<Record*> OpNodes = CP->getRootNodes();
3027 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
3028 PatternsByOpcode[OpNodes[j]]
3029 .insert(PatternsByOpcode[OpNodes[j]].begin(), &PatternsToMatch[i]);
3032 std::cerr << "Unrecognized opcode '";
3034 std::cerr << "' on tree pattern '";
3036 PatternsToMatch[i].getDstPattern()->getOperator()->getName();
3037 std::cerr << "'!\n";
3043 // Emit one Select_* method for each top-level opcode. We do this instead of
3044 // emitting one giant switch statement to support compilers where this will
3045 // result in the recursive functions taking less stack space.
3046 for (std::map<Record*, std::vector<PatternToMatch*>,
3047 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3048 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3049 const std::string &OpName = PBOI->first->getName();
3050 OS << "void Select_" << OpName << "(SDOperand &Result, SDOperand N) {\n";
3052 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3054 (OpcodeInfo.hasProperty(SDNodeInfo::SDNPHasChain) &&
3055 OpcodeInfo.getNumResults() > 0);
3058 OS << " if (N.ResNo == " << OpcodeInfo.getNumResults()
3059 << " && N.getValue(0).hasOneUse()) {\n"
3060 << " SDOperand Dummy = "
3061 << "CurDAG->getNode(ISD::HANDLENODE, MVT::Other, N);\n"
3062 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, "
3063 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3064 << " SelectionDAG::InsertISelMapEntry(HandleMap, N.Val, "
3065 << OpcodeInfo.getNumResults() << ", Dummy.Val, 0);\n"
3066 << " Result = Dummy;\n"
3071 std::vector<PatternToMatch*> &Patterns = PBOI->second;
3072 assert(!Patterns.empty() && "No patterns but map has entry?");
3074 // We want to emit all of the matching code now. However, we want to emit
3075 // the matches in order of minimal cost. Sort the patterns so the least
3076 // cost one is at the start.
3077 std::stable_sort(Patterns.begin(), Patterns.end(),
3078 PatternSortingPredicate(*this));
3080 typedef std::vector<std::pair<bool, std::string> > CodeList;
3081 typedef std::set<std::string> DeclSet;
3083 std::vector<std::pair<PatternToMatch*, CodeList> > CodeForPatterns;
3084 std::set<std::pair<bool, std::string> > GeneratedDecl;
3085 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3086 CodeList GeneratedCode;
3087 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
3089 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
3092 // Scan the code to see if all of the patterns are reachable and if it is
3093 // possible that the last one might not match.
3094 bool mightNotMatch = true;
3095 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3096 CodeList &GeneratedCode = CodeForPatterns[i].second;
3097 mightNotMatch = false;
3099 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
3100 if (GeneratedCode[j].first) { // predicate.
3101 mightNotMatch = true;
3106 // If this pattern definitely matches, and if it isn't the last one, the
3107 // patterns after it CANNOT ever match. Error out.
3108 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
3109 std::cerr << "Pattern '";
3110 CodeForPatterns[i+1].first->getSrcPattern()->print(OS);
3111 std::cerr << "' is impossible to select!\n";
3116 // Print all declarations.
3117 for (std::set<std::pair<bool, std::string> >::iterator
3118 I = GeneratedDecl.begin(), E = GeneratedDecl.end(); I != E; ++I)
3120 OS << " SDNode *" << I->second << ";\n";
3122 OS << " SDOperand " << I->second << "(0, 0);\n";
3124 // Loop through and reverse all of the CodeList vectors, as we will be
3125 // accessing them from their logical front, but accessing the end of a
3126 // vector is more efficient.
3127 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
3128 CodeList &GeneratedCode = CodeForPatterns[i].second;
3129 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
3132 // Next, reverse the list of patterns itself for the same reason.
3133 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
3135 // Emit all of the patterns now, grouped together to share code.
3136 EmitPatterns(CodeForPatterns, 2, OS);
3138 // If the last pattern has predicates (which could fail) emit code to catch
3139 // the case where nothing handles a pattern.
3140 if (mightNotMatch) {
3141 OS << " std::cerr << \"Cannot yet select: \";\n";
3142 if (OpcodeInfo.getEnumName() != "ISD::INTRINSIC_W_CHAIN" &&
3143 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_WO_CHAIN" &&
3144 OpcodeInfo.getEnumName() != "ISD::INTRINSIC_VOID") {
3145 OS << " N.Val->dump(CurDAG);\n";
3147 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3148 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3149 << " std::cerr << \"intrinsic %\"<< "
3150 "Intrinsic::getName((Intrinsic::ID)iid);\n";
3152 OS << " std::cerr << '\\n';\n"
3158 // Emit boilerplate.
3159 OS << "void Select_INLINEASM(SDOperand& Result, SDOperand N) {\n"
3160 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
3161 << " Select(Ops[0], N.getOperand(0)); // Select the chain.\n\n"
3162 << " // Select the flag operand.\n"
3163 << " if (Ops.back().getValueType() == MVT::Flag)\n"
3164 << " Select(Ops.back(), Ops.back());\n"
3165 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n"
3166 << " std::vector<MVT::ValueType> VTs;\n"
3167 << " VTs.push_back(MVT::Other);\n"
3168 << " VTs.push_back(MVT::Flag);\n"
3169 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, Ops);\n"
3170 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, New.Val, 0);\n"
3171 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, New.Val, 1);\n"
3172 << " Result = New.getValue(N.ResNo);\n"
3176 OS << "// The main instruction selector code.\n"
3177 << "void SelectCode(SDOperand &Result, SDOperand N) {\n"
3178 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
3179 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
3180 << "INSTRUCTION_LIST_END)) {\n"
3182 << " return; // Already selected.\n"
3184 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
3185 << " if (CGMI != CodeGenMap.end()) {\n"
3186 << " Result = CGMI->second;\n"
3189 << " switch (N.getOpcode()) {\n"
3190 << " default: break;\n"
3191 << " case ISD::EntryToken: // These leaves remain the same.\n"
3192 << " case ISD::BasicBlock:\n"
3193 << " case ISD::Register:\n"
3194 << " case ISD::HANDLENODE:\n"
3195 << " case ISD::TargetConstant:\n"
3196 << " case ISD::TargetConstantPool:\n"
3197 << " case ISD::TargetFrameIndex:\n"
3198 << " case ISD::TargetGlobalAddress: {\n"
3202 << " case ISD::AssertSext:\n"
3203 << " case ISD::AssertZext: {\n"
3204 << " SDOperand Tmp0;\n"
3205 << " Select(Tmp0, N.getOperand(0));\n"
3206 << " if (!N.Val->hasOneUse())\n"
3207 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3208 << "Tmp0.Val, Tmp0.ResNo);\n"
3209 << " Result = Tmp0;\n"
3212 << " case ISD::TokenFactor:\n"
3213 << " if (N.getNumOperands() == 2) {\n"
3214 << " SDOperand Op0, Op1;\n"
3215 << " Select(Op0, N.getOperand(0));\n"
3216 << " Select(Op1, N.getOperand(1));\n"
3218 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);\n"
3219 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3220 << "Result.Val, Result.ResNo);\n"
3222 << " std::vector<SDOperand> Ops;\n"
3223 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i) {\n"
3224 << " SDOperand Val;\n"
3225 << " Select(Val, N.getOperand(i));\n"
3226 << " Ops.push_back(Val);\n"
3229 << " CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n"
3230 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, N.ResNo, "
3231 << "Result.Val, Result.ResNo);\n"
3234 << " case ISD::CopyFromReg: {\n"
3235 << " SDOperand Chain;\n"
3236 << " Select(Chain, N.getOperand(0));\n"
3237 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3238 << " MVT::ValueType VT = N.Val->getValueType(0);\n"
3239 << " if (N.Val->getNumValues() == 2) {\n"
3240 << " if (Chain == N.getOperand(0)) {\n"
3241 << " Result = N; // No change\n"
3244 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT);\n"
3245 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3247 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3249 << " Result = New.getValue(N.ResNo);\n"
3252 << " SDOperand Flag;\n"
3253 << " if (N.getNumOperands() == 3) Select(Flag, N.getOperand(2));\n"
3254 << " if (Chain == N.getOperand(0) &&\n"
3255 << " (N.getNumOperands() == 2 || Flag == N.getOperand(2))) {\n"
3256 << " Result = N; // No change\n"
3259 << " SDOperand New = CurDAG->getCopyFromReg(Chain, Reg, VT, Flag);\n"
3260 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3262 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3264 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 2, "
3266 << " Result = New.getValue(N.ResNo);\n"
3270 << " case ISD::CopyToReg: {\n"
3271 << " SDOperand Chain;\n"
3272 << " Select(Chain, N.getOperand(0));\n"
3273 << " unsigned Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();\n"
3274 << " SDOperand Val;\n"
3275 << " Select(Val, N.getOperand(2));\n"
3277 << " if (N.Val->getNumValues() == 1) {\n"
3278 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2))\n"
3279 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val);\n"
3280 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3281 << "Result.Val, 0);\n"
3283 << " SDOperand Flag(0, 0);\n"
3284 << " if (N.getNumOperands() == 4) Select(Flag, N.getOperand(3));\n"
3285 << " if (Chain != N.getOperand(0) || Val != N.getOperand(2) ||\n"
3286 << " (N.getNumOperands() == 4 && Flag != N.getOperand(3)))\n"
3287 << " Result = CurDAG->getCopyToReg(Chain, Reg, Val, Flag);\n"
3288 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 0, "
3289 << "Result.Val, 0);\n"
3290 << " SelectionDAG::InsertISelMapEntry(CodeGenMap, N.Val, 1, "
3291 << "Result.Val, 1);\n"
3292 << " Result = Result.getValue(N.ResNo);\n"
3296 << " case ISD::INLINEASM: Select_INLINEASM(Result, N); return;\n";
3299 // Loop over all of the case statements, emiting a call to each method we
3301 for (std::map<Record*, std::vector<PatternToMatch*>,
3302 CompareByRecordName>::iterator PBOI = PatternsByOpcode.begin(),
3303 E = PatternsByOpcode.end(); PBOI != E; ++PBOI) {
3304 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
3305 OS << " case " << OpcodeInfo.getEnumName() << ": "
3306 << std::string(std::max(0, int(24-OpcodeInfo.getEnumName().size())), ' ')
3307 << "Select_" << PBOI->first->getName() << "(Result, N); return;\n";
3310 OS << " } // end of big switch.\n\n"
3311 << " std::cerr << \"Cannot yet select: \";\n"
3312 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
3313 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
3314 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
3315 << " N.Val->dump(CurDAG);\n"
3317 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
3318 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
3319 << " std::cerr << \"intrinsic %\"<< "
3320 "Intrinsic::getName((Intrinsic::ID)iid);\n"
3322 << " std::cerr << '\\n';\n"
3327 void DAGISelEmitter::run(std::ostream &OS) {
3328 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
3331 OS << "// *** NOTE: This file is #included into the middle of the target\n"
3332 << "// *** instruction selector class. These functions are really "
3335 OS << "// Instance var to keep track of multiply used nodes that have \n"
3336 << "// already been selected.\n"
3337 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
3339 OS << "// Instance var to keep track of mapping of chain generating nodes\n"
3340 << "// and their place handle nodes.\n";
3341 OS << "std::map<SDOperand, SDOperand> HandleMap;\n";
3342 OS << "// Instance var to keep track of mapping of place handle nodes\n"
3343 << "// and their replacement nodes.\n";
3344 OS << "std::map<SDOperand, SDOperand> ReplaceMap;\n";
3347 OS << "static void findNonImmUse(SDNode* Use, SDNode* Def, bool &found, "
3348 << "std::set<SDNode *> &Visited) {\n";
3349 OS << " if (found || !Visited.insert(Use).second) return;\n";
3350 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3351 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3352 OS << " if (N->getNodeDepth() >= Def->getNodeDepth()) {\n";
3353 OS << " if (N != Def) {\n";
3354 OS << " findNonImmUse(N, Def, found, Visited);\n";
3355 OS << " } else {\n";
3356 OS << " found = true;\n";
3364 OS << "static bool isNonImmUse(SDNode* Use, SDNode* Def) {\n";
3365 OS << " std::set<SDNode *> Visited;\n";
3366 OS << " bool found = false;\n";
3367 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3368 OS << " SDNode *N = Use->getOperand(i).Val;\n";
3369 OS << " if (N != Def) {\n";
3370 OS << " findNonImmUse(N, Def, found, Visited);\n";
3371 OS << " if (found) break;\n";
3374 OS << " return found;\n";
3378 OS << "// AddHandleReplacement - Note the pending replacement node for a\n"
3379 << "// handle node in ReplaceMap.\n";
3380 OS << "void AddHandleReplacement(SDNode *H, unsigned HNum, SDNode *R, "
3381 << "unsigned RNum) {\n";
3382 OS << " SDOperand N(H, HNum);\n";
3383 OS << " std::map<SDOperand, SDOperand>::iterator HMI = HandleMap.find(N);\n";
3384 OS << " if (HMI != HandleMap.end()) {\n";
3385 OS << " ReplaceMap[HMI->second] = SDOperand(R, RNum);\n";
3386 OS << " HandleMap.erase(N);\n";
3391 OS << "// SelectDanglingHandles - Select replacements for all `dangling`\n";
3392 OS << "// handles.Some handles do not yet have replacements because the\n";
3393 OS << "// nodes they replacements have only dead readers.\n";
3394 OS << "void SelectDanglingHandles() {\n";
3395 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3396 << "HandleMap.begin(),\n"
3397 << " E = HandleMap.end(); I != E; ++I) {\n";
3398 OS << " SDOperand N = I->first;\n";
3399 OS << " SDOperand R;\n";
3400 OS << " Select(R, N.getValue(0));\n";
3401 OS << " AddHandleReplacement(N.Val, N.ResNo, R.Val, R.ResNo);\n";
3405 OS << "// ReplaceHandles - Replace all the handles with the real target\n";
3406 OS << "// specific nodes.\n";
3407 OS << "void ReplaceHandles() {\n";
3408 OS << " for (std::map<SDOperand, SDOperand>::iterator I = "
3409 << "ReplaceMap.begin(),\n"
3410 << " E = ReplaceMap.end(); I != E; ++I) {\n";
3411 OS << " SDOperand From = I->first;\n";
3412 OS << " SDOperand To = I->second;\n";
3413 OS << " for (SDNode::use_iterator UI = From.Val->use_begin(), "
3414 << "E = From.Val->use_end(); UI != E; ++UI) {\n";
3415 OS << " SDNode *Use = *UI;\n";
3416 OS << " std::vector<SDOperand> Ops;\n";
3417 OS << " for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {\n";
3418 OS << " SDOperand O = Use->getOperand(i);\n";
3419 OS << " if (O.Val == From.Val)\n";
3420 OS << " Ops.push_back(To);\n";
3422 OS << " Ops.push_back(O);\n";
3424 OS << " SDOperand U = SDOperand(Use, 0);\n";
3425 OS << " CurDAG->UpdateNodeOperands(U, Ops);\n";
3431 OS << "// UpdateFoldedChain - return a SDOperand of the new chain created\n";
3432 OS << "// if the folding were to happen. This is called when, for example,\n";
3433 OS << "// a load is folded into a store. If the store's chain is the load,\n";
3434 OS << "// then the resulting node's input chain would be the load's input\n";
3435 OS << "// chain. If the store's chain is a TokenFactor and the load's\n";
3436 OS << "// output chain feeds into in, then the new chain is a TokenFactor\n";
3437 OS << "// with the other operands along with the input chain of the load.\n";
3438 OS << "SDOperand UpdateFoldedChain(SelectionDAG *DAG, SDNode *N, "
3439 << "SDNode *Chain, SDNode* &OldTF) {\n";
3440 OS << " OldTF = NULL;\n";
3441 OS << " if (N == Chain) {\n";
3442 OS << " return N->getOperand(0);\n";
3443 OS << " } else if (Chain->getOpcode() == ISD::TokenFactor &&\n";
3444 OS << " N->isOperand(Chain)) {\n";
3445 OS << " SDOperand Ch = SDOperand(Chain, 0);\n";
3446 OS << " std::map<SDOperand, SDOperand>::iterator CGMI = "
3447 << "CodeGenMap.find(Ch);\n";
3448 OS << " if (CGMI != CodeGenMap.end())\n";
3449 OS << " return SDOperand(0, 0);\n";
3450 OS << " OldTF = Chain;\n";
3451 OS << " std::vector<SDOperand> Ops;\n";
3452 OS << " for (unsigned i = 0; i < Chain->getNumOperands(); ++i) {\n";
3453 OS << " SDOperand Op = Chain->getOperand(i);\n";
3454 OS << " if (Op.Val == N)\n";
3455 OS << " Ops.push_back(N->getOperand(0));\n";
3457 OS << " Ops.push_back(Op);\n";
3459 OS << " return DAG->getNode(ISD::TokenFactor, MVT::Other, Ops);\n";
3461 OS << " return SDOperand(0, 0);\n";
3465 OS << "// SelectRoot - Top level entry to DAG isel.\n";
3466 OS << "SDOperand SelectRoot(SDOperand N) {\n";
3467 OS << " SDOperand ResNode;\n";
3468 OS << " Select(ResNode, N);\n";
3469 OS << " SelectDanglingHandles();\n";
3470 OS << " ReplaceHandles();\n";
3471 OS << " ReplaceMap.clear();\n";
3472 OS << " return ResNode;\n";
3475 Intrinsics = LoadIntrinsics(Records);
3477 ParseNodeTransforms(OS);
3478 ParseComplexPatterns();
3479 ParsePatternFragments(OS);
3480 ParseInstructions();
3483 // Generate variants. For example, commutative patterns can match
3484 // multiple ways. Add them to PatternsToMatch as well.
3488 DEBUG(std::cerr << "\n\nALL PATTERNS TO MATCH:\n\n";
3489 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3490 std::cerr << "PATTERN: "; PatternsToMatch[i].getSrcPattern()->dump();
3491 std::cerr << "\nRESULT: ";PatternsToMatch[i].getDstPattern()->dump();
3495 // At this point, we have full information about the 'Patterns' we need to
3496 // parse, both implicitly from instructions as well as from explicit pattern
3497 // definitions. Emit the resultant instruction selector.
3498 EmitInstructionSelector(OS);
3500 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
3501 E = PatternFragments.end(); I != E; ++I)
3503 PatternFragments.clear();
3505 Instructions.clear();