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