1 //===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "DAGISelMatcher.h"
11 #include "CodeGenDAGPatterns.h"
12 #include "CodeGenRegisters.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringMap.h"
21 /// getRegisterValueType - Look up and return the ValueType of the specified
22 /// register. If the register is a member of multiple register classes which
23 /// have different associated types, return MVT::Other.
24 static MVT::SimpleValueType getRegisterValueType(Record *R,
25 const CodeGenTarget &T) {
27 MVT::SimpleValueType VT = MVT::Other;
28 const CodeGenRegister *Reg = T.getRegBank().getReg(R);
29 ArrayRef<CodeGenRegisterClass*> RCs = T.getRegBank().getRegClasses();
31 for (unsigned rc = 0, e = RCs.size(); rc != e; ++rc) {
32 const CodeGenRegisterClass &RC = *RCs[rc];
33 if (!RC.contains(Reg))
38 VT = RC.getValueTypeNum(0);
42 // If this occurs in multiple register classes, they all have to agree.
43 assert(VT == RC.getValueTypeNum(0));
51 const PatternToMatch &Pattern;
52 const CodeGenDAGPatterns &CGP;
54 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
55 /// out with all of the types removed. This allows us to insert type checks
56 /// as we scan the tree.
57 TreePatternNode *PatWithNoTypes;
59 /// VariableMap - A map from variable names ('$dst') to the recorded operand
60 /// number that they were captured as. These are biased by 1 to make
62 StringMap<unsigned> VariableMap;
64 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
65 /// the RecordedNodes array, this keeps track of which slot will be next to
67 unsigned NextRecordedOperandNo;
69 /// MatchedChainNodes - This maintains the position in the recorded nodes
70 /// array of all of the recorded input nodes that have chains.
71 SmallVector<unsigned, 2> MatchedChainNodes;
73 /// MatchedGlueResultNodes - This maintains the position in the recorded
74 /// nodes array of all of the recorded input nodes that have glue results.
75 SmallVector<unsigned, 2> MatchedGlueResultNodes;
77 /// MatchedComplexPatterns - This maintains a list of all of the
78 /// ComplexPatterns that we need to check. The patterns are known to have
79 /// names which were recorded. The second element of each pair is the first
80 /// slot number that the OPC_CheckComplexPat opcode drops the matched
82 SmallVector<std::pair<const TreePatternNode*,
83 unsigned>, 2> MatchedComplexPatterns;
85 /// PhysRegInputs - List list has an entry for each explicitly specified
86 /// physreg input to the pattern. The first elt is the Register node, the
87 /// second is the recorded slot number the input pattern match saved it in.
88 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
90 /// Matcher - This is the top level of the generated matcher, the result.
93 /// CurPredicate - As we emit matcher nodes, this points to the latest check
94 /// which should have future checks stuck into its Next position.
95 Matcher *CurPredicate;
97 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
100 delete PatWithNoTypes;
103 bool EmitMatcherCode(unsigned Variant);
104 void EmitResultCode();
106 Matcher *GetMatcher() const { return TheMatcher; }
108 void AddMatcher(Matcher *NewNode);
109 void InferPossibleTypes();
111 // Matcher Generation.
112 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
113 void EmitLeafMatchCode(const TreePatternNode *N);
114 void EmitOperatorMatchCode(const TreePatternNode *N,
115 TreePatternNode *NodeNoTypes);
117 // Result Code Generation.
118 unsigned getNamedArgumentSlot(StringRef Name) {
119 unsigned VarMapEntry = VariableMap[Name];
120 assert(VarMapEntry != 0 &&
121 "Variable referenced but not defined and not caught earlier!");
122 return VarMapEntry-1;
125 /// GetInstPatternNode - Get the pattern for an instruction.
126 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
127 const TreePatternNode *N);
129 void EmitResultOperand(const TreePatternNode *N,
130 SmallVectorImpl<unsigned> &ResultOps);
131 void EmitResultOfNamedOperand(const TreePatternNode *N,
132 SmallVectorImpl<unsigned> &ResultOps);
133 void EmitResultLeafAsOperand(const TreePatternNode *N,
134 SmallVectorImpl<unsigned> &ResultOps);
135 void EmitResultInstructionAsOperand(const TreePatternNode *N,
136 SmallVectorImpl<unsigned> &ResultOps);
137 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
138 SmallVectorImpl<unsigned> &ResultOps);
141 } // end anon namespace.
143 MatcherGen::MatcherGen(const PatternToMatch &pattern,
144 const CodeGenDAGPatterns &cgp)
145 : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
146 TheMatcher(0), CurPredicate(0) {
147 // We need to produce the matcher tree for the patterns source pattern. To do
148 // this we need to match the structure as well as the types. To do the type
149 // matching, we want to figure out the fewest number of type checks we need to
150 // emit. For example, if there is only one integer type supported by a
151 // target, there should be no type comparisons at all for integer patterns!
153 // To figure out the fewest number of type checks needed, clone the pattern,
154 // remove the types, then perform type inference on the pattern as a whole.
155 // If there are unresolved types, emit an explicit check for those types,
156 // apply the type to the tree, then rerun type inference. Iterate until all
157 // types are resolved.
159 PatWithNoTypes = Pattern.getSrcPattern()->clone();
160 PatWithNoTypes->RemoveAllTypes();
162 // If there are types that are manifestly known, infer them.
163 InferPossibleTypes();
166 /// InferPossibleTypes - As we emit the pattern, we end up generating type
167 /// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
168 /// want to propagate implied types as far throughout the tree as possible so
169 /// that we avoid doing redundant type checks. This does the type propagation.
170 void MatcherGen::InferPossibleTypes() {
171 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
172 // diagnostics, which we know are impossible at this point.
173 TreePattern &TP = *CGP.pf_begin()->second;
176 bool MadeChange = true;
178 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
179 true/*Ignore reg constraints*/);
181 errs() << "Type constraint application shouldn't fail!";
187 /// AddMatcher - Add a matcher node to the current graph we're building.
188 void MatcherGen::AddMatcher(Matcher *NewNode) {
189 if (CurPredicate != 0)
190 CurPredicate->setNext(NewNode);
192 TheMatcher = NewNode;
193 CurPredicate = NewNode;
197 //===----------------------------------------------------------------------===//
198 // Pattern Match Generation
199 //===----------------------------------------------------------------------===//
201 /// EmitLeafMatchCode - Generate matching code for leaf nodes.
202 void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
203 assert(N->isLeaf() && "Not a leaf?");
205 // Direct match against an integer constant.
206 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
207 // If this is the root of the dag we're matching, we emit a redundant opcode
208 // check to ensure that this gets folded into the normal top-level
210 if (N == Pattern.getSrcPattern()) {
211 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
212 AddMatcher(new CheckOpcodeMatcher(NI));
215 return AddMatcher(new CheckIntegerMatcher(II->getValue()));
218 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
220 errs() << "Unknown leaf kind: " << *DI << "\n";
224 Record *LeafRec = DI->getDef();
225 if (// Handle register references. Nothing to do here, they always match.
226 LeafRec->isSubClassOf("RegisterClass") ||
227 LeafRec->isSubClassOf("RegisterOperand") ||
228 LeafRec->isSubClassOf("PointerLikeRegClass") ||
229 LeafRec->isSubClassOf("SubRegIndex") ||
230 // Place holder for SRCVALUE nodes. Nothing to do here.
231 LeafRec->getName() == "srcvalue")
234 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
235 // record the register
236 if (LeafRec->isSubClassOf("Register")) {
237 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(),
238 NextRecordedOperandNo));
239 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
243 if (LeafRec->isSubClassOf("ValueType"))
244 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
246 if (LeafRec->isSubClassOf("CondCode"))
247 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
249 if (LeafRec->isSubClassOf("ComplexPattern")) {
250 // We can't model ComplexPattern uses that don't have their name taken yet.
251 // The OPC_CheckComplexPattern operation implicitly records the results.
252 if (N->getName().empty()) {
253 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
257 // Remember this ComplexPattern so that we can emit it after all the other
258 // structural matches are done.
259 MatchedComplexPatterns.push_back(std::make_pair(N, 0));
263 errs() << "Unknown leaf kind: " << *N << "\n";
267 void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
268 TreePatternNode *NodeNoTypes) {
269 assert(!N->isLeaf() && "Not an operator?");
270 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
272 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
273 // a constant without a predicate fn that has more that one bit set, handle
274 // this as a special case. This is usually for targets that have special
275 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
276 // handling stuff). Using these instructions is often far more efficient
277 // than materializing the constant. Unfortunately, both the instcombiner
278 // and the dag combiner can often infer that bits are dead, and thus drop
279 // them from the mask in the dag. For example, it might turn 'AND X, 255'
280 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
282 if ((N->getOperator()->getName() == "and" ||
283 N->getOperator()->getName() == "or") &&
284 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
285 N->getPredicateFns().empty()) {
286 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
287 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
288 // If this is at the root of the pattern, we emit a redundant
289 // CheckOpcode so that the following checks get factored properly under
290 // a single opcode check.
291 if (N == Pattern.getSrcPattern())
292 AddMatcher(new CheckOpcodeMatcher(CInfo));
294 // Emit the CheckAndImm/CheckOrImm node.
295 if (N->getOperator()->getName() == "and")
296 AddMatcher(new CheckAndImmMatcher(II->getValue()));
298 AddMatcher(new CheckOrImmMatcher(II->getValue()));
300 // Match the LHS of the AND as appropriate.
301 AddMatcher(new MoveChildMatcher(0));
302 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
303 AddMatcher(new MoveParentMatcher());
309 // Check that the current opcode lines up.
310 AddMatcher(new CheckOpcodeMatcher(CInfo));
312 // If this node has memory references (i.e. is a load or store), tell the
313 // interpreter to capture them in the memref array.
314 if (N->NodeHasProperty(SDNPMemOperand, CGP))
315 AddMatcher(new RecordMemRefMatcher());
317 // If this node has a chain, then the chain is operand #0 is the SDNode, and
318 // the child numbers of the node are all offset by one.
320 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
321 // Record the node and remember it in our chained nodes list.
322 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
324 NextRecordedOperandNo));
325 // Remember all of the input chains our pattern will match.
326 MatchedChainNodes.push_back(NextRecordedOperandNo++);
328 // Don't look at the input chain when matching the tree pattern to the
332 // If this node is not the root and the subtree underneath it produces a
333 // chain, then the result of matching the node is also produce a chain.
334 // Beyond that, this means that we're also folding (at least) the root node
335 // into the node that produce the chain (for example, matching
336 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
337 // problematic, if the 'reg' node also uses the load (say, its chain).
342 // | \ DAG's like cheese.
348 // It would be invalid to fold XX and LD. In this case, folding the two
349 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
350 // To prevent this, we emit a dynamic check for legality before allowing
351 // this to be folded.
353 const TreePatternNode *Root = Pattern.getSrcPattern();
354 if (N != Root) { // Not the root of the pattern.
355 // If there is a node between the root and this node, then we definitely
356 // need to emit the check.
357 bool NeedCheck = !Root->hasChild(N);
359 // If it *is* an immediate child of the root, we can still need a check if
360 // the root SDNode has multiple inputs. For us, this means that it is an
361 // intrinsic, has multiple operands, or has other inputs like chain or
364 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
366 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
367 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
368 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
369 PInfo.getNumOperands() > 1 ||
370 PInfo.hasProperty(SDNPHasChain) ||
371 PInfo.hasProperty(SDNPInGlue) ||
372 PInfo.hasProperty(SDNPOptInGlue);
376 AddMatcher(new CheckFoldableChainNodeMatcher());
380 // If this node has an output glue and isn't the root, remember it.
381 if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
382 N != Pattern.getSrcPattern()) {
383 // TODO: This redundantly records nodes with both glues and chains.
385 // Record the node and remember it in our chained nodes list.
386 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
387 "' glue output node",
388 NextRecordedOperandNo));
389 // Remember all of the nodes with output glue our pattern will match.
390 MatchedGlueResultNodes.push_back(NextRecordedOperandNo++);
393 // If this node is known to have an input glue or if it *might* have an input
394 // glue, capture it as the glue input of the pattern.
395 if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
396 N->NodeHasProperty(SDNPInGlue, CGP))
397 AddMatcher(new CaptureGlueInputMatcher());
399 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
400 // Get the code suitable for matching this child. Move to the child, check
401 // it then move back to the parent.
402 AddMatcher(new MoveChildMatcher(OpNo));
403 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
404 AddMatcher(new MoveParentMatcher());
409 void MatcherGen::EmitMatchCode(const TreePatternNode *N,
410 TreePatternNode *NodeNoTypes) {
411 // If N and NodeNoTypes don't agree on a type, then this is a case where we
412 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
413 // reinfer any correlated types.
414 SmallVector<unsigned, 2> ResultsToTypeCheck;
416 for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
417 if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
418 NodeNoTypes->setType(i, N->getExtType(i));
419 InferPossibleTypes();
420 ResultsToTypeCheck.push_back(i);
423 // If this node has a name associated with it, capture it in VariableMap. If
424 // we already saw this in the pattern, emit code to verify dagness.
425 if (!N->getName().empty()) {
426 unsigned &VarMapEntry = VariableMap[N->getName()];
427 if (VarMapEntry == 0) {
428 // If it is a named node, we must emit a 'Record' opcode.
429 AddMatcher(new RecordMatcher("$" + N->getName(), NextRecordedOperandNo));
430 VarMapEntry = ++NextRecordedOperandNo;
432 // If we get here, this is a second reference to a specific name. Since
433 // we already have checked that the first reference is valid, we don't
434 // have to recursively match it, just check that it's the same as the
435 // previously named thing.
436 AddMatcher(new CheckSameMatcher(VarMapEntry-1));
442 EmitLeafMatchCode(N);
444 EmitOperatorMatchCode(N, NodeNoTypes);
446 // If there are node predicates for this node, generate their checks.
447 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
448 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
450 for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
451 AddMatcher(new CheckTypeMatcher(N->getType(ResultsToTypeCheck[i]),
452 ResultsToTypeCheck[i]));
455 /// EmitMatcherCode - Generate the code that matches the predicate of this
456 /// pattern for the specified Variant. If the variant is invalid this returns
457 /// true and does not generate code, if it is valid, it returns false.
458 bool MatcherGen::EmitMatcherCode(unsigned Variant) {
459 // If the root of the pattern is a ComplexPattern and if it is specified to
460 // match some number of root opcodes, these are considered to be our variants.
461 // Depending on which variant we're generating code for, emit the root opcode
463 if (const ComplexPattern *CP =
464 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
465 const std::vector<Record*> &OpNodes = CP->getRootNodes();
466 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
467 if (Variant >= OpNodes.size()) return true;
469 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
471 if (Variant != 0) return true;
474 // Emit the matcher for the pattern structure and types.
475 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
477 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
478 // feature is around, do the check).
479 if (!Pattern.getPredicateCheck().empty())
480 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
482 // Now that we've completed the structural type match, emit any ComplexPattern
483 // checks (e.g. addrmode matches). We emit this after the structural match
484 // because they are generally more expensive to evaluate and more difficult to
486 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
487 const TreePatternNode *N = MatchedComplexPatterns[i].first;
489 // Remember where the results of this match get stuck.
490 MatchedComplexPatterns[i].second = NextRecordedOperandNo;
492 // Get the slot we recorded the value in from the name on the node.
493 unsigned RecNodeEntry = VariableMap[N->getName()];
494 assert(!N->getName().empty() && RecNodeEntry &&
495 "Complex pattern should have a name and slot");
496 --RecNodeEntry; // Entries in VariableMap are biased.
498 const ComplexPattern &CP =
499 CGP.getComplexPattern(((DefInit*)N->getLeafValue())->getDef());
501 // Emit a CheckComplexPat operation, which does the match (aborting if it
502 // fails) and pushes the matched operands onto the recorded nodes list.
503 AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
504 N->getName(), NextRecordedOperandNo));
506 // Record the right number of operands.
507 NextRecordedOperandNo += CP.getNumOperands();
508 if (CP.hasProperty(SDNPHasChain)) {
509 // If the complex pattern has a chain, then we need to keep track of the
510 // fact that we just recorded a chain input. The chain input will be
511 // matched as the last operand of the predicate if it was successful.
512 ++NextRecordedOperandNo; // Chained node operand.
514 // It is the last operand recorded.
515 assert(NextRecordedOperandNo > 1 &&
516 "Should have recorded input/result chains at least!");
517 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
520 // TODO: Complex patterns can't have output glues, if they did, we'd want
528 //===----------------------------------------------------------------------===//
529 // Node Result Generation
530 //===----------------------------------------------------------------------===//
532 void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
533 SmallVectorImpl<unsigned> &ResultOps){
534 assert(!N->getName().empty() && "Operand not named!");
536 // A reference to a complex pattern gets all of the results of the complex
538 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
540 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i)
541 if (MatchedComplexPatterns[i].first->getName() == N->getName()) {
542 SlotNo = MatchedComplexPatterns[i].second;
545 assert(SlotNo != 0 && "Didn't get a slot number assigned?");
547 // The first slot entry is the node itself, the subsequent entries are the
549 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
550 ResultOps.push_back(SlotNo+i);
554 unsigned SlotNo = getNamedArgumentSlot(N->getName());
556 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
557 // version of the immediate so that it doesn't get selected due to some other
560 StringRef OperatorName = N->getOperator()->getName();
561 if (OperatorName == "imm" || OperatorName == "fpimm") {
562 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
563 ResultOps.push_back(NextRecordedOperandNo++);
568 ResultOps.push_back(SlotNo);
571 void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
572 SmallVectorImpl<unsigned> &ResultOps) {
573 assert(N->isLeaf() && "Must be a leaf");
575 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
576 AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getType(0)));
577 ResultOps.push_back(NextRecordedOperandNo++);
581 // If this is an explicit register reference, handle it.
582 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
583 Record *Def = DI->getDef();
584 if (Def->isSubClassOf("Register")) {
585 const CodeGenRegister *Reg =
586 CGP.getTargetInfo().getRegBank().getReg(Def);
587 AddMatcher(new EmitRegisterMatcher(Reg, N->getType(0)));
588 ResultOps.push_back(NextRecordedOperandNo++);
592 if (Def->getName() == "zero_reg") {
593 AddMatcher(new EmitRegisterMatcher(0, N->getType(0)));
594 ResultOps.push_back(NextRecordedOperandNo++);
598 // Handle a reference to a register class. This is used
599 // in COPY_TO_SUBREG instructions.
600 if (Def->isSubClassOf("RegisterOperand"))
601 Def = Def->getValueAsDef("RegClass");
602 if (Def->isSubClassOf("RegisterClass")) {
603 std::string Value = getQualifiedName(Def) + "RegClassID";
604 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
605 ResultOps.push_back(NextRecordedOperandNo++);
609 // Handle a subregister index. This is used for INSERT_SUBREG etc.
610 if (Def->isSubClassOf("SubRegIndex")) {
611 std::string Value = getQualifiedName(Def);
612 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
613 ResultOps.push_back(NextRecordedOperandNo++);
618 errs() << "unhandled leaf node: \n";
622 /// GetInstPatternNode - Get the pattern for an instruction.
624 const TreePatternNode *MatcherGen::
625 GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
626 const TreePattern *InstPat = Inst.getPattern();
628 // FIXME2?: Assume actual pattern comes before "implicit".
629 TreePatternNode *InstPatNode;
631 InstPatNode = InstPat->getTree(0);
632 else if (/*isRoot*/ N == Pattern.getDstPattern())
633 InstPatNode = Pattern.getSrcPattern();
637 if (InstPatNode && !InstPatNode->isLeaf() &&
638 InstPatNode->getOperator()->getName() == "set")
639 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
645 mayInstNodeLoadOrStore(const TreePatternNode *N,
646 const CodeGenDAGPatterns &CGP) {
647 Record *Op = N->getOperator();
648 const CodeGenTarget &CGT = CGP.getTargetInfo();
649 CodeGenInstruction &II = CGT.getInstruction(Op);
650 return II.mayLoad || II.mayStore;
654 numNodesThatMayLoadOrStore(const TreePatternNode *N,
655 const CodeGenDAGPatterns &CGP) {
659 Record *OpRec = N->getOperator();
660 if (!OpRec->isSubClassOf("Instruction"))
664 if (mayInstNodeLoadOrStore(N, CGP))
667 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
668 Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
674 EmitResultInstructionAsOperand(const TreePatternNode *N,
675 SmallVectorImpl<unsigned> &OutputOps) {
676 Record *Op = N->getOperator();
677 const CodeGenTarget &CGT = CGP.getTargetInfo();
678 CodeGenInstruction &II = CGT.getInstruction(Op);
679 const DAGInstruction &Inst = CGP.getInstruction(Op);
681 // If we can, get the pattern for the instruction we're generating. We derive
682 // a variety of information from this pattern, such as whether it has a chain.
684 // FIXME2: This is extremely dubious for several reasons, not the least of
685 // which it gives special status to instructions with patterns that Pat<>
686 // nodes can't duplicate.
687 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
689 // NodeHasChain - Whether the instruction node we're creating takes chains.
690 bool NodeHasChain = InstPatNode &&
691 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
693 bool isRoot = N == Pattern.getDstPattern();
695 // TreeHasOutGlue - True if this tree has glue.
696 bool TreeHasInGlue = false, TreeHasOutGlue = false;
698 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
699 TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
700 SrcPat->TreeHasProperty(SDNPInGlue, CGP);
702 // FIXME2: this is checking the entire pattern, not just the node in
703 // question, doing this just for the root seems like a total hack.
704 TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
707 // NumResults - This is the number of results produced by the instruction in
709 unsigned NumResults = Inst.getNumResults();
711 // Loop over all of the operands of the instruction pattern, emitting code
712 // to fill them all in. The node 'N' usually has number children equal to
713 // the number of input operands of the instruction. However, in cases
714 // where there are predicate operands for an instruction, we need to fill
715 // in the 'execute always' values. Match up the node operands to the
716 // instruction operands to do this.
717 SmallVector<unsigned, 8> InstOps;
718 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.Operands.size();
719 InstOpNo != e; ++InstOpNo) {
721 // Determine what to emit for this operand.
722 Record *OperandNode = II.Operands[InstOpNo].Rec;
723 if ((OperandNode->isSubClassOf("PredicateOperand") ||
724 OperandNode->isSubClassOf("OptionalDefOperand")) &&
725 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
726 // This is a predicate or optional def operand; emit the
727 // 'default ops' operands.
728 const DAGDefaultOperand &DefaultOp
729 = CGP.getDefaultOperand(OperandNode);
730 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
731 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
735 const TreePatternNode *Child = N->getChild(ChildNo);
737 // Otherwise this is a normal operand or a predicate operand without
738 // 'execute always'; emit it.
739 unsigned BeforeAddingNumOps = InstOps.size();
740 EmitResultOperand(Child, InstOps);
741 assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
743 // If the operand is an instruction and it produced multiple results, just
744 // take the first one.
745 if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
746 InstOps.resize(BeforeAddingNumOps+1);
751 // If this node has input glue or explicitly specified input physregs, we
752 // need to add chained and glued copyfromreg nodes and materialize the glue
754 if (isRoot && !PhysRegInputs.empty()) {
755 // Emit all of the CopyToReg nodes for the input physical registers. These
756 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
757 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
758 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
759 PhysRegInputs[i].first));
760 // Even if the node has no other glue inputs, the resultant node must be
761 // glued to the CopyFromReg nodes we just generated.
762 TreeHasInGlue = true;
765 // Result order: node results, chain, glue
767 // Determine the result types.
768 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
769 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
770 ResultVTs.push_back(N->getType(i));
772 // If this is the root instruction of a pattern that has physical registers in
773 // its result pattern, add output VTs for them. For example, X86 has:
774 // (set AL, (mul ...))
775 // This also handles implicit results like:
777 if (isRoot && !Pattern.getDstRegs().empty()) {
778 // If the root came from an implicit def in the instruction handling stuff,
780 Record *HandledReg = 0;
781 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
782 HandledReg = II.ImplicitDefs[0];
784 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
785 Record *Reg = Pattern.getDstRegs()[i];
786 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
787 ResultVTs.push_back(getRegisterValueType(Reg, CGT));
791 // If this is the root of the pattern and the pattern we're matching includes
792 // a node that is variadic, mark the generated node as variadic so that it
793 // gets the excess operands from the input DAG.
794 int NumFixedArityOperands = -1;
796 (Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP)))
797 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
799 // If this is the root node and multiple matched nodes in the input pattern
800 // have MemRefs in them, have the interpreter collect them and plop them onto
801 // this node. If there is just one node with MemRefs, leave them on that node
802 // even if it is not the root.
804 // FIXME3: This is actively incorrect for result patterns with multiple
805 // memory-referencing instructions.
806 bool PatternHasMemOperands =
807 Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
809 bool NodeHasMemRefs = false;
810 if (PatternHasMemOperands) {
811 unsigned NumNodesThatLoadOrStore =
812 numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
813 bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
814 NumNodesThatLoadOrStore == 1;
816 NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
817 NumNodesThatLoadOrStore != 1));
820 assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
821 "Node has no result");
823 AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
824 ResultVTs.data(), ResultVTs.size(),
825 InstOps.data(), InstOps.size(),
826 NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
827 NodeHasMemRefs, NumFixedArityOperands,
828 NextRecordedOperandNo));
830 // The non-chain and non-glue results of the newly emitted node get recorded.
831 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
832 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
833 OutputOps.push_back(NextRecordedOperandNo++);
838 EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
839 SmallVectorImpl<unsigned> &ResultOps) {
840 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
843 SmallVector<unsigned, 8> InputOps;
845 // FIXME2: Could easily generalize this to support multiple inputs and outputs
846 // to the SDNodeXForm. For now we just support one input and one output like
847 // the old instruction selector.
848 assert(N->getNumChildren() == 1);
849 EmitResultOperand(N->getChild(0), InputOps);
851 // The input currently must have produced exactly one result.
852 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
854 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
855 ResultOps.push_back(NextRecordedOperandNo++);
858 void MatcherGen::EmitResultOperand(const TreePatternNode *N,
859 SmallVectorImpl<unsigned> &ResultOps) {
860 // This is something selected from the pattern we matched.
861 if (!N->getName().empty())
862 return EmitResultOfNamedOperand(N, ResultOps);
865 return EmitResultLeafAsOperand(N, ResultOps);
867 Record *OpRec = N->getOperator();
868 if (OpRec->isSubClassOf("Instruction"))
869 return EmitResultInstructionAsOperand(N, ResultOps);
870 if (OpRec->isSubClassOf("SDNodeXForm"))
871 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
872 errs() << "Unknown result node to emit code for: " << *N << '\n';
873 throw std::string("Unknown node in result pattern!");
876 void MatcherGen::EmitResultCode() {
877 // Patterns that match nodes with (potentially multiple) chain inputs have to
878 // merge them together into a token factor. This informs the generated code
879 // what all the chained nodes are.
880 if (!MatchedChainNodes.empty())
881 AddMatcher(new EmitMergeInputChainsMatcher
882 (MatchedChainNodes.data(), MatchedChainNodes.size()));
884 // Codegen the root of the result pattern, capturing the resulting values.
885 SmallVector<unsigned, 8> Ops;
886 EmitResultOperand(Pattern.getDstPattern(), Ops);
888 // At this point, we have however many values the result pattern produces.
889 // However, the input pattern might not need all of these. If there are
890 // excess values at the end (such as implicit defs of condition codes etc)
891 // just lop them off. This doesn't need to worry about glue or chains, just
894 unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
896 // If the pattern also has (implicit) results, count them as well.
897 if (!Pattern.getDstRegs().empty()) {
898 // If the root came from an implicit def in the instruction handling stuff,
900 Record *HandledReg = 0;
901 const TreePatternNode *DstPat = Pattern.getDstPattern();
902 if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
903 const CodeGenTarget &CGT = CGP.getTargetInfo();
904 CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
906 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
907 HandledReg = II.ImplicitDefs[0];
910 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
911 Record *Reg = Pattern.getDstRegs()[i];
912 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
917 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
918 Ops.resize(NumSrcResults);
920 // If the matched pattern covers nodes which define a glue result, emit a node
921 // that tells the matcher about them so that it can update their results.
922 if (!MatchedGlueResultNodes.empty())
923 AddMatcher(new MarkGlueResultsMatcher(MatchedGlueResultNodes.data(),
924 MatchedGlueResultNodes.size()));
926 AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
930 /// ConvertPatternToMatcher - Create the matcher for the specified pattern with
931 /// the specified variant. If the variant number is invalid, this returns null.
932 Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
934 const CodeGenDAGPatterns &CGP) {
935 MatcherGen Gen(Pattern, CGP);
937 // Generate the code for the matcher.
938 if (Gen.EmitMatcherCode(Variant))
941 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
942 // FIXME2: Split result code out to another table, and make the matcher end
943 // with an "Emit <index>" command. This allows result generation stuff to be
944 // shared and factored?
946 // If the match succeeds, then we generate Pattern.
947 Gen.EmitResultCode();
949 // Unconditional match.
950 return Gen.GetMatcher();