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 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
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 (const IntInit *II = dynamic_cast<const 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 const DefInit *DI = dynamic_cast<const 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 (const IntInit *II =
287 dynamic_cast<const IntInit*>(N->getChild(1)->getLeafValue())) {
288 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
289 // If this is at the root of the pattern, we emit a redundant
290 // CheckOpcode so that the following checks get factored properly under
291 // a single opcode check.
292 if (N == Pattern.getSrcPattern())
293 AddMatcher(new CheckOpcodeMatcher(CInfo));
295 // Emit the CheckAndImm/CheckOrImm node.
296 if (N->getOperator()->getName() == "and")
297 AddMatcher(new CheckAndImmMatcher(II->getValue()));
299 AddMatcher(new CheckOrImmMatcher(II->getValue()));
301 // Match the LHS of the AND as appropriate.
302 AddMatcher(new MoveChildMatcher(0));
303 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
304 AddMatcher(new MoveParentMatcher());
310 // Check that the current opcode lines up.
311 AddMatcher(new CheckOpcodeMatcher(CInfo));
313 // If this node has memory references (i.e. is a load or store), tell the
314 // interpreter to capture them in the memref array.
315 if (N->NodeHasProperty(SDNPMemOperand, CGP))
316 AddMatcher(new RecordMemRefMatcher());
318 // If this node has a chain, then the chain is operand #0 is the SDNode, and
319 // the child numbers of the node are all offset by one.
321 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
322 // Record the node and remember it in our chained nodes list.
323 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
325 NextRecordedOperandNo));
326 // Remember all of the input chains our pattern will match.
327 MatchedChainNodes.push_back(NextRecordedOperandNo++);
329 // Don't look at the input chain when matching the tree pattern to the
333 // If this node is not the root and the subtree underneath it produces a
334 // chain, then the result of matching the node is also produce a chain.
335 // Beyond that, this means that we're also folding (at least) the root node
336 // into the node that produce the chain (for example, matching
337 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
338 // problematic, if the 'reg' node also uses the load (say, its chain).
343 // | \ DAG's like cheese.
349 // It would be invalid to fold XX and LD. In this case, folding the two
350 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
351 // To prevent this, we emit a dynamic check for legality before allowing
352 // this to be folded.
354 const TreePatternNode *Root = Pattern.getSrcPattern();
355 if (N != Root) { // Not the root of the pattern.
356 // If there is a node between the root and this node, then we definitely
357 // need to emit the check.
358 bool NeedCheck = !Root->hasChild(N);
360 // If it *is* an immediate child of the root, we can still need a check if
361 // the root SDNode has multiple inputs. For us, this means that it is an
362 // intrinsic, has multiple operands, or has other inputs like chain or
365 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
367 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
368 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
369 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
370 PInfo.getNumOperands() > 1 ||
371 PInfo.hasProperty(SDNPHasChain) ||
372 PInfo.hasProperty(SDNPInGlue) ||
373 PInfo.hasProperty(SDNPOptInGlue);
377 AddMatcher(new CheckFoldableChainNodeMatcher());
381 // If this node has an output glue and isn't the root, remember it.
382 if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
383 N != Pattern.getSrcPattern()) {
384 // TODO: This redundantly records nodes with both glues and chains.
386 // Record the node and remember it in our chained nodes list.
387 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
388 "' glue output node",
389 NextRecordedOperandNo));
390 // Remember all of the nodes with output glue our pattern will match.
391 MatchedGlueResultNodes.push_back(NextRecordedOperandNo++);
394 // If this node is known to have an input glue or if it *might* have an input
395 // glue, capture it as the glue input of the pattern.
396 if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
397 N->NodeHasProperty(SDNPInGlue, CGP))
398 AddMatcher(new CaptureGlueInputMatcher());
400 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
401 // Get the code suitable for matching this child. Move to the child, check
402 // it then move back to the parent.
403 AddMatcher(new MoveChildMatcher(OpNo));
404 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
405 AddMatcher(new MoveParentMatcher());
410 void MatcherGen::EmitMatchCode(const TreePatternNode *N,
411 TreePatternNode *NodeNoTypes) {
412 // If N and NodeNoTypes don't agree on a type, then this is a case where we
413 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
414 // reinfer any correlated types.
415 SmallVector<unsigned, 2> ResultsToTypeCheck;
417 for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
418 if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
419 NodeNoTypes->setType(i, N->getExtType(i));
420 InferPossibleTypes();
421 ResultsToTypeCheck.push_back(i);
424 // If this node has a name associated with it, capture it in VariableMap. If
425 // we already saw this in the pattern, emit code to verify dagness.
426 if (!N->getName().empty()) {
427 unsigned &VarMapEntry = VariableMap[N->getName()];
428 if (VarMapEntry == 0) {
429 // If it is a named node, we must emit a 'Record' opcode.
430 AddMatcher(new RecordMatcher("$" + N->getName(), NextRecordedOperandNo));
431 VarMapEntry = ++NextRecordedOperandNo;
433 // If we get here, this is a second reference to a specific name. Since
434 // we already have checked that the first reference is valid, we don't
435 // have to recursively match it, just check that it's the same as the
436 // previously named thing.
437 AddMatcher(new CheckSameMatcher(VarMapEntry-1));
443 EmitLeafMatchCode(N);
445 EmitOperatorMatchCode(N, NodeNoTypes);
447 // If there are node predicates for this node, generate their checks.
448 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
449 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
451 for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
452 AddMatcher(new CheckTypeMatcher(N->getType(ResultsToTypeCheck[i]),
453 ResultsToTypeCheck[i]));
456 /// EmitMatcherCode - Generate the code that matches the predicate of this
457 /// pattern for the specified Variant. If the variant is invalid this returns
458 /// true and does not generate code, if it is valid, it returns false.
459 bool MatcherGen::EmitMatcherCode(unsigned Variant) {
460 // If the root of the pattern is a ComplexPattern and if it is specified to
461 // match some number of root opcodes, these are considered to be our variants.
462 // Depending on which variant we're generating code for, emit the root opcode
464 if (const ComplexPattern *CP =
465 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
466 const std::vector<Record*> &OpNodes = CP->getRootNodes();
467 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
468 if (Variant >= OpNodes.size()) return true;
470 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
472 if (Variant != 0) return true;
475 // Emit the matcher for the pattern structure and types.
476 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
478 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
479 // feature is around, do the check).
480 if (!Pattern.getPredicateCheck().empty())
481 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
483 // Now that we've completed the structural type match, emit any ComplexPattern
484 // checks (e.g. addrmode matches). We emit this after the structural match
485 // because they are generally more expensive to evaluate and more difficult to
487 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
488 const TreePatternNode *N = MatchedComplexPatterns[i].first;
490 // Remember where the results of this match get stuck.
491 MatchedComplexPatterns[i].second = NextRecordedOperandNo;
493 // Get the slot we recorded the value in from the name on the node.
494 unsigned RecNodeEntry = VariableMap[N->getName()];
495 assert(!N->getName().empty() && RecNodeEntry &&
496 "Complex pattern should have a name and slot");
497 --RecNodeEntry; // Entries in VariableMap are biased.
499 const ComplexPattern &CP =
500 CGP.getComplexPattern(((const DefInit*)N->getLeafValue())->getDef());
502 // Emit a CheckComplexPat operation, which does the match (aborting if it
503 // fails) and pushes the matched operands onto the recorded nodes list.
504 AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
505 N->getName(), NextRecordedOperandNo));
507 // Record the right number of operands.
508 NextRecordedOperandNo += CP.getNumOperands();
509 if (CP.hasProperty(SDNPHasChain)) {
510 // If the complex pattern has a chain, then we need to keep track of the
511 // fact that we just recorded a chain input. The chain input will be
512 // matched as the last operand of the predicate if it was successful.
513 ++NextRecordedOperandNo; // Chained node operand.
515 // It is the last operand recorded.
516 assert(NextRecordedOperandNo > 1 &&
517 "Should have recorded input/result chains at least!");
518 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
521 // TODO: Complex patterns can't have output glues, if they did, we'd want
529 //===----------------------------------------------------------------------===//
530 // Node Result Generation
531 //===----------------------------------------------------------------------===//
533 void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
534 SmallVectorImpl<unsigned> &ResultOps){
535 assert(!N->getName().empty() && "Operand not named!");
537 // A reference to a complex pattern gets all of the results of the complex
539 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
541 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i)
542 if (MatchedComplexPatterns[i].first->getName() == N->getName()) {
543 SlotNo = MatchedComplexPatterns[i].second;
546 assert(SlotNo != 0 && "Didn't get a slot number assigned?");
548 // The first slot entry is the node itself, the subsequent entries are the
550 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
551 ResultOps.push_back(SlotNo+i);
555 unsigned SlotNo = getNamedArgumentSlot(N->getName());
557 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
558 // version of the immediate so that it doesn't get selected due to some other
561 StringRef OperatorName = N->getOperator()->getName();
562 if (OperatorName == "imm" || OperatorName == "fpimm") {
563 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
564 ResultOps.push_back(NextRecordedOperandNo++);
569 ResultOps.push_back(SlotNo);
572 void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
573 SmallVectorImpl<unsigned> &ResultOps) {
574 assert(N->isLeaf() && "Must be a leaf");
576 if (const IntInit *II = dynamic_cast<const IntInit*>(N->getLeafValue())) {
577 AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getType(0)));
578 ResultOps.push_back(NextRecordedOperandNo++);
582 // If this is an explicit register reference, handle it.
583 if (const DefInit *DI = dynamic_cast<const DefInit*>(N->getLeafValue())) {
584 Record *Def = DI->getDef();
585 if (Def->isSubClassOf("Register")) {
586 const CodeGenRegister *Reg =
587 CGP.getTargetInfo().getRegBank().getReg(Def);
588 AddMatcher(new EmitRegisterMatcher(Reg, N->getType(0)));
589 ResultOps.push_back(NextRecordedOperandNo++);
593 if (Def->getName() == "zero_reg") {
594 AddMatcher(new EmitRegisterMatcher(0, N->getType(0)));
595 ResultOps.push_back(NextRecordedOperandNo++);
599 // Handle a reference to a register class. This is used
600 // in COPY_TO_SUBREG instructions.
601 if (Def->isSubClassOf("RegisterOperand"))
602 Def = Def->getValueAsDef("RegClass");
603 if (Def->isSubClassOf("RegisterClass")) {
604 std::string Value = getQualifiedName(Def) + "RegClassID";
605 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
606 ResultOps.push_back(NextRecordedOperandNo++);
610 // Handle a subregister index. This is used for INSERT_SUBREG etc.
611 if (Def->isSubClassOf("SubRegIndex")) {
612 std::string Value = getQualifiedName(Def);
613 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
614 ResultOps.push_back(NextRecordedOperandNo++);
619 errs() << "unhandled leaf node: \n";
623 /// GetInstPatternNode - Get the pattern for an instruction.
625 const TreePatternNode *MatcherGen::
626 GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
627 const TreePattern *InstPat = Inst.getPattern();
629 // FIXME2?: Assume actual pattern comes before "implicit".
630 TreePatternNode *InstPatNode;
632 InstPatNode = InstPat->getTree(0);
633 else if (/*isRoot*/ N == Pattern.getDstPattern())
634 InstPatNode = Pattern.getSrcPattern();
638 if (InstPatNode && !InstPatNode->isLeaf() &&
639 InstPatNode->getOperator()->getName() == "set")
640 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
646 mayInstNodeLoadOrStore(const TreePatternNode *N,
647 const CodeGenDAGPatterns &CGP) {
648 Record *Op = N->getOperator();
649 const CodeGenTarget &CGT = CGP.getTargetInfo();
650 CodeGenInstruction &II = CGT.getInstruction(Op);
651 return II.mayLoad || II.mayStore;
655 numNodesThatMayLoadOrStore(const TreePatternNode *N,
656 const CodeGenDAGPatterns &CGP) {
660 Record *OpRec = N->getOperator();
661 if (!OpRec->isSubClassOf("Instruction"))
665 if (mayInstNodeLoadOrStore(N, CGP))
668 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
669 Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
675 EmitResultInstructionAsOperand(const TreePatternNode *N,
676 SmallVectorImpl<unsigned> &OutputOps) {
677 Record *Op = N->getOperator();
678 const CodeGenTarget &CGT = CGP.getTargetInfo();
679 CodeGenInstruction &II = CGT.getInstruction(Op);
680 const DAGInstruction &Inst = CGP.getInstruction(Op);
682 // If we can, get the pattern for the instruction we're generating. We derive
683 // a variety of information from this pattern, such as whether it has a chain.
685 // FIXME2: This is extremely dubious for several reasons, not the least of
686 // which it gives special status to instructions with patterns that Pat<>
687 // nodes can't duplicate.
688 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
690 // NodeHasChain - Whether the instruction node we're creating takes chains.
691 bool NodeHasChain = InstPatNode &&
692 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
694 bool isRoot = N == Pattern.getDstPattern();
696 // TreeHasOutGlue - True if this tree has glue.
697 bool TreeHasInGlue = false, TreeHasOutGlue = false;
699 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
700 TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
701 SrcPat->TreeHasProperty(SDNPInGlue, CGP);
703 // FIXME2: this is checking the entire pattern, not just the node in
704 // question, doing this just for the root seems like a total hack.
705 TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
708 // NumResults - This is the number of results produced by the instruction in
710 unsigned NumResults = Inst.getNumResults();
712 // Loop over all of the operands of the instruction pattern, emitting code
713 // to fill them all in. The node 'N' usually has number children equal to
714 // the number of input operands of the instruction. However, in cases
715 // where there are predicate operands for an instruction, we need to fill
716 // in the 'execute always' values. Match up the node operands to the
717 // instruction operands to do this.
718 SmallVector<unsigned, 8> InstOps;
719 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.Operands.size();
720 InstOpNo != e; ++InstOpNo) {
722 // Determine what to emit for this operand.
723 Record *OperandNode = II.Operands[InstOpNo].Rec;
724 if ((OperandNode->isSubClassOf("PredicateOperand") ||
725 OperandNode->isSubClassOf("OptionalDefOperand")) &&
726 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
727 // This is a predicate or optional def operand; emit the
728 // 'default ops' operands.
729 const DAGDefaultOperand &DefaultOp
730 = CGP.getDefaultOperand(OperandNode);
731 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
732 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
736 const TreePatternNode *Child = N->getChild(ChildNo);
738 // Otherwise this is a normal operand or a predicate operand without
739 // 'execute always'; emit it.
740 unsigned BeforeAddingNumOps = InstOps.size();
741 EmitResultOperand(Child, InstOps);
742 assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
744 // If the operand is an instruction and it produced multiple results, just
745 // take the first one.
746 if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
747 InstOps.resize(BeforeAddingNumOps+1);
752 // If this node has input glue or explicitly specified input physregs, we
753 // need to add chained and glued copyfromreg nodes and materialize the glue
755 if (isRoot && !PhysRegInputs.empty()) {
756 // Emit all of the CopyToReg nodes for the input physical registers. These
757 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
758 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
759 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
760 PhysRegInputs[i].first));
761 // Even if the node has no other glue inputs, the resultant node must be
762 // glued to the CopyFromReg nodes we just generated.
763 TreeHasInGlue = true;
766 // Result order: node results, chain, glue
768 // Determine the result types.
769 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
770 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
771 ResultVTs.push_back(N->getType(i));
773 // If this is the root instruction of a pattern that has physical registers in
774 // its result pattern, add output VTs for them. For example, X86 has:
775 // (set AL, (mul ...))
776 // This also handles implicit results like:
778 if (isRoot && !Pattern.getDstRegs().empty()) {
779 // If the root came from an implicit def in the instruction handling stuff,
781 Record *HandledReg = 0;
782 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
783 HandledReg = II.ImplicitDefs[0];
785 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
786 Record *Reg = Pattern.getDstRegs()[i];
787 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
788 ResultVTs.push_back(getRegisterValueType(Reg, CGT));
792 // If this is the root of the pattern and the pattern we're matching includes
793 // a node that is variadic, mark the generated node as variadic so that it
794 // gets the excess operands from the input DAG.
795 int NumFixedArityOperands = -1;
797 (Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP)))
798 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
800 // If this is the root node and multiple matched nodes in the input pattern
801 // have MemRefs in them, have the interpreter collect them and plop them onto
802 // this node. If there is just one node with MemRefs, leave them on that node
803 // even if it is not the root.
805 // FIXME3: This is actively incorrect for result patterns with multiple
806 // memory-referencing instructions.
807 bool PatternHasMemOperands =
808 Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
810 bool NodeHasMemRefs = false;
811 if (PatternHasMemOperands) {
812 unsigned NumNodesThatLoadOrStore =
813 numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
814 bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
815 NumNodesThatLoadOrStore == 1;
817 NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
818 NumNodesThatLoadOrStore != 1));
821 assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
822 "Node has no result");
824 AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
825 ResultVTs.data(), ResultVTs.size(),
826 InstOps.data(), InstOps.size(),
827 NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
828 NodeHasMemRefs, NumFixedArityOperands,
829 NextRecordedOperandNo));
831 // The non-chain and non-glue results of the newly emitted node get recorded.
832 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
833 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
834 OutputOps.push_back(NextRecordedOperandNo++);
839 EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
840 SmallVectorImpl<unsigned> &ResultOps) {
841 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
844 SmallVector<unsigned, 8> InputOps;
846 // FIXME2: Could easily generalize this to support multiple inputs and outputs
847 // to the SDNodeXForm. For now we just support one input and one output like
848 // the old instruction selector.
849 assert(N->getNumChildren() == 1);
850 EmitResultOperand(N->getChild(0), InputOps);
852 // The input currently must have produced exactly one result.
853 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
855 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
856 ResultOps.push_back(NextRecordedOperandNo++);
859 void MatcherGen::EmitResultOperand(const TreePatternNode *N,
860 SmallVectorImpl<unsigned> &ResultOps) {
861 // This is something selected from the pattern we matched.
862 if (!N->getName().empty())
863 return EmitResultOfNamedOperand(N, ResultOps);
866 return EmitResultLeafAsOperand(N, ResultOps);
868 Record *OpRec = N->getOperator();
869 if (OpRec->isSubClassOf("Instruction"))
870 return EmitResultInstructionAsOperand(N, ResultOps);
871 if (OpRec->isSubClassOf("SDNodeXForm"))
872 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
873 errs() << "Unknown result node to emit code for: " << *N << '\n';
874 throw std::string("Unknown node in result pattern!");
877 void MatcherGen::EmitResultCode() {
878 // Patterns that match nodes with (potentially multiple) chain inputs have to
879 // merge them together into a token factor. This informs the generated code
880 // what all the chained nodes are.
881 if (!MatchedChainNodes.empty())
882 AddMatcher(new EmitMergeInputChainsMatcher
883 (MatchedChainNodes.data(), MatchedChainNodes.size()));
885 // Codegen the root of the result pattern, capturing the resulting values.
886 SmallVector<unsigned, 8> Ops;
887 EmitResultOperand(Pattern.getDstPattern(), Ops);
889 // At this point, we have however many values the result pattern produces.
890 // However, the input pattern might not need all of these. If there are
891 // excess values at the end (such as implicit defs of condition codes etc)
892 // just lop them off. This doesn't need to worry about glue or chains, just
895 unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
897 // If the pattern also has (implicit) results, count them as well.
898 if (!Pattern.getDstRegs().empty()) {
899 // If the root came from an implicit def in the instruction handling stuff,
901 Record *HandledReg = 0;
902 const TreePatternNode *DstPat = Pattern.getDstPattern();
903 if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
904 const CodeGenTarget &CGT = CGP.getTargetInfo();
905 CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
907 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
908 HandledReg = II.ImplicitDefs[0];
911 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
912 Record *Reg = Pattern.getDstRegs()[i];
913 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
918 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
919 Ops.resize(NumSrcResults);
921 // If the matched pattern covers nodes which define a glue result, emit a node
922 // that tells the matcher about them so that it can update their results.
923 if (!MatchedGlueResultNodes.empty())
924 AddMatcher(new MarkGlueResultsMatcher(MatchedGlueResultNodes.data(),
925 MatchedGlueResultNodes.size()));
927 AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
931 /// ConvertPatternToMatcher - Create the matcher for the specified pattern with
932 /// the specified variant. If the variant number is invalid, this returns null.
933 Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
935 const CodeGenDAGPatterns &CGP) {
936 MatcherGen Gen(Pattern, CGP);
938 // Generate the code for the matcher.
939 if (Gen.EmitMatcherCode(Variant))
942 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
943 // FIXME2: Split result code out to another table, and make the matcher end
944 // with an "Emit <index>" command. This allows result generation stuff to be
945 // shared and factored?
947 // If the match succeeds, then we generate Pattern.
948 Gen.EmitResultCode();
950 // Unconditional match.
951 return Gen.GetMatcher();