1 //===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "CodeGenDAGPatterns.h"
10 #include "CodeGenInstruction.h"
11 #include "CodeGenRegisters.h"
12 #include "CodeGenTarget.h"
13 #include "DAGISelMatcher.h"
14 #include "InfoByHwMode.h"
15 #include "SDNodeProperties.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/TableGen/Error.h"
19 #include "llvm/TableGen/Record.h"
20 #include <utility>
21 using namespace llvm;
22 
23 
24 /// getRegisterValueType - Look up and return the ValueType of the specified
25 /// register. If the register is a member of multiple register classes, they
26 /// must all have the same type.
getRegisterValueType(Record * R,const CodeGenTarget & T)27 static MVT::SimpleValueType getRegisterValueType(Record *R,
28                                                  const CodeGenTarget &T) {
29   bool FoundRC = false;
30   MVT::SimpleValueType VT = MVT::Other;
31   const CodeGenRegister *Reg = T.getRegBank().getReg(R);
32 
33   for (const auto &RC : T.getRegBank().getRegClasses()) {
34     if (!RC.contains(Reg))
35       continue;
36 
37     if (!FoundRC) {
38       FoundRC = true;
39       const ValueTypeByHwMode &VVT = RC.getValueTypeNum(0);
40       assert(VVT.isSimple());
41       VT = VVT.getSimple().SimpleTy;
42       continue;
43     }
44 
45 #ifndef NDEBUG
46     // If this occurs in multiple register classes, they all have to agree.
47     const ValueTypeByHwMode &VVT = RC.getValueTypeNum(0);
48     assert(VVT.isSimple() && VVT.getSimple().SimpleTy == VT &&
49            "ValueType mismatch between register classes for this register");
50 #endif
51   }
52   return VT;
53 }
54 
55 
56 namespace {
57   class MatcherGen {
58     const PatternToMatch &Pattern;
59     const CodeGenDAGPatterns &CGP;
60 
61     /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
62     /// out with all of the types removed.  This allows us to insert type checks
63     /// as we scan the tree.
64     TreePatternNodePtr PatWithNoTypes;
65 
66     /// VariableMap - A map from variable names ('$dst') to the recorded operand
67     /// number that they were captured as.  These are biased by 1 to make
68     /// insertion easier.
69     StringMap<unsigned> VariableMap;
70 
71     /// This maintains the recorded operand number that OPC_CheckComplexPattern
72     /// drops each sub-operand into. We don't want to insert these into
73     /// VariableMap because that leads to identity checking if they are
74     /// encountered multiple times. Biased by 1 like VariableMap for
75     /// consistency.
76     StringMap<unsigned> NamedComplexPatternOperands;
77 
78     /// NextRecordedOperandNo - As we emit opcodes to record matched values in
79     /// the RecordedNodes array, this keeps track of which slot will be next to
80     /// record into.
81     unsigned NextRecordedOperandNo;
82 
83     /// MatchedChainNodes - This maintains the position in the recorded nodes
84     /// array of all of the recorded input nodes that have chains.
85     SmallVector<unsigned, 2> MatchedChainNodes;
86 
87     /// MatchedComplexPatterns - This maintains a list of all of the
88     /// ComplexPatterns that we need to check. The second element of each pair
89     /// is the recorded operand number of the input node.
90     SmallVector<std::pair<const TreePatternNode*,
91                           unsigned>, 2> MatchedComplexPatterns;
92 
93     /// PhysRegInputs - List list has an entry for each explicitly specified
94     /// physreg input to the pattern.  The first elt is the Register node, the
95     /// second is the recorded slot number the input pattern match saved it in.
96     SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
97 
98     /// Matcher - This is the top level of the generated matcher, the result.
99     Matcher *TheMatcher;
100 
101     /// CurPredicate - As we emit matcher nodes, this points to the latest check
102     /// which should have future checks stuck into its Next position.
103     Matcher *CurPredicate;
104   public:
105     MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
106 
107     bool EmitMatcherCode(unsigned Variant);
108     void EmitResultCode();
109 
GetMatcher() const110     Matcher *GetMatcher() const { return TheMatcher; }
111   private:
112     void AddMatcher(Matcher *NewNode);
113     void InferPossibleTypes();
114 
115     // Matcher Generation.
116     void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
117     void EmitLeafMatchCode(const TreePatternNode *N);
118     void EmitOperatorMatchCode(const TreePatternNode *N,
119                                TreePatternNode *NodeNoTypes);
120 
121     /// If this is the first time a node with unique identifier Name has been
122     /// seen, record it. Otherwise, emit a check to make sure this is the same
123     /// node. Returns true if this is the first encounter.
124     bool recordUniqueNode(ArrayRef<std::string> Names);
125 
126     // Result Code Generation.
getNamedArgumentSlot(StringRef Name)127     unsigned getNamedArgumentSlot(StringRef Name) {
128       unsigned VarMapEntry = VariableMap[Name];
129       assert(VarMapEntry != 0 &&
130              "Variable referenced but not defined and not caught earlier!");
131       return VarMapEntry-1;
132     }
133 
134     void EmitResultOperand(const TreePatternNode *N,
135                            SmallVectorImpl<unsigned> &ResultOps);
136     void EmitResultOfNamedOperand(const TreePatternNode *N,
137                                   SmallVectorImpl<unsigned> &ResultOps);
138     void EmitResultLeafAsOperand(const TreePatternNode *N,
139                                  SmallVectorImpl<unsigned> &ResultOps);
140     void EmitResultInstructionAsOperand(const TreePatternNode *N,
141                                         SmallVectorImpl<unsigned> &ResultOps);
142     void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
143                                         SmallVectorImpl<unsigned> &ResultOps);
144     };
145 
146 } // end anonymous namespace
147 
MatcherGen(const PatternToMatch & pattern,const CodeGenDAGPatterns & cgp)148 MatcherGen::MatcherGen(const PatternToMatch &pattern,
149                        const CodeGenDAGPatterns &cgp)
150     : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0), TheMatcher(nullptr),
151       CurPredicate(nullptr) {
152   // We need to produce the matcher tree for the patterns source pattern.  To
153   // do this we need to match the structure as well as the types.  To do the
154   // type matching, we want to figure out the fewest number of type checks we
155   // need to emit.  For example, if there is only one integer type supported
156   // by a target, there should be no type comparisons at all for integer
157   // patterns!
158   //
159   // To figure out the fewest number of type checks needed, clone the pattern,
160   // remove the types, then perform type inference on the pattern as a whole.
161   // If there are unresolved types, emit an explicit check for those types,
162   // apply the type to the tree, then rerun type inference.  Iterate until all
163   // types are resolved.
164   //
165   PatWithNoTypes = Pattern.getSrcPattern()->clone();
166   PatWithNoTypes->RemoveAllTypes();
167 
168   // If there are types that are manifestly known, infer them.
169   InferPossibleTypes();
170 }
171 
172 /// InferPossibleTypes - As we emit the pattern, we end up generating type
173 /// checks and applying them to the 'PatWithNoTypes' tree.  As we do this, we
174 /// want to propagate implied types as far throughout the tree as possible so
175 /// that we avoid doing redundant type checks.  This does the type propagation.
InferPossibleTypes()176 void MatcherGen::InferPossibleTypes() {
177   // TP - Get *SOME* tree pattern, we don't care which.  It is only used for
178   // diagnostics, which we know are impossible at this point.
179   TreePattern &TP = *CGP.pf_begin()->second;
180 
181   bool MadeChange = true;
182   while (MadeChange)
183     MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
184                                               true/*Ignore reg constraints*/);
185 }
186 
187 
188 /// AddMatcher - Add a matcher node to the current graph we're building.
AddMatcher(Matcher * NewNode)189 void MatcherGen::AddMatcher(Matcher *NewNode) {
190   if (CurPredicate)
191     CurPredicate->setNext(NewNode);
192   else
193     TheMatcher = NewNode;
194   CurPredicate = NewNode;
195 }
196 
197 
198 //===----------------------------------------------------------------------===//
199 // Pattern Match Generation
200 //===----------------------------------------------------------------------===//
201 
202 /// EmitLeafMatchCode - Generate matching code for leaf nodes.
EmitLeafMatchCode(const TreePatternNode * N)203 void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
204   assert(N->isLeaf() && "Not a leaf?");
205 
206   // Direct match against an integer constant.
207   if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
208     // If this is the root of the dag we're matching, we emit a redundant opcode
209     // check to ensure that this gets folded into the normal top-level
210     // OpcodeSwitch.
211     if (N == Pattern.getSrcPattern()) {
212       const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
213       AddMatcher(new CheckOpcodeMatcher(NI));
214     }
215 
216     return AddMatcher(new CheckIntegerMatcher(II->getValue()));
217   }
218 
219   // An UnsetInit represents a named node without any constraints.
220   if (isa<UnsetInit>(N->getLeafValue())) {
221     assert(N->hasName() && "Unnamed ? leaf");
222     return;
223   }
224 
225   DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
226   if (!DI) {
227     errs() << "Unknown leaf kind: " << *N << "\n";
228     abort();
229   }
230 
231   Record *LeafRec = DI->getDef();
232 
233   // A ValueType leaf node can represent a register when named, or itself when
234   // unnamed.
235   if (LeafRec->isSubClassOf("ValueType")) {
236     // A named ValueType leaf always matches: (add i32:$a, i32:$b).
237     if (N->hasName())
238       return;
239     // An unnamed ValueType as in (sext_inreg GPR:$foo, i8).
240     return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
241   }
242 
243   if (// Handle register references.  Nothing to do here, they always match.
244       LeafRec->isSubClassOf("RegisterClass") ||
245       LeafRec->isSubClassOf("RegisterOperand") ||
246       LeafRec->isSubClassOf("PointerLikeRegClass") ||
247       LeafRec->isSubClassOf("SubRegIndex") ||
248       // Place holder for SRCVALUE nodes. Nothing to do here.
249       LeafRec->getName() == "srcvalue")
250     return;
251 
252   // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
253   // record the register
254   if (LeafRec->isSubClassOf("Register")) {
255     AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName().str(),
256                                  NextRecordedOperandNo));
257     PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
258     return;
259   }
260 
261   if (LeafRec->isSubClassOf("CondCode"))
262     return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
263 
264   if (LeafRec->isSubClassOf("ComplexPattern")) {
265     // We can't model ComplexPattern uses that don't have their name taken yet.
266     // The OPC_CheckComplexPattern operation implicitly records the results.
267     if (N->getName().empty()) {
268       std::string S;
269       raw_string_ostream OS(S);
270       OS << "We expect complex pattern uses to have names: " << *N;
271       PrintFatalError(S);
272     }
273 
274     // Remember this ComplexPattern so that we can emit it after all the other
275     // structural matches are done.
276     unsigned InputOperand = VariableMap[N->getName()] - 1;
277     MatchedComplexPatterns.push_back(std::make_pair(N, InputOperand));
278     return;
279   }
280 
281   if (LeafRec->getName() == "immAllOnesV" ||
282       LeafRec->getName() == "immAllZerosV") {
283     // If this is the root of the dag we're matching, we emit a redundant opcode
284     // check to ensure that this gets folded into the normal top-level
285     // OpcodeSwitch.
286     if (N == Pattern.getSrcPattern()) {
287       MVT VT = N->getSimpleType(0);
288       StringRef Name = VT.isScalableVector() ? "splat_vector" : "build_vector";
289       const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed(Name));
290       AddMatcher(new CheckOpcodeMatcher(NI));
291     }
292     if (LeafRec->getName() == "immAllOnesV")
293       AddMatcher(new CheckImmAllOnesVMatcher());
294     else
295       AddMatcher(new CheckImmAllZerosVMatcher());
296     return;
297   }
298 
299   errs() << "Unknown leaf kind: " << *N << "\n";
300   abort();
301 }
302 
EmitOperatorMatchCode(const TreePatternNode * N,TreePatternNode * NodeNoTypes)303 void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
304                                        TreePatternNode *NodeNoTypes) {
305   assert(!N->isLeaf() && "Not an operator?");
306 
307   if (N->getOperator()->isSubClassOf("ComplexPattern")) {
308     // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
309     // "MY_PAT:op1:op2". We should already have validated that the uses are
310     // consistent.
311     std::string PatternName = std::string(N->getOperator()->getName());
312     for (unsigned i = 0; i < N->getNumChildren(); ++i) {
313       PatternName += ":";
314       PatternName += N->getChild(i)->getName();
315     }
316 
317     if (recordUniqueNode(PatternName)) {
318       auto NodeAndOpNum = std::make_pair(N, NextRecordedOperandNo - 1);
319       MatchedComplexPatterns.push_back(NodeAndOpNum);
320     }
321 
322     return;
323   }
324 
325   const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
326 
327   // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
328   // a constant without a predicate fn that has more than one bit set, handle
329   // this as a special case.  This is usually for targets that have special
330   // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
331   // handling stuff).  Using these instructions is often far more efficient
332   // than materializing the constant.  Unfortunately, both the instcombiner
333   // and the dag combiner can often infer that bits are dead, and thus drop
334   // them from the mask in the dag.  For example, it might turn 'AND X, 255'
335   // into 'AND X, 254' if it knows the low bit is set.  Emit code that checks
336   // to handle this.
337   if ((N->getOperator()->getName() == "and" ||
338        N->getOperator()->getName() == "or") &&
339       N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateCalls().empty() &&
340       N->getPredicateCalls().empty()) {
341     if (IntInit *II = dyn_cast<IntInit>(N->getChild(1)->getLeafValue())) {
342       if (!llvm::has_single_bit<uint32_t>(
343               II->getValue())) { // Don't bother with single bits.
344         // If this is at the root of the pattern, we emit a redundant
345         // CheckOpcode so that the following checks get factored properly under
346         // a single opcode check.
347         if (N == Pattern.getSrcPattern())
348           AddMatcher(new CheckOpcodeMatcher(CInfo));
349 
350         // Emit the CheckAndImm/CheckOrImm node.
351         if (N->getOperator()->getName() == "and")
352           AddMatcher(new CheckAndImmMatcher(II->getValue()));
353         else
354           AddMatcher(new CheckOrImmMatcher(II->getValue()));
355 
356         // Match the LHS of the AND as appropriate.
357         AddMatcher(new MoveChildMatcher(0));
358         EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
359         AddMatcher(new MoveParentMatcher());
360         return;
361       }
362     }
363   }
364 
365   // Check that the current opcode lines up.
366   AddMatcher(new CheckOpcodeMatcher(CInfo));
367 
368   // If this node has memory references (i.e. is a load or store), tell the
369   // interpreter to capture them in the memref array.
370   if (N->NodeHasProperty(SDNPMemOperand, CGP))
371     AddMatcher(new RecordMemRefMatcher());
372 
373   // If this node has a chain, then the chain is operand #0 is the SDNode, and
374   // the child numbers of the node are all offset by one.
375   unsigned OpNo = 0;
376   if (N->NodeHasProperty(SDNPHasChain, CGP)) {
377     // Record the node and remember it in our chained nodes list.
378     AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
379                                          "' chained node",
380                                  NextRecordedOperandNo));
381     // Remember all of the input chains our pattern will match.
382     MatchedChainNodes.push_back(NextRecordedOperandNo++);
383 
384     // Don't look at the input chain when matching the tree pattern to the
385     // SDNode.
386     OpNo = 1;
387 
388     // If this node is not the root and the subtree underneath it produces a
389     // chain, then the result of matching the node is also produce a chain.
390     // Beyond that, this means that we're also folding (at least) the root node
391     // into the node that produce the chain (for example, matching
392     // "(add reg, (load ptr))" as a add_with_memory on X86).  This is
393     // problematic, if the 'reg' node also uses the load (say, its chain).
394     // Graphically:
395     //
396     //         [LD]
397     //         ^  ^
398     //         |  \                              DAG's like cheese.
399     //        /    |
400     //       /    [YY]
401     //       |     ^
402     //      [XX]--/
403     //
404     // It would be invalid to fold XX and LD.  In this case, folding the two
405     // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
406     // To prevent this, we emit a dynamic check for legality before allowing
407     // this to be folded.
408     //
409     const TreePatternNode *Root = Pattern.getSrcPattern();
410     if (N != Root) {                             // Not the root of the pattern.
411       // If there is a node between the root and this node, then we definitely
412       // need to emit the check.
413       bool NeedCheck = !Root->hasChild(N);
414 
415       // If it *is* an immediate child of the root, we can still need a check if
416       // the root SDNode has multiple inputs.  For us, this means that it is an
417       // intrinsic, has multiple operands, or has other inputs like chain or
418       // glue).
419       if (!NeedCheck) {
420         const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
421         NeedCheck =
422           Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
423           Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
424           Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
425           PInfo.getNumOperands() > 1 ||
426           PInfo.hasProperty(SDNPHasChain) ||
427           PInfo.hasProperty(SDNPInGlue) ||
428           PInfo.hasProperty(SDNPOptInGlue);
429       }
430 
431       if (NeedCheck)
432         AddMatcher(new CheckFoldableChainNodeMatcher());
433     }
434   }
435 
436   // If this node has an output glue and isn't the root, remember it.
437   if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
438       N != Pattern.getSrcPattern()) {
439     // TODO: This redundantly records nodes with both glues and chains.
440 
441     // Record the node and remember it in our chained nodes list.
442     AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
443                                          "' glue output node",
444                                  NextRecordedOperandNo));
445   }
446 
447   // If this node is known to have an input glue or if it *might* have an input
448   // glue, capture it as the glue input of the pattern.
449   if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
450       N->NodeHasProperty(SDNPInGlue, CGP))
451     AddMatcher(new CaptureGlueInputMatcher());
452 
453   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
454     // Get the code suitable for matching this child.  Move to the child, check
455     // it then move back to the parent.
456     AddMatcher(new MoveChildMatcher(OpNo));
457     EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
458     AddMatcher(new MoveParentMatcher());
459   }
460 }
461 
recordUniqueNode(ArrayRef<std::string> Names)462 bool MatcherGen::recordUniqueNode(ArrayRef<std::string> Names) {
463   unsigned Entry = 0;
464   for (const std::string &Name : Names) {
465     unsigned &VarMapEntry = VariableMap[Name];
466     if (!Entry)
467       Entry = VarMapEntry;
468     assert(Entry == VarMapEntry);
469   }
470 
471   bool NewRecord = false;
472   if (Entry == 0) {
473     // If it is a named node, we must emit a 'Record' opcode.
474     std::string WhatFor;
475     for (const std::string &Name : Names) {
476       if (!WhatFor.empty())
477         WhatFor += ',';
478       WhatFor += "$" + Name;
479     }
480     AddMatcher(new RecordMatcher(WhatFor, NextRecordedOperandNo));
481     Entry = ++NextRecordedOperandNo;
482     NewRecord = true;
483   } else {
484     // If we get here, this is a second reference to a specific name.  Since
485     // we already have checked that the first reference is valid, we don't
486     // have to recursively match it, just check that it's the same as the
487     // previously named thing.
488     AddMatcher(new CheckSameMatcher(Entry-1));
489   }
490 
491   for (const std::string &Name : Names)
492     VariableMap[Name] = Entry;
493 
494   return NewRecord;
495 }
496 
EmitMatchCode(const TreePatternNode * N,TreePatternNode * NodeNoTypes)497 void MatcherGen::EmitMatchCode(const TreePatternNode *N,
498                                TreePatternNode *NodeNoTypes) {
499   // If N and NodeNoTypes don't agree on a type, then this is a case where we
500   // need to do a type check.  Emit the check, apply the type to NodeNoTypes and
501   // reinfer any correlated types.
502   SmallVector<unsigned, 2> ResultsToTypeCheck;
503 
504   for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
505     if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
506     NodeNoTypes->setType(i, N->getExtType(i));
507     InferPossibleTypes();
508     ResultsToTypeCheck.push_back(i);
509   }
510 
511   // If this node has a name associated with it, capture it in VariableMap. If
512   // we already saw this in the pattern, emit code to verify dagness.
513   SmallVector<std::string, 4> Names;
514   if (!N->getName().empty())
515     Names.push_back(N->getName());
516 
517   for (const ScopedName &Name : N->getNamesAsPredicateArg()) {
518     Names.push_back(("pred:" + Twine(Name.getScope()) + ":" + Name.getIdentifier()).str());
519   }
520 
521   if (!Names.empty()) {
522     if (!recordUniqueNode(Names))
523       return;
524   }
525 
526   if (N->isLeaf())
527     EmitLeafMatchCode(N);
528   else
529     EmitOperatorMatchCode(N, NodeNoTypes);
530 
531   // If there are node predicates for this node, generate their checks.
532   for (unsigned i = 0, e = N->getPredicateCalls().size(); i != e; ++i) {
533     const TreePredicateCall &Pred = N->getPredicateCalls()[i];
534     SmallVector<unsigned, 4> Operands;
535     if (Pred.Fn.usesOperands()) {
536       TreePattern *TP = Pred.Fn.getOrigPatFragRecord();
537       for (unsigned i = 0; i < TP->getNumArgs(); ++i) {
538         std::string Name =
539             ("pred:" + Twine(Pred.Scope) + ":" + TP->getArgName(i)).str();
540         Operands.push_back(getNamedArgumentSlot(Name));
541       }
542     }
543     AddMatcher(new CheckPredicateMatcher(Pred.Fn, Operands));
544   }
545 
546   for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
547     AddMatcher(new CheckTypeMatcher(N->getSimpleType(ResultsToTypeCheck[i]),
548                                     ResultsToTypeCheck[i]));
549 }
550 
551 /// EmitMatcherCode - Generate the code that matches the predicate of this
552 /// pattern for the specified Variant.  If the variant is invalid this returns
553 /// true and does not generate code, if it is valid, it returns false.
EmitMatcherCode(unsigned Variant)554 bool MatcherGen::EmitMatcherCode(unsigned Variant) {
555   // If the root of the pattern is a ComplexPattern and if it is specified to
556   // match some number of root opcodes, these are considered to be our variants.
557   // Depending on which variant we're generating code for, emit the root opcode
558   // check.
559   if (const ComplexPattern *CP =
560                    Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
561     const std::vector<Record*> &OpNodes = CP->getRootNodes();
562     assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
563     if (Variant >= OpNodes.size()) return true;
564 
565     AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
566   } else {
567     if (Variant != 0) return true;
568   }
569 
570   // Emit the matcher for the pattern structure and types.
571   EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes.get());
572 
573   // If the pattern has a predicate on it (e.g. only enabled when a subtarget
574   // feature is around, do the check).
575   std::string PredicateCheck = Pattern.getPredicateCheck();
576   if (!PredicateCheck.empty())
577     AddMatcher(new CheckPatternPredicateMatcher(PredicateCheck));
578 
579   // Now that we've completed the structural type match, emit any ComplexPattern
580   // checks (e.g. addrmode matches).  We emit this after the structural match
581   // because they are generally more expensive to evaluate and more difficult to
582   // factor.
583   for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
584     auto N = MatchedComplexPatterns[i].first;
585 
586     // Remember where the results of this match get stuck.
587     if (N->isLeaf()) {
588       NamedComplexPatternOperands[N->getName()] = NextRecordedOperandNo + 1;
589     } else {
590       unsigned CurOp = NextRecordedOperandNo;
591       for (unsigned i = 0; i < N->getNumChildren(); ++i) {
592         NamedComplexPatternOperands[N->getChild(i)->getName()] = CurOp + 1;
593         CurOp += N->getChild(i)->getNumMIResults(CGP);
594       }
595     }
596 
597     // Get the slot we recorded the value in from the name on the node.
598     unsigned RecNodeEntry = MatchedComplexPatterns[i].second;
599 
600     const ComplexPattern *CP = N->getComplexPatternInfo(CGP);
601     assert(CP && "Not a valid ComplexPattern!");
602 
603     // Emit a CheckComplexPat operation, which does the match (aborting if it
604     // fails) and pushes the matched operands onto the recorded nodes list.
605     AddMatcher(new CheckComplexPatMatcher(*CP, RecNodeEntry, N->getName(),
606                                           NextRecordedOperandNo));
607 
608     // Record the right number of operands.
609     NextRecordedOperandNo += CP->getNumOperands();
610     if (CP->hasProperty(SDNPHasChain)) {
611       // If the complex pattern has a chain, then we need to keep track of the
612       // fact that we just recorded a chain input.  The chain input will be
613       // matched as the last operand of the predicate if it was successful.
614       ++NextRecordedOperandNo; // Chained node operand.
615 
616       // It is the last operand recorded.
617       assert(NextRecordedOperandNo > 1 &&
618              "Should have recorded input/result chains at least!");
619       MatchedChainNodes.push_back(NextRecordedOperandNo-1);
620     }
621 
622     // TODO: Complex patterns can't have output glues, if they did, we'd want
623     // to record them.
624   }
625 
626   return false;
627 }
628 
629 
630 //===----------------------------------------------------------------------===//
631 // Node Result Generation
632 //===----------------------------------------------------------------------===//
633 
EmitResultOfNamedOperand(const TreePatternNode * N,SmallVectorImpl<unsigned> & ResultOps)634 void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
635                                           SmallVectorImpl<unsigned> &ResultOps){
636   assert(!N->getName().empty() && "Operand not named!");
637 
638   if (unsigned SlotNo = NamedComplexPatternOperands[N->getName()]) {
639     // Complex operands have already been completely selected, just find the
640     // right slot ant add the arguments directly.
641     for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
642       ResultOps.push_back(SlotNo - 1 + i);
643 
644     return;
645   }
646 
647   unsigned SlotNo = getNamedArgumentSlot(N->getName());
648 
649   // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
650   // version of the immediate so that it doesn't get selected due to some other
651   // node use.
652   if (!N->isLeaf()) {
653     StringRef OperatorName = N->getOperator()->getName();
654     if (OperatorName == "imm" || OperatorName == "fpimm") {
655       AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
656       ResultOps.push_back(NextRecordedOperandNo++);
657       return;
658     }
659   }
660 
661   for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
662     ResultOps.push_back(SlotNo + i);
663 }
664 
EmitResultLeafAsOperand(const TreePatternNode * N,SmallVectorImpl<unsigned> & ResultOps)665 void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
666                                          SmallVectorImpl<unsigned> &ResultOps) {
667   assert(N->isLeaf() && "Must be a leaf");
668 
669   if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
670     AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getSimpleType(0)));
671     ResultOps.push_back(NextRecordedOperandNo++);
672     return;
673   }
674 
675   // If this is an explicit register reference, handle it.
676   if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
677     Record *Def = DI->getDef();
678     if (Def->isSubClassOf("Register")) {
679       const CodeGenRegister *Reg =
680         CGP.getTargetInfo().getRegBank().getReg(Def);
681       AddMatcher(new EmitRegisterMatcher(Reg, N->getSimpleType(0)));
682       ResultOps.push_back(NextRecordedOperandNo++);
683       return;
684     }
685 
686     if (Def->getName() == "zero_reg") {
687       AddMatcher(new EmitRegisterMatcher(nullptr, N->getSimpleType(0)));
688       ResultOps.push_back(NextRecordedOperandNo++);
689       return;
690     }
691 
692     if (Def->getName() == "undef_tied_input") {
693       MVT::SimpleValueType ResultVT = N->getSimpleType(0);
694       auto IDOperandNo = NextRecordedOperandNo++;
695       Record *ImpDef = Def->getRecords().getDef("IMPLICIT_DEF");
696       CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(ImpDef);
697       AddMatcher(new EmitNodeMatcher(II, ResultVT, std::nullopt, false, false,
698                                      false, false, -1, IDOperandNo));
699       ResultOps.push_back(IDOperandNo);
700       return;
701     }
702 
703     // Handle a reference to a register class. This is used
704     // in COPY_TO_SUBREG instructions.
705     if (Def->isSubClassOf("RegisterOperand"))
706       Def = Def->getValueAsDef("RegClass");
707     if (Def->isSubClassOf("RegisterClass")) {
708       // If the register class has an enum integer value greater than 127, the
709       // encoding overflows the limit of 7 bits, which precludes the use of
710       // StringIntegerMatcher. In this case, fallback to using IntegerMatcher.
711       const CodeGenRegisterClass &RC =
712           CGP.getTargetInfo().getRegisterClass(Def);
713       if (RC.EnumValue <= 127) {
714         std::string Value = RC.getQualifiedIdName();
715         AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
716         ResultOps.push_back(NextRecordedOperandNo++);
717       } else {
718         AddMatcher(new EmitIntegerMatcher(RC.EnumValue, MVT::i32));
719         ResultOps.push_back(NextRecordedOperandNo++);
720       }
721       return;
722     }
723 
724     // Handle a subregister index. This is used for INSERT_SUBREG etc.
725     if (Def->isSubClassOf("SubRegIndex")) {
726       const CodeGenRegBank &RB = CGP.getTargetInfo().getRegBank();
727       // If we have more than 127 subreg indices the encoding can overflow
728       // 7 bit and we cannot use StringInteger.
729       if (RB.getSubRegIndices().size() > 127) {
730         const CodeGenSubRegIndex *I = RB.findSubRegIdx(Def);
731         assert(I && "Cannot find subreg index by name!");
732         if (I->EnumValue > 127) {
733           AddMatcher(new EmitIntegerMatcher(I->EnumValue, MVT::i32));
734           ResultOps.push_back(NextRecordedOperandNo++);
735           return;
736         }
737       }
738       std::string Value = getQualifiedName(Def);
739       AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
740       ResultOps.push_back(NextRecordedOperandNo++);
741       return;
742     }
743   }
744 
745   errs() << "unhandled leaf node:\n";
746   N->dump();
747 }
748 
749 static bool
mayInstNodeLoadOrStore(const TreePatternNode * N,const CodeGenDAGPatterns & CGP)750 mayInstNodeLoadOrStore(const TreePatternNode *N,
751                        const CodeGenDAGPatterns &CGP) {
752   Record *Op = N->getOperator();
753   const CodeGenTarget &CGT = CGP.getTargetInfo();
754   CodeGenInstruction &II = CGT.getInstruction(Op);
755   return II.mayLoad || II.mayStore;
756 }
757 
758 static unsigned
numNodesThatMayLoadOrStore(const TreePatternNode * N,const CodeGenDAGPatterns & CGP)759 numNodesThatMayLoadOrStore(const TreePatternNode *N,
760                            const CodeGenDAGPatterns &CGP) {
761   if (N->isLeaf())
762     return 0;
763 
764   Record *OpRec = N->getOperator();
765   if (!OpRec->isSubClassOf("Instruction"))
766     return 0;
767 
768   unsigned Count = 0;
769   if (mayInstNodeLoadOrStore(N, CGP))
770     ++Count;
771 
772   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
773     Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
774 
775   return Count;
776 }
777 
778 void MatcherGen::
EmitResultInstructionAsOperand(const TreePatternNode * N,SmallVectorImpl<unsigned> & OutputOps)779 EmitResultInstructionAsOperand(const TreePatternNode *N,
780                                SmallVectorImpl<unsigned> &OutputOps) {
781   Record *Op = N->getOperator();
782   const CodeGenTarget &CGT = CGP.getTargetInfo();
783   CodeGenInstruction &II = CGT.getInstruction(Op);
784   const DAGInstruction &Inst = CGP.getInstruction(Op);
785 
786   bool isRoot = N == Pattern.getDstPattern();
787 
788   // TreeHasOutGlue - True if this tree has glue.
789   bool TreeHasInGlue = false, TreeHasOutGlue = false;
790   if (isRoot) {
791     const TreePatternNode *SrcPat = Pattern.getSrcPattern();
792     TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
793                     SrcPat->TreeHasProperty(SDNPInGlue, CGP);
794 
795     // FIXME2: this is checking the entire pattern, not just the node in
796     // question, doing this just for the root seems like a total hack.
797     TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
798   }
799 
800   // NumResults - This is the number of results produced by the instruction in
801   // the "outs" list.
802   unsigned NumResults = Inst.getNumResults();
803 
804   // Number of operands we know the output instruction must have. If it is
805   // variadic, we could have more operands.
806   unsigned NumFixedOperands = II.Operands.size();
807 
808   SmallVector<unsigned, 8> InstOps;
809 
810   // Loop over all of the fixed operands of the instruction pattern, emitting
811   // code to fill them all in. The node 'N' usually has number children equal to
812   // the number of input operands of the instruction.  However, in cases where
813   // there are predicate operands for an instruction, we need to fill in the
814   // 'execute always' values. Match up the node operands to the instruction
815   // operands to do this.
816   unsigned ChildNo = 0;
817 
818   // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
819   // number of operands at the end of the list which have default values.
820   // Those can come from the pattern if it provides enough arguments, or be
821   // filled in with the default if the pattern hasn't provided them. But any
822   // operand with a default value _before_ the last mandatory one will be
823   // filled in with their defaults unconditionally.
824   unsigned NonOverridableOperands = NumFixedOperands;
825   while (NonOverridableOperands > NumResults &&
826          CGP.operandHasDefault(II.Operands[NonOverridableOperands-1].Rec))
827     --NonOverridableOperands;
828 
829   for (unsigned InstOpNo = NumResults, e = NumFixedOperands;
830        InstOpNo != e; ++InstOpNo) {
831     // Determine what to emit for this operand.
832     Record *OperandNode = II.Operands[InstOpNo].Rec;
833     if (CGP.operandHasDefault(OperandNode) &&
834         (InstOpNo < NonOverridableOperands || ChildNo >= N->getNumChildren())) {
835       // This is a predicate or optional def operand which the pattern has not
836       // overridden, or which we aren't letting it override; emit the 'default
837       // ops' operands.
838       const DAGDefaultOperand &DefaultOp
839         = CGP.getDefaultOperand(OperandNode);
840       for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
841         EmitResultOperand(DefaultOp.DefaultOps[i].get(), InstOps);
842       continue;
843     }
844 
845     // Otherwise this is a normal operand or a predicate operand without
846     // 'execute always'; emit it.
847 
848     // For operands with multiple sub-operands we may need to emit
849     // multiple child patterns to cover them all.  However, ComplexPattern
850     // children may themselves emit multiple MI operands.
851     unsigned NumSubOps = 1;
852     if (OperandNode->isSubClassOf("Operand")) {
853       DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
854       if (unsigned NumArgs = MIOpInfo->getNumArgs())
855         NumSubOps = NumArgs;
856     }
857 
858     unsigned FinalNumOps = InstOps.size() + NumSubOps;
859     while (InstOps.size() < FinalNumOps) {
860       const TreePatternNode *Child = N->getChild(ChildNo);
861       unsigned BeforeAddingNumOps = InstOps.size();
862       EmitResultOperand(Child, InstOps);
863       assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
864 
865       // If the operand is an instruction and it produced multiple results, just
866       // take the first one.
867       if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
868         InstOps.resize(BeforeAddingNumOps+1);
869 
870       ++ChildNo;
871     }
872   }
873 
874   // If this is a variadic output instruction (i.e. REG_SEQUENCE), we can't
875   // expand suboperands, use default operands, or other features determined from
876   // the CodeGenInstruction after the fixed operands, which were handled
877   // above. Emit the remaining instructions implicitly added by the use for
878   // variable_ops.
879   if (II.Operands.isVariadic) {
880     for (unsigned I = ChildNo, E = N->getNumChildren(); I < E; ++I)
881       EmitResultOperand(N->getChild(I), InstOps);
882   }
883 
884   // If this node has input glue or explicitly specified input physregs, we
885   // need to add chained and glued copyfromreg nodes and materialize the glue
886   // input.
887   if (isRoot && !PhysRegInputs.empty()) {
888     // Emit all of the CopyToReg nodes for the input physical registers.  These
889     // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
890     for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i) {
891       const CodeGenRegister *Reg =
892         CGP.getTargetInfo().getRegBank().getReg(PhysRegInputs[i].first);
893       AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
894                                           Reg));
895     }
896 
897     // Even if the node has no other glue inputs, the resultant node must be
898     // glued to the CopyFromReg nodes we just generated.
899     TreeHasInGlue = true;
900   }
901 
902   // Result order: node results, chain, glue
903 
904   // Determine the result types.
905   SmallVector<MVT::SimpleValueType, 4> ResultVTs;
906   for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
907     ResultVTs.push_back(N->getSimpleType(i));
908 
909   // If this is the root instruction of a pattern that has physical registers in
910   // its result pattern, add output VTs for them.  For example, X86 has:
911   //   (set AL, (mul ...))
912   // This also handles implicit results like:
913   //   (implicit EFLAGS)
914   if (isRoot && !Pattern.getDstRegs().empty()) {
915     // If the root came from an implicit def in the instruction handling stuff,
916     // don't re-add it.
917     Record *HandledReg = nullptr;
918     if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
919       HandledReg = II.ImplicitDefs[0];
920 
921     for (Record *Reg : Pattern.getDstRegs()) {
922       if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
923       ResultVTs.push_back(getRegisterValueType(Reg, CGT));
924     }
925   }
926 
927   // If this is the root of the pattern and the pattern we're matching includes
928   // a node that is variadic, mark the generated node as variadic so that it
929   // gets the excess operands from the input DAG.
930   int NumFixedArityOperands = -1;
931   if (isRoot &&
932       Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP))
933     NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
934 
935   // If this is the root node and multiple matched nodes in the input pattern
936   // have MemRefs in them, have the interpreter collect them and plop them onto
937   // this node. If there is just one node with MemRefs, leave them on that node
938   // even if it is not the root.
939   //
940   // FIXME3: This is actively incorrect for result patterns with multiple
941   // memory-referencing instructions.
942   bool PatternHasMemOperands =
943     Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
944 
945   bool NodeHasMemRefs = false;
946   if (PatternHasMemOperands) {
947     unsigned NumNodesThatLoadOrStore =
948       numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
949     bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
950                                    NumNodesThatLoadOrStore == 1;
951     NodeHasMemRefs =
952       NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
953                                              NumNodesThatLoadOrStore != 1));
954   }
955 
956   // Determine whether we need to attach a chain to this node.
957   bool NodeHasChain = false;
958   if (Pattern.getSrcPattern()->TreeHasProperty(SDNPHasChain, CGP)) {
959     // For some instructions, we were able to infer from the pattern whether
960     // they should have a chain.  Otherwise, attach the chain to the root.
961     //
962     // FIXME2: This is extremely dubious for several reasons, not the least of
963     // which it gives special status to instructions with patterns that Pat<>
964     // nodes can't duplicate.
965     if (II.hasChain_Inferred)
966       NodeHasChain = II.hasChain;
967     else
968       NodeHasChain = isRoot;
969     // Instructions which load and store from memory should have a chain,
970     // regardless of whether they happen to have a pattern saying so.
971     if (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad ||
972         II.hasSideEffects)
973       NodeHasChain = true;
974   }
975 
976   assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
977          "Node has no result");
978 
979   AddMatcher(new EmitNodeMatcher(II, ResultVTs, InstOps, NodeHasChain,
980                                  TreeHasInGlue, TreeHasOutGlue, NodeHasMemRefs,
981                                  NumFixedArityOperands, NextRecordedOperandNo));
982 
983   // The non-chain and non-glue results of the newly emitted node get recorded.
984   for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
985     if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
986     OutputOps.push_back(NextRecordedOperandNo++);
987   }
988 }
989 
990 void MatcherGen::
EmitResultSDNodeXFormAsOperand(const TreePatternNode * N,SmallVectorImpl<unsigned> & ResultOps)991 EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
992                                SmallVectorImpl<unsigned> &ResultOps) {
993   assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
994 
995   // Emit the operand.
996   SmallVector<unsigned, 8> InputOps;
997 
998   // FIXME2: Could easily generalize this to support multiple inputs and outputs
999   // to the SDNodeXForm.  For now we just support one input and one output like
1000   // the old instruction selector.
1001   assert(N->getNumChildren() == 1);
1002   EmitResultOperand(N->getChild(0), InputOps);
1003 
1004   // The input currently must have produced exactly one result.
1005   assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
1006 
1007   AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
1008   ResultOps.push_back(NextRecordedOperandNo++);
1009 }
1010 
EmitResultOperand(const TreePatternNode * N,SmallVectorImpl<unsigned> & ResultOps)1011 void MatcherGen::EmitResultOperand(const TreePatternNode *N,
1012                                    SmallVectorImpl<unsigned> &ResultOps) {
1013   // This is something selected from the pattern we matched.
1014   if (!N->getName().empty())
1015     return EmitResultOfNamedOperand(N, ResultOps);
1016 
1017   if (N->isLeaf())
1018     return EmitResultLeafAsOperand(N, ResultOps);
1019 
1020   Record *OpRec = N->getOperator();
1021   if (OpRec->isSubClassOf("Instruction"))
1022     return EmitResultInstructionAsOperand(N, ResultOps);
1023   if (OpRec->isSubClassOf("SDNodeXForm"))
1024     return EmitResultSDNodeXFormAsOperand(N, ResultOps);
1025   errs() << "Unknown result node to emit code for: " << *N << '\n';
1026   PrintFatalError("Unknown node in result pattern!");
1027 }
1028 
EmitResultCode()1029 void MatcherGen::EmitResultCode() {
1030   // Patterns that match nodes with (potentially multiple) chain inputs have to
1031   // merge them together into a token factor.  This informs the generated code
1032   // what all the chained nodes are.
1033   if (!MatchedChainNodes.empty())
1034     AddMatcher(new EmitMergeInputChainsMatcher(MatchedChainNodes));
1035 
1036   // Codegen the root of the result pattern, capturing the resulting values.
1037   SmallVector<unsigned, 8> Ops;
1038   EmitResultOperand(Pattern.getDstPattern(), Ops);
1039 
1040   // At this point, we have however many values the result pattern produces.
1041   // However, the input pattern might not need all of these.  If there are
1042   // excess values at the end (such as implicit defs of condition codes etc)
1043   // just lop them off.  This doesn't need to worry about glue or chains, just
1044   // explicit results.
1045   //
1046   unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
1047 
1048   // If the pattern also has (implicit) results, count them as well.
1049   if (!Pattern.getDstRegs().empty()) {
1050     // If the root came from an implicit def in the instruction handling stuff,
1051     // don't re-add it.
1052     Record *HandledReg = nullptr;
1053     const TreePatternNode *DstPat = Pattern.getDstPattern();
1054     if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
1055       const CodeGenTarget &CGT = CGP.getTargetInfo();
1056       CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
1057 
1058       if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
1059         HandledReg = II.ImplicitDefs[0];
1060     }
1061 
1062     for (Record *Reg : Pattern.getDstRegs()) {
1063       if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
1064       ++NumSrcResults;
1065     }
1066   }
1067 
1068   SmallVector<unsigned, 8> Results(Ops);
1069 
1070   // Apply result permutation.
1071   for (unsigned ResNo = 0; ResNo < Pattern.getDstPattern()->getNumResults();
1072        ++ResNo) {
1073     Results[ResNo] = Ops[Pattern.getDstPattern()->getResultIndex(ResNo)];
1074   }
1075 
1076   Results.resize(NumSrcResults);
1077   AddMatcher(new CompleteMatchMatcher(Results, Pattern));
1078 }
1079 
1080 
1081 /// ConvertPatternToMatcher - Create the matcher for the specified pattern with
1082 /// the specified variant.  If the variant number is invalid, this returns null.
ConvertPatternToMatcher(const PatternToMatch & Pattern,unsigned Variant,const CodeGenDAGPatterns & CGP)1083 Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
1084                                        unsigned Variant,
1085                                        const CodeGenDAGPatterns &CGP) {
1086   MatcherGen Gen(Pattern, CGP);
1087 
1088   // Generate the code for the matcher.
1089   if (Gen.EmitMatcherCode(Variant))
1090     return nullptr;
1091 
1092   // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
1093   // FIXME2: Split result code out to another table, and make the matcher end
1094   // with an "Emit <index>" command.  This allows result generation stuff to be
1095   // shared and factored?
1096 
1097   // If the match succeeds, then we generate Pattern.
1098   Gen.EmitResultCode();
1099 
1100   // Unconditional match.
1101   return Gen.GetMatcher();
1102 }
1103