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"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/TableGen/Error.h"
16 #include "llvm/TableGen/Record.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);
30 for (const auto &RC : T.getRegBank().getRegClasses()) {
31 if (!RC.contains(Reg))
36 ValueTypeByHwMode VVT = RC.getValueTypeNum(0);
38 VT = VVT.getSimple().SimpleTy;
42 // If this occurs in multiple register classes, they all have to agree.
44 ValueTypeByHwMode T = RC.getValueTypeNum(0);
45 assert((!T.isSimple() || T.getSimple().SimpleTy == VT) &&
46 "ValueType mismatch between register classes for this register");
55 const PatternToMatch &Pattern;
56 const CodeGenDAGPatterns &CGP;
58 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
59 /// out with all of the types removed. This allows us to insert type checks
60 /// as we scan the tree.
61 TreePatternNode *PatWithNoTypes;
63 /// VariableMap - A map from variable names ('$dst') to the recorded operand
64 /// number that they were captured as. These are biased by 1 to make
66 StringMap<unsigned> VariableMap;
68 /// This maintains the recorded operand number that OPC_CheckComplexPattern
69 /// drops each sub-operand into. We don't want to insert these into
70 /// VariableMap because that leads to identity checking if they are
71 /// encountered multiple times. Biased by 1 like VariableMap for
73 StringMap<unsigned> NamedComplexPatternOperands;
75 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
76 /// the RecordedNodes array, this keeps track of which slot will be next to
78 unsigned NextRecordedOperandNo;
80 /// MatchedChainNodes - This maintains the position in the recorded nodes
81 /// array of all of the recorded input nodes that have chains.
82 SmallVector<unsigned, 2> MatchedChainNodes;
84 /// MatchedComplexPatterns - This maintains a list of all of the
85 /// ComplexPatterns that we need to check. The second element of each pair
86 /// is the recorded operand number of the input node.
87 SmallVector<std::pair<const TreePatternNode*,
88 unsigned>, 2> MatchedComplexPatterns;
90 /// PhysRegInputs - List list has an entry for each explicitly specified
91 /// physreg input to the pattern. The first elt is the Register node, the
92 /// second is the recorded slot number the input pattern match saved it in.
93 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
95 /// Matcher - This is the top level of the generated matcher, the result.
98 /// CurPredicate - As we emit matcher nodes, this points to the latest check
99 /// which should have future checks stuck into its Next position.
100 Matcher *CurPredicate;
102 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
105 delete PatWithNoTypes;
108 bool EmitMatcherCode(unsigned Variant);
109 void EmitResultCode();
111 Matcher *GetMatcher() const { return TheMatcher; }
113 void AddMatcher(Matcher *NewNode);
114 void InferPossibleTypes(unsigned ForceMode);
116 // Matcher Generation.
117 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes,
119 void EmitLeafMatchCode(const TreePatternNode *N);
120 void EmitOperatorMatchCode(const TreePatternNode *N,
121 TreePatternNode *NodeNoTypes,
124 /// If this is the first time a node with unique identifier Name has been
125 /// seen, record it. Otherwise, emit a check to make sure this is the same
126 /// node. Returns true if this is the first encounter.
127 bool recordUniqueNode(const std::string &Name);
129 // Result Code Generation.
130 unsigned getNamedArgumentSlot(StringRef Name) {
131 unsigned VarMapEntry = VariableMap[Name];
132 assert(VarMapEntry != 0 &&
133 "Variable referenced but not defined and not caught earlier!");
134 return VarMapEntry-1;
137 /// GetInstPatternNode - Get the pattern for an instruction.
138 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
139 const TreePatternNode *N);
141 void EmitResultOperand(const TreePatternNode *N,
142 SmallVectorImpl<unsigned> &ResultOps);
143 void EmitResultOfNamedOperand(const TreePatternNode *N,
144 SmallVectorImpl<unsigned> &ResultOps);
145 void EmitResultLeafAsOperand(const TreePatternNode *N,
146 SmallVectorImpl<unsigned> &ResultOps);
147 void EmitResultInstructionAsOperand(const TreePatternNode *N,
148 SmallVectorImpl<unsigned> &ResultOps);
149 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
150 SmallVectorImpl<unsigned> &ResultOps);
153 } // end anon namespace.
155 MatcherGen::MatcherGen(const PatternToMatch &pattern,
156 const CodeGenDAGPatterns &cgp)
157 : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
158 TheMatcher(nullptr), CurPredicate(nullptr) {
159 // We need to produce the matcher tree for the patterns source pattern. To do
160 // this we need to match the structure as well as the types. To do the type
161 // matching, we want to figure out the fewest number of type checks we need to
162 // emit. For example, if there is only one integer type supported by a
163 // target, there should be no type comparisons at all for integer patterns!
165 // To figure out the fewest number of type checks needed, clone the pattern,
166 // remove the types, then perform type inference on the pattern as a whole.
167 // If there are unresolved types, emit an explicit check for those types,
168 // apply the type to the tree, then rerun type inference. Iterate until all
169 // types are resolved.
171 PatWithNoTypes = Pattern.getSrcPattern()->clone();
172 PatWithNoTypes->RemoveAllTypes();
174 // If there are types that are manifestly known, infer them.
175 InferPossibleTypes(Pattern.ForceMode);
178 /// InferPossibleTypes - As we emit the pattern, we end up generating type
179 /// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
180 /// want to propagate implied types as far throughout the tree as possible so
181 /// that we avoid doing redundant type checks. This does the type propagation.
182 void MatcherGen::InferPossibleTypes(unsigned ForceMode) {
183 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
184 // diagnostics, which we know are impossible at this point.
185 TreePattern &TP = *CGP.pf_begin()->second;
186 TP.getInfer().CodeGen = true;
187 TP.getInfer().ForceMode = ForceMode;
189 bool MadeChange = true;
191 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
192 true/*Ignore reg constraints*/);
196 /// AddMatcher - Add a matcher node to the current graph we're building.
197 void MatcherGen::AddMatcher(Matcher *NewNode) {
199 CurPredicate->setNext(NewNode);
201 TheMatcher = NewNode;
202 CurPredicate = NewNode;
206 //===----------------------------------------------------------------------===//
207 // Pattern Match Generation
208 //===----------------------------------------------------------------------===//
210 /// EmitLeafMatchCode - Generate matching code for leaf nodes.
211 void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
212 assert(N->isLeaf() && "Not a leaf?");
214 // Direct match against an integer constant.
215 if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
216 // If this is the root of the dag we're matching, we emit a redundant opcode
217 // check to ensure that this gets folded into the normal top-level
219 if (N == Pattern.getSrcPattern()) {
220 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
221 AddMatcher(new CheckOpcodeMatcher(NI));
224 return AddMatcher(new CheckIntegerMatcher(II->getValue()));
227 // An UnsetInit represents a named node without any constraints.
228 if (isa<UnsetInit>(N->getLeafValue())) {
229 assert(N->hasName() && "Unnamed ? leaf");
233 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
235 errs() << "Unknown leaf kind: " << *N << "\n";
239 Record *LeafRec = DI->getDef();
241 // A ValueType leaf node can represent a register when named, or itself when
243 if (LeafRec->isSubClassOf("ValueType")) {
244 // A named ValueType leaf always matches: (add i32:$a, i32:$b).
247 // An unnamed ValueType as in (sext_inreg GPR:$foo, i8).
248 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
251 if (// Handle register references. Nothing to do here, they always match.
252 LeafRec->isSubClassOf("RegisterClass") ||
253 LeafRec->isSubClassOf("RegisterOperand") ||
254 LeafRec->isSubClassOf("PointerLikeRegClass") ||
255 LeafRec->isSubClassOf("SubRegIndex") ||
256 // Place holder for SRCVALUE nodes. Nothing to do here.
257 LeafRec->getName() == "srcvalue")
260 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
261 // record the register
262 if (LeafRec->isSubClassOf("Register")) {
263 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName().str(),
264 NextRecordedOperandNo));
265 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
269 if (LeafRec->isSubClassOf("CondCode"))
270 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
272 if (LeafRec->isSubClassOf("ComplexPattern")) {
273 // We can't model ComplexPattern uses that don't have their name taken yet.
274 // The OPC_CheckComplexPattern operation implicitly records the results.
275 if (N->getName().empty()) {
277 raw_string_ostream OS(S);
278 OS << "We expect complex pattern uses to have names: " << *N;
279 PrintFatalError(OS.str());
282 // Remember this ComplexPattern so that we can emit it after all the other
283 // structural matches are done.
284 unsigned InputOperand = VariableMap[N->getName()] - 1;
285 MatchedComplexPatterns.push_back(std::make_pair(N, InputOperand));
289 errs() << "Unknown leaf kind: " << *N << "\n";
293 void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
294 TreePatternNode *NodeNoTypes,
295 unsigned ForceMode) {
296 assert(!N->isLeaf() && "Not an operator?");
298 if (N->getOperator()->isSubClassOf("ComplexPattern")) {
299 // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
300 // "MY_PAT:op1:op2". We should already have validated that the uses are
302 std::string PatternName = N->getOperator()->getName();
303 for (unsigned i = 0; i < N->getNumChildren(); ++i) {
305 PatternName += N->getChild(i)->getName();
308 if (recordUniqueNode(PatternName)) {
309 auto NodeAndOpNum = std::make_pair(N, NextRecordedOperandNo - 1);
310 MatchedComplexPatterns.push_back(NodeAndOpNum);
316 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
318 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
319 // a constant without a predicate fn that has more than one bit set, handle
320 // this as a special case. This is usually for targets that have special
321 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
322 // handling stuff). Using these instructions is often far more efficient
323 // than materializing the constant. Unfortunately, both the instcombiner
324 // and the dag combiner can often infer that bits are dead, and thus drop
325 // them from the mask in the dag. For example, it might turn 'AND X, 255'
326 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
328 if ((N->getOperator()->getName() == "and" ||
329 N->getOperator()->getName() == "or") &&
330 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
331 N->getPredicateFns().empty()) {
332 if (IntInit *II = dyn_cast<IntInit>(N->getChild(1)->getLeafValue())) {
333 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
334 // If this is at the root of the pattern, we emit a redundant
335 // CheckOpcode so that the following checks get factored properly under
336 // a single opcode check.
337 if (N == Pattern.getSrcPattern())
338 AddMatcher(new CheckOpcodeMatcher(CInfo));
340 // Emit the CheckAndImm/CheckOrImm node.
341 if (N->getOperator()->getName() == "and")
342 AddMatcher(new CheckAndImmMatcher(II->getValue()));
344 AddMatcher(new CheckOrImmMatcher(II->getValue()));
346 // Match the LHS of the AND as appropriate.
347 AddMatcher(new MoveChildMatcher(0));
348 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0), ForceMode);
349 AddMatcher(new MoveParentMatcher());
355 // Check that the current opcode lines up.
356 AddMatcher(new CheckOpcodeMatcher(CInfo));
358 // If this node has memory references (i.e. is a load or store), tell the
359 // interpreter to capture them in the memref array.
360 if (N->NodeHasProperty(SDNPMemOperand, CGP))
361 AddMatcher(new RecordMemRefMatcher());
363 // If this node has a chain, then the chain is operand #0 is the SDNode, and
364 // the child numbers of the node are all offset by one.
366 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
367 // Record the node and remember it in our chained nodes list.
368 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
370 NextRecordedOperandNo));
371 // Remember all of the input chains our pattern will match.
372 MatchedChainNodes.push_back(NextRecordedOperandNo++);
374 // Don't look at the input chain when matching the tree pattern to the
378 // If this node is not the root and the subtree underneath it produces a
379 // chain, then the result of matching the node is also produce a chain.
380 // Beyond that, this means that we're also folding (at least) the root node
381 // into the node that produce the chain (for example, matching
382 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
383 // problematic, if the 'reg' node also uses the load (say, its chain).
388 // | \ DAG's like cheese.
394 // It would be invalid to fold XX and LD. In this case, folding the two
395 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
396 // To prevent this, we emit a dynamic check for legality before allowing
397 // this to be folded.
399 const TreePatternNode *Root = Pattern.getSrcPattern();
400 if (N != Root) { // Not the root of the pattern.
401 // If there is a node between the root and this node, then we definitely
402 // need to emit the check.
403 bool NeedCheck = !Root->hasChild(N);
405 // If it *is* an immediate child of the root, we can still need a check if
406 // the root SDNode has multiple inputs. For us, this means that it is an
407 // intrinsic, has multiple operands, or has other inputs like chain or
410 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
412 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
413 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
414 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
415 PInfo.getNumOperands() > 1 ||
416 PInfo.hasProperty(SDNPHasChain) ||
417 PInfo.hasProperty(SDNPInGlue) ||
418 PInfo.hasProperty(SDNPOptInGlue);
422 AddMatcher(new CheckFoldableChainNodeMatcher());
426 // If this node has an output glue and isn't the root, remember it.
427 if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
428 N != Pattern.getSrcPattern()) {
429 // TODO: This redundantly records nodes with both glues and chains.
431 // Record the node and remember it in our chained nodes list.
432 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
433 "' glue output node",
434 NextRecordedOperandNo));
437 // If this node is known to have an input glue or if it *might* have an input
438 // glue, capture it as the glue input of the pattern.
439 if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
440 N->NodeHasProperty(SDNPInGlue, CGP))
441 AddMatcher(new CaptureGlueInputMatcher());
443 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
444 // Get the code suitable for matching this child. Move to the child, check
445 // it then move back to the parent.
446 AddMatcher(new MoveChildMatcher(OpNo));
447 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i), ForceMode);
448 AddMatcher(new MoveParentMatcher());
452 bool MatcherGen::recordUniqueNode(const std::string &Name) {
453 unsigned &VarMapEntry = VariableMap[Name];
454 if (VarMapEntry == 0) {
455 // If it is a named node, we must emit a 'Record' opcode.
456 AddMatcher(new RecordMatcher("$" + Name, NextRecordedOperandNo));
457 VarMapEntry = ++NextRecordedOperandNo;
461 // If we get here, this is a second reference to a specific name. Since
462 // we already have checked that the first reference is valid, we don't
463 // have to recursively match it, just check that it's the same as the
464 // previously named thing.
465 AddMatcher(new CheckSameMatcher(VarMapEntry-1));
469 void MatcherGen::EmitMatchCode(const TreePatternNode *N,
470 TreePatternNode *NodeNoTypes,
471 unsigned ForceMode) {
472 // If N and NodeNoTypes don't agree on a type, then this is a case where we
473 // need to do a type check. Emit the check, apply the type to NodeNoTypes and
474 // reinfer any correlated types.
475 SmallVector<unsigned, 2> ResultsToTypeCheck;
477 for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
478 if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
479 NodeNoTypes->setType(i, N->getExtType(i));
480 InferPossibleTypes(ForceMode);
481 ResultsToTypeCheck.push_back(i);
484 // If this node has a name associated with it, capture it in VariableMap. If
485 // we already saw this in the pattern, emit code to verify dagness.
486 if (!N->getName().empty())
487 if (!recordUniqueNode(N->getName()))
491 EmitLeafMatchCode(N);
493 EmitOperatorMatchCode(N, NodeNoTypes, ForceMode);
495 // If there are node predicates for this node, generate their checks.
496 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
497 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
499 for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
500 AddMatcher(new CheckTypeMatcher(N->getSimpleType(ResultsToTypeCheck[i]),
501 ResultsToTypeCheck[i]));
504 /// EmitMatcherCode - Generate the code that matches the predicate of this
505 /// pattern for the specified Variant. If the variant is invalid this returns
506 /// true and does not generate code, if it is valid, it returns false.
507 bool MatcherGen::EmitMatcherCode(unsigned Variant) {
508 // If the root of the pattern is a ComplexPattern and if it is specified to
509 // match some number of root opcodes, these are considered to be our variants.
510 // Depending on which variant we're generating code for, emit the root opcode
512 if (const ComplexPattern *CP =
513 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
514 const std::vector<Record*> &OpNodes = CP->getRootNodes();
515 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
516 if (Variant >= OpNodes.size()) return true;
518 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
520 if (Variant != 0) return true;
523 // Emit the matcher for the pattern structure and types.
524 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes, Pattern.ForceMode);
526 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
527 // feature is around, do the check).
528 if (!Pattern.getPredicateCheck().empty())
529 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
531 // Now that we've completed the structural type match, emit any ComplexPattern
532 // checks (e.g. addrmode matches). We emit this after the structural match
533 // because they are generally more expensive to evaluate and more difficult to
535 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
536 const TreePatternNode *N = MatchedComplexPatterns[i].first;
538 // Remember where the results of this match get stuck.
540 NamedComplexPatternOperands[N->getName()] = NextRecordedOperandNo + 1;
542 unsigned CurOp = NextRecordedOperandNo;
543 for (unsigned i = 0; i < N->getNumChildren(); ++i) {
544 NamedComplexPatternOperands[N->getChild(i)->getName()] = CurOp + 1;
545 CurOp += N->getChild(i)->getNumMIResults(CGP);
549 // Get the slot we recorded the value in from the name on the node.
550 unsigned RecNodeEntry = MatchedComplexPatterns[i].second;
552 const ComplexPattern &CP = *N->getComplexPatternInfo(CGP);
554 // Emit a CheckComplexPat operation, which does the match (aborting if it
555 // fails) and pushes the matched operands onto the recorded nodes list.
556 AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
557 N->getName(), NextRecordedOperandNo));
559 // Record the right number of operands.
560 NextRecordedOperandNo += CP.getNumOperands();
561 if (CP.hasProperty(SDNPHasChain)) {
562 // If the complex pattern has a chain, then we need to keep track of the
563 // fact that we just recorded a chain input. The chain input will be
564 // matched as the last operand of the predicate if it was successful.
565 ++NextRecordedOperandNo; // Chained node operand.
567 // It is the last operand recorded.
568 assert(NextRecordedOperandNo > 1 &&
569 "Should have recorded input/result chains at least!");
570 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
573 // TODO: Complex patterns can't have output glues, if they did, we'd want
581 //===----------------------------------------------------------------------===//
582 // Node Result Generation
583 //===----------------------------------------------------------------------===//
585 void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
586 SmallVectorImpl<unsigned> &ResultOps){
587 assert(!N->getName().empty() && "Operand not named!");
589 if (unsigned SlotNo = NamedComplexPatternOperands[N->getName()]) {
590 // Complex operands have already been completely selected, just find the
591 // right slot ant add the arguments directly.
592 for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
593 ResultOps.push_back(SlotNo - 1 + i);
598 unsigned SlotNo = getNamedArgumentSlot(N->getName());
600 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
601 // version of the immediate so that it doesn't get selected due to some other
604 StringRef OperatorName = N->getOperator()->getName();
605 if (OperatorName == "imm" || OperatorName == "fpimm") {
606 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
607 ResultOps.push_back(NextRecordedOperandNo++);
612 for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
613 ResultOps.push_back(SlotNo + i);
616 void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
617 SmallVectorImpl<unsigned> &ResultOps) {
618 assert(N->isLeaf() && "Must be a leaf");
620 if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
621 AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getSimpleType(0)));
622 ResultOps.push_back(NextRecordedOperandNo++);
626 // If this is an explicit register reference, handle it.
627 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
628 Record *Def = DI->getDef();
629 if (Def->isSubClassOf("Register")) {
630 const CodeGenRegister *Reg =
631 CGP.getTargetInfo().getRegBank().getReg(Def);
632 AddMatcher(new EmitRegisterMatcher(Reg, N->getSimpleType(0)));
633 ResultOps.push_back(NextRecordedOperandNo++);
637 if (Def->getName() == "zero_reg") {
638 AddMatcher(new EmitRegisterMatcher(nullptr, N->getSimpleType(0)));
639 ResultOps.push_back(NextRecordedOperandNo++);
643 // Handle a reference to a register class. This is used
644 // in COPY_TO_SUBREG instructions.
645 if (Def->isSubClassOf("RegisterOperand"))
646 Def = Def->getValueAsDef("RegClass");
647 if (Def->isSubClassOf("RegisterClass")) {
648 std::string Value = getQualifiedName(Def) + "RegClassID";
649 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
650 ResultOps.push_back(NextRecordedOperandNo++);
654 // Handle a subregister index. This is used for INSERT_SUBREG etc.
655 if (Def->isSubClassOf("SubRegIndex")) {
656 std::string Value = getQualifiedName(Def);
657 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
658 ResultOps.push_back(NextRecordedOperandNo++);
663 errs() << "unhandled leaf node: \n";
667 /// GetInstPatternNode - Get the pattern for an instruction.
669 const TreePatternNode *MatcherGen::
670 GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
671 const TreePattern *InstPat = Inst.getPattern();
673 // FIXME2?: Assume actual pattern comes before "implicit".
674 TreePatternNode *InstPatNode;
676 InstPatNode = InstPat->getTree(0);
677 else if (/*isRoot*/ N == Pattern.getDstPattern())
678 InstPatNode = Pattern.getSrcPattern();
682 if (InstPatNode && !InstPatNode->isLeaf() &&
683 InstPatNode->getOperator()->getName() == "set")
684 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
690 mayInstNodeLoadOrStore(const TreePatternNode *N,
691 const CodeGenDAGPatterns &CGP) {
692 Record *Op = N->getOperator();
693 const CodeGenTarget &CGT = CGP.getTargetInfo();
694 CodeGenInstruction &II = CGT.getInstruction(Op);
695 return II.mayLoad || II.mayStore;
699 numNodesThatMayLoadOrStore(const TreePatternNode *N,
700 const CodeGenDAGPatterns &CGP) {
704 Record *OpRec = N->getOperator();
705 if (!OpRec->isSubClassOf("Instruction"))
709 if (mayInstNodeLoadOrStore(N, CGP))
712 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
713 Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
719 EmitResultInstructionAsOperand(const TreePatternNode *N,
720 SmallVectorImpl<unsigned> &OutputOps) {
721 Record *Op = N->getOperator();
722 const CodeGenTarget &CGT = CGP.getTargetInfo();
723 CodeGenInstruction &II = CGT.getInstruction(Op);
724 const DAGInstruction &Inst = CGP.getInstruction(Op);
726 // If we can, get the pattern for the instruction we're generating. We derive
727 // a variety of information from this pattern, such as whether it has a chain.
729 // FIXME2: This is extremely dubious for several reasons, not the least of
730 // which it gives special status to instructions with patterns that Pat<>
731 // nodes can't duplicate.
732 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
734 // NodeHasChain - Whether the instruction node we're creating takes chains.
735 bool NodeHasChain = InstPatNode &&
736 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
738 // Instructions which load and store from memory should have a chain,
739 // regardless of whether they happen to have an internal pattern saying so.
740 if (Pattern.getSrcPattern()->TreeHasProperty(SDNPHasChain, CGP)
741 && (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad ||
745 bool isRoot = N == Pattern.getDstPattern();
747 // TreeHasOutGlue - True if this tree has glue.
748 bool TreeHasInGlue = false, TreeHasOutGlue = false;
750 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
751 TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
752 SrcPat->TreeHasProperty(SDNPInGlue, CGP);
754 // FIXME2: this is checking the entire pattern, not just the node in
755 // question, doing this just for the root seems like a total hack.
756 TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
759 // NumResults - This is the number of results produced by the instruction in
761 unsigned NumResults = Inst.getNumResults();
763 // Number of operands we know the output instruction must have. If it is
764 // variadic, we could have more operands.
765 unsigned NumFixedOperands = II.Operands.size();
767 SmallVector<unsigned, 8> InstOps;
769 // Loop over all of the fixed operands of the instruction pattern, emitting
770 // code to fill them all in. The node 'N' usually has number children equal to
771 // the number of input operands of the instruction. However, in cases where
772 // there are predicate operands for an instruction, we need to fill in the
773 // 'execute always' values. Match up the node operands to the instruction
774 // operands to do this.
775 unsigned ChildNo = 0;
776 for (unsigned InstOpNo = NumResults, e = NumFixedOperands;
777 InstOpNo != e; ++InstOpNo) {
778 // Determine what to emit for this operand.
779 Record *OperandNode = II.Operands[InstOpNo].Rec;
780 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
781 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
782 // This is a predicate or optional def operand; emit the
783 // 'default ops' operands.
784 const DAGDefaultOperand &DefaultOp
785 = CGP.getDefaultOperand(OperandNode);
786 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
787 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
791 // Otherwise this is a normal operand or a predicate operand without
792 // 'execute always'; emit it.
794 // For operands with multiple sub-operands we may need to emit
795 // multiple child patterns to cover them all. However, ComplexPattern
796 // children may themselves emit multiple MI operands.
797 unsigned NumSubOps = 1;
798 if (OperandNode->isSubClassOf("Operand")) {
799 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
800 if (unsigned NumArgs = MIOpInfo->getNumArgs())
804 unsigned FinalNumOps = InstOps.size() + NumSubOps;
805 while (InstOps.size() < FinalNumOps) {
806 const TreePatternNode *Child = N->getChild(ChildNo);
807 unsigned BeforeAddingNumOps = InstOps.size();
808 EmitResultOperand(Child, InstOps);
809 assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
811 // If the operand is an instruction and it produced multiple results, just
812 // take the first one.
813 if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
814 InstOps.resize(BeforeAddingNumOps+1);
820 // If this is a variadic output instruction (i.e. REG_SEQUENCE), we can't
821 // expand suboperands, use default operands, or other features determined from
822 // the CodeGenInstruction after the fixed operands, which were handled
823 // above. Emit the remaining instructions implicitly added by the use for
825 if (II.Operands.isVariadic) {
826 for (unsigned I = ChildNo, E = N->getNumChildren(); I < E; ++I)
827 EmitResultOperand(N->getChild(I), InstOps);
830 // If this node has input glue or explicitly specified input physregs, we
831 // need to add chained and glued copyfromreg nodes and materialize the glue
833 if (isRoot && !PhysRegInputs.empty()) {
834 // Emit all of the CopyToReg nodes for the input physical registers. These
835 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
836 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
837 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
838 PhysRegInputs[i].first));
839 // Even if the node has no other glue inputs, the resultant node must be
840 // glued to the CopyFromReg nodes we just generated.
841 TreeHasInGlue = true;
844 // Result order: node results, chain, glue
846 // Determine the result types.
847 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
848 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
849 ResultVTs.push_back(N->getSimpleType(i));
851 // If this is the root instruction of a pattern that has physical registers in
852 // its result pattern, add output VTs for them. For example, X86 has:
853 // (set AL, (mul ...))
854 // This also handles implicit results like:
856 if (isRoot && !Pattern.getDstRegs().empty()) {
857 // If the root came from an implicit def in the instruction handling stuff,
859 Record *HandledReg = nullptr;
860 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
861 HandledReg = II.ImplicitDefs[0];
863 for (Record *Reg : Pattern.getDstRegs()) {
864 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
865 ResultVTs.push_back(getRegisterValueType(Reg, CGT));
869 // If this is the root of the pattern and the pattern we're matching includes
870 // a node that is variadic, mark the generated node as variadic so that it
871 // gets the excess operands from the input DAG.
872 int NumFixedArityOperands = -1;
874 Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP))
875 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
877 // If this is the root node and multiple matched nodes in the input pattern
878 // have MemRefs in them, have the interpreter collect them and plop them onto
879 // this node. If there is just one node with MemRefs, leave them on that node
880 // even if it is not the root.
882 // FIXME3: This is actively incorrect for result patterns with multiple
883 // memory-referencing instructions.
884 bool PatternHasMemOperands =
885 Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
887 bool NodeHasMemRefs = false;
888 if (PatternHasMemOperands) {
889 unsigned NumNodesThatLoadOrStore =
890 numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
891 bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
892 NumNodesThatLoadOrStore == 1;
894 NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
895 NumNodesThatLoadOrStore != 1));
898 assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
899 "Node has no result");
901 AddMatcher(new EmitNodeMatcher(II.Namespace.str()+"::"+II.TheDef->getName().str(),
903 NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
904 NodeHasMemRefs, NumFixedArityOperands,
905 NextRecordedOperandNo));
907 // The non-chain and non-glue results of the newly emitted node get recorded.
908 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
909 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
910 OutputOps.push_back(NextRecordedOperandNo++);
915 EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
916 SmallVectorImpl<unsigned> &ResultOps) {
917 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
920 SmallVector<unsigned, 8> InputOps;
922 // FIXME2: Could easily generalize this to support multiple inputs and outputs
923 // to the SDNodeXForm. For now we just support one input and one output like
924 // the old instruction selector.
925 assert(N->getNumChildren() == 1);
926 EmitResultOperand(N->getChild(0), InputOps);
928 // The input currently must have produced exactly one result.
929 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
931 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
932 ResultOps.push_back(NextRecordedOperandNo++);
935 void MatcherGen::EmitResultOperand(const TreePatternNode *N,
936 SmallVectorImpl<unsigned> &ResultOps) {
937 // This is something selected from the pattern we matched.
938 if (!N->getName().empty())
939 return EmitResultOfNamedOperand(N, ResultOps);
942 return EmitResultLeafAsOperand(N, ResultOps);
944 Record *OpRec = N->getOperator();
945 if (OpRec->isSubClassOf("Instruction"))
946 return EmitResultInstructionAsOperand(N, ResultOps);
947 if (OpRec->isSubClassOf("SDNodeXForm"))
948 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
949 errs() << "Unknown result node to emit code for: " << *N << '\n';
950 PrintFatalError("Unknown node in result pattern!");
953 void MatcherGen::EmitResultCode() {
954 // Patterns that match nodes with (potentially multiple) chain inputs have to
955 // merge them together into a token factor. This informs the generated code
956 // what all the chained nodes are.
957 if (!MatchedChainNodes.empty())
958 AddMatcher(new EmitMergeInputChainsMatcher(MatchedChainNodes));
960 // Codegen the root of the result pattern, capturing the resulting values.
961 SmallVector<unsigned, 8> Ops;
962 EmitResultOperand(Pattern.getDstPattern(), Ops);
964 // At this point, we have however many values the result pattern produces.
965 // However, the input pattern might not need all of these. If there are
966 // excess values at the end (such as implicit defs of condition codes etc)
967 // just lop them off. This doesn't need to worry about glue or chains, just
970 unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
972 // If the pattern also has (implicit) results, count them as well.
973 if (!Pattern.getDstRegs().empty()) {
974 // If the root came from an implicit def in the instruction handling stuff,
976 Record *HandledReg = nullptr;
977 const TreePatternNode *DstPat = Pattern.getDstPattern();
978 if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
979 const CodeGenTarget &CGT = CGP.getTargetInfo();
980 CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
982 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
983 HandledReg = II.ImplicitDefs[0];
986 for (Record *Reg : Pattern.getDstRegs()) {
987 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
992 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
993 Ops.resize(NumSrcResults);
995 AddMatcher(new CompleteMatchMatcher(Ops, Pattern));
999 /// ConvertPatternToMatcher - Create the matcher for the specified pattern with
1000 /// the specified variant. If the variant number is invalid, this returns null.
1001 Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
1003 const CodeGenDAGPatterns &CGP) {
1004 MatcherGen Gen(Pattern, CGP);
1006 // Generate the code for the matcher.
1007 if (Gen.EmitMatcherCode(Variant))
1010 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
1011 // FIXME2: Split result code out to another table, and make the matcher end
1012 // with an "Emit <index>" command. This allows result generation stuff to be
1013 // shared and factored?
1015 // If the match succeeds, then we generate Pattern.
1016 Gen.EmitResultCode();
1018 // Unconditional match.
1019 return Gen.GetMatcher();