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