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