introduce a new ResultVal and start keeping track of temporary values.
[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 "Record.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringMap.h"
15 using namespace llvm;
16
17 namespace {
18   /// ResultVal - When generating new nodes for the result of a pattern match,
19   /// this value is used to represent an input to the node.  Result values can
20   /// either be an input that is 'recorded' in the RecordedNodes array by the
21   /// matcher or it can be a temporary value created by the emitter for things
22   /// like constants.
23   class ResultVal {
24     unsigned Number : 30;
25     enum {
26       Recorded, Temporary
27     } Kind : 2; // True if temporary, false if recorded.
28   public:
29     static ResultVal getRecorded(unsigned N) {
30       ResultVal R;
31       R.Number = N;
32       R.Kind = Recorded;
33       return R;
34     }
35     
36     static ResultVal getTemp(unsigned N) {
37       ResultVal R;
38       R.Number = N;
39       R.Kind = Temporary;
40       return R;
41     }
42
43     bool isTemp() const { return Kind == Temporary; }
44     bool isRecorded() const { return Kind == Recorded; }
45     
46     unsigned getTempNo() const {
47       assert(isTemp());
48       return Number;
49     }
50
51     unsigned getRecordedNo() const {
52       assert(isRecorded());
53       return Number;
54     }
55   };
56   
57   
58   class MatcherGen {
59     const PatternToMatch &Pattern;
60     const CodeGenDAGPatterns &CGP;
61     
62     /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
63     /// out with all of the types removed.  This allows us to insert type checks
64     /// as we scan the tree.
65     TreePatternNode *PatWithNoTypes;
66     
67     /// VariableMap - A map from variable names ('$dst') to the recorded operand
68     /// number that they were captured as.  These are biased by 1 to make
69     /// insertion easier.
70     StringMap<unsigned> VariableMap;
71     
72     /// NextRecordedOperandNo - As we emit opcodes to record matched values in
73     /// the RecordedNodes array, this keeps track of which slot will be next to
74     /// record into.
75     unsigned NextRecordedOperandNo;
76     
77     /// NextTemporary - As we generate code, this indicates the next temporary
78     /// ID that will be generated.
79     unsigned NextTemporary;
80     
81     /// InputChains - This maintains the position in the recorded nodes array of
82     /// all of the recorded input chains.
83     SmallVector<unsigned, 2> InputChains;
84     
85     /// Matcher - This is the top level of the generated matcher, the result.
86     MatcherNode *Matcher;
87     
88     /// CurPredicate - As we emit matcher nodes, this points to the latest check
89     /// which should have future checks stuck into its Next position.
90     MatcherNode *CurPredicate;
91   public:
92     MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
93     
94     ~MatcherGen() {
95       delete PatWithNoTypes;
96     }
97     
98     void EmitMatcherCode();
99     void EmitResultCode();
100     
101     MatcherNode *GetMatcher() const { return Matcher; }
102     MatcherNode *GetCurPredicate() const { return CurPredicate; }
103   private:
104     void AddMatcherNode(MatcherNode *NewNode);
105     void InferPossibleTypes();
106     
107     // Matcher Generation.
108     void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
109     void EmitLeafMatchCode(const TreePatternNode *N);
110     void EmitOperatorMatchCode(const TreePatternNode *N,
111                                TreePatternNode *NodeNoTypes);
112     
113     // Result Code Generation.
114     void EmitResultOperand(const TreePatternNode *N,
115                            SmallVectorImpl<ResultVal> &ResultOps);
116     void EmitResultLeafAsOperand(const TreePatternNode *N,
117                                  SmallVectorImpl<ResultVal> &ResultOps);
118     void EmitResultInstructionAsOperand(const TreePatternNode *N,
119                                         SmallVectorImpl<ResultVal> &ResultOps);
120   };
121   
122 } // end anon namespace.
123
124 MatcherGen::MatcherGen(const PatternToMatch &pattern,
125                        const CodeGenDAGPatterns &cgp)
126 : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0), NextTemporary(0),
127   Matcher(0), CurPredicate(0) {
128   // We need to produce the matcher tree for the patterns source pattern.  To do
129   // this we need to match the structure as well as the types.  To do the type
130   // matching, we want to figure out the fewest number of type checks we need to
131   // emit.  For example, if there is only one integer type supported by a
132   // target, there should be no type comparisons at all for integer patterns!
133   //
134   // To figure out the fewest number of type checks needed, clone the pattern,
135   // remove the types, then perform type inference on the pattern as a whole.
136   // If there are unresolved types, emit an explicit check for those types,
137   // apply the type to the tree, then rerun type inference.  Iterate until all
138   // types are resolved.
139   //
140   PatWithNoTypes = Pattern.getSrcPattern()->clone();
141   PatWithNoTypes->RemoveAllTypes();
142     
143   // If there are types that are manifestly known, infer them.
144   InferPossibleTypes();
145 }
146
147 /// InferPossibleTypes - As we emit the pattern, we end up generating type
148 /// checks and applying them to the 'PatWithNoTypes' tree.  As we do this, we
149 /// want to propagate implied types as far throughout the tree as possible so
150 /// that we avoid doing redundant type checks.  This does the type propagation.
151 void MatcherGen::InferPossibleTypes() {
152   // TP - Get *SOME* tree pattern, we don't care which.  It is only used for
153   // diagnostics, which we know are impossible at this point.
154   TreePattern &TP = *CGP.pf_begin()->second;
155   
156   try {
157     bool MadeChange = true;
158     while (MadeChange)
159       MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
160                                                 true/*Ignore reg constraints*/);
161   } catch (...) {
162     errs() << "Type constraint application shouldn't fail!";
163     abort();
164   }
165 }
166
167
168 /// AddMatcherNode - Add a matcher node to the current graph we're building. 
169 void MatcherGen::AddMatcherNode(MatcherNode *NewNode) {
170   if (CurPredicate != 0)
171     CurPredicate->setNext(NewNode);
172   else
173     Matcher = NewNode;
174   CurPredicate = NewNode;
175 }
176
177
178 //===----------------------------------------------------------------------===//
179 // Pattern Match Generation
180 //===----------------------------------------------------------------------===//
181
182 /// EmitLeafMatchCode - Generate matching code for leaf nodes.
183 void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
184   assert(N->isLeaf() && "Not a leaf?");
185   // Direct match against an integer constant.
186   if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
187     return AddMatcherNode(new CheckIntegerMatcherNode(II->getValue()));
188   
189   DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
190   if (DI == 0) {
191     errs() << "Unknown leaf kind: " << *DI << "\n";
192     abort();
193   }
194   
195   Record *LeafRec = DI->getDef();
196   if (// Handle register references.  Nothing to do here, they always match.
197       LeafRec->isSubClassOf("RegisterClass") || 
198       LeafRec->isSubClassOf("PointerLikeRegClass") ||
199       LeafRec->isSubClassOf("Register") ||
200       // Place holder for SRCVALUE nodes. Nothing to do here.
201       LeafRec->getName() == "srcvalue")
202     return;
203   
204   if (LeafRec->isSubClassOf("ValueType"))
205     return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
206   
207   if (LeafRec->isSubClassOf("CondCode"))
208     return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
209   
210   if (LeafRec->isSubClassOf("ComplexPattern")) {
211     // We can't model ComplexPattern uses that don't have their name taken yet.
212     // The OPC_CheckComplexPattern operation implicitly records the results.
213     if (N->getName().empty()) {
214       errs() << "We expect complex pattern uses to have names: " << *N << "\n";
215       exit(1);
216     }
217     
218     // Handle complex pattern.
219     const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
220     AddMatcherNode(new CheckComplexPatMatcherNode(CP));
221     
222     // If the complex pattern has a chain, then we need to keep track of the
223     // fact that we just recorded a chain input.  The chain input will be
224     // matched as the last operand of the predicate if it was successful.
225     if (CP.hasProperty(SDNPHasChain)) {
226       // It is the last operand recorded.
227       assert(NextRecordedOperandNo > 1 &&
228              "Should have recorded input/result chains at least!");
229       InputChains.push_back(NextRecordedOperandNo-1);
230
231       // IF we need to check chains, do so, see comment for
232       // "NodeHasProperty(SDNPHasChain" below.
233       if (InputChains.size() > 1) {
234         // FIXME: This is broken, we should eliminate this nonsense completely,
235         // but we want to produce the same selections that the old matcher does
236         // for now.
237         unsigned PrevOp = InputChains[InputChains.size()-2];
238         AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
239       }
240     }
241     return;
242   }
243   
244   errs() << "Unknown leaf kind: " << *N << "\n";
245   abort();
246 }
247
248 void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
249                                        TreePatternNode *NodeNoTypes) {
250   assert(!N->isLeaf() && "Not an operator?");
251   const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
252   
253   // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
254   // a constant without a predicate fn that has more that one bit set, handle
255   // this as a special case.  This is usually for targets that have special
256   // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
257   // handling stuff).  Using these instructions is often far more efficient
258   // than materializing the constant.  Unfortunately, both the instcombiner
259   // and the dag combiner can often infer that bits are dead, and thus drop
260   // them from the mask in the dag.  For example, it might turn 'AND X, 255'
261   // into 'AND X, 254' if it knows the low bit is set.  Emit code that checks
262   // to handle this.
263   if ((N->getOperator()->getName() == "and" || 
264        N->getOperator()->getName() == "or") &&
265       N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty()) {
266     if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
267       if (!isPowerOf2_32(II->getValue())) {  // Don't bother with single bits.
268         if (N->getOperator()->getName() == "and")
269           AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
270         else
271           AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
272
273         // Match the LHS of the AND as appropriate.
274         AddMatcherNode(new MoveChildMatcherNode(0));
275         EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
276         AddMatcherNode(new MoveParentMatcherNode());
277         return;
278       }
279     }
280   }
281   
282   // Check that the current opcode lines up.
283   AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
284   
285   // If this node has a chain, then the chain is operand #0 is the SDNode, and
286   // the child numbers of the node are all offset by one.
287   unsigned OpNo = 0;
288   if (N->NodeHasProperty(SDNPHasChain, CGP)) {
289     // Record the input chain, which is always input #0 of the SDNode.
290     AddMatcherNode(new MoveChildMatcherNode(0));
291     AddMatcherNode(new RecordMatcherNode("'" + N->getOperator()->getName() +
292                                          "' input chain"));
293     
294     // Remember all of the input chains our pattern will match.
295     InputChains.push_back(NextRecordedOperandNo);
296     ++NextRecordedOperandNo;
297     AddMatcherNode(new MoveParentMatcherNode());
298     
299     // If this is the second (e.g. indbr(load) or store(add(load))) or third
300     // input chain (e.g. (store (add (load, load))) from msp430) we need to make
301     // sure that folding the chain won't induce cycles in the DAG.  This could
302     // happen if there were an intermediate node between the indbr and load, for
303     // example.
304     if (InputChains.size() > 1) {
305       // FIXME: This is broken, we should eliminate this nonsense completely,
306       // but we want to produce the same selections that the old matcher does
307       // for now.
308       unsigned PrevOp = InputChains[InputChains.size()-2];
309       AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
310     }
311     
312     // Don't look at the input chain when matching the tree pattern to the
313     // SDNode.
314     OpNo = 1;
315
316     // If this node is not the root and the subtree underneath it produces a
317     // chain, then the result of matching the node is also produce a chain.
318     // Beyond that, this means that we're also folding (at least) the root node
319     // into the node that produce the chain (for example, matching
320     // "(add reg, (load ptr))" as a add_with_memory on X86).  This is
321     // problematic, if the 'reg' node also uses the load (say, its chain).
322     // Graphically:
323     //
324     //         [LD]
325     //         ^  ^
326     //         |  \                              DAG's like cheese.
327     //        /    |
328     //       /    [YY]
329     //       |     ^
330     //      [XX]--/
331     //
332     // It would be invalid to fold XX and LD.  In this case, folding the two
333     // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
334     // To prevent this, we emit a dynamic check for legality before allowing
335     // this to be folded.
336     //
337     const TreePatternNode *Root = Pattern.getSrcPattern();
338     if (N != Root) {                             // Not the root of the pattern.
339       // If there is a node between the root and this node, then we definitely
340       // need to emit the check.
341       bool NeedCheck = !Root->hasChild(N);
342       
343       // If it *is* an immediate child of the root, we can still need a check if
344       // the root SDNode has multiple inputs.  For us, this means that it is an
345       // intrinsic, has multiple operands, or has other inputs like chain or
346       // flag).
347       if (!NeedCheck) {
348         const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
349         NeedCheck =
350           Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
351           Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
352           Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
353           PInfo.getNumOperands() > 1 ||
354           PInfo.hasProperty(SDNPHasChain) ||
355           PInfo.hasProperty(SDNPInFlag) ||
356           PInfo.hasProperty(SDNPOptInFlag);
357       }
358       
359       if (NeedCheck)
360         AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
361     }
362   }
363       
364   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
365     // Get the code suitable for matching this child.  Move to the child, check
366     // it then move back to the parent.
367     AddMatcherNode(new MoveChildMatcherNode(OpNo));
368     EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
369     AddMatcherNode(new MoveParentMatcherNode());
370   }
371 }
372
373
374 void MatcherGen::EmitMatchCode(const TreePatternNode *N,
375                                TreePatternNode *NodeNoTypes) {
376   // If N and NodeNoTypes don't agree on a type, then this is a case where we
377   // need to do a type check.  Emit the check, apply the tyep to NodeNoTypes and
378   // reinfer any correlated types.
379   if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
380     AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
381     NodeNoTypes->setTypes(N->getExtTypes());
382     InferPossibleTypes();
383   }
384   
385   // If this node has a name associated with it, capture it in VariableMap. If
386   // we already saw this in the pattern, emit code to verify dagness.
387   if (!N->getName().empty()) {
388     unsigned &VarMapEntry = VariableMap[N->getName()];
389     if (VarMapEntry == 0) {
390       VarMapEntry = NextRecordedOperandNo+1;
391       
392       unsigned NumRecorded;
393       
394       // If this is a complex pattern, the match operation for it will
395       // implicitly record all of the outputs of it (which may be more than
396       // one).
397       if (const ComplexPattern *AM = N->getComplexPatternInfo(CGP)) {
398         // Record the right number of operands.
399         NumRecorded = AM->getNumOperands()-1;
400         
401         if (AM->hasProperty(SDNPHasChain))
402           NumRecorded += 2; // Input and output chains.
403       } else {
404         // If it is a normal named node, we must emit a 'Record' opcode.
405         AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
406         NumRecorded = 1;
407       }
408       NextRecordedOperandNo += NumRecorded;
409       
410     } else {
411       // If we get here, this is a second reference to a specific name.  Since
412       // we already have checked that the first reference is valid, we don't
413       // have to recursively match it, just check that it's the same as the
414       // previously named thing.
415       AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
416       return;
417     }
418   }
419   
420   // If there are node predicates for this node, generate their checks.
421   for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
422     AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
423
424   if (N->isLeaf())
425     EmitLeafMatchCode(N);
426   else
427     EmitOperatorMatchCode(N, NodeNoTypes);
428 }
429
430 void MatcherGen::EmitMatcherCode() {
431   // If the pattern has a predicate on it (e.g. only enabled when a subtarget
432   // feature is around, do the check).
433   if (!Pattern.getPredicateCheck().empty())
434     AddMatcherNode(new 
435                  CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
436   
437   // Emit the matcher for the pattern structure and types.
438   EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
439 }
440
441
442 //===----------------------------------------------------------------------===//
443 // Node Result Generation
444 //===----------------------------------------------------------------------===//
445
446 void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
447                                          SmallVectorImpl<ResultVal> &ResultOps){
448   assert(N->isLeaf() && "Must be a leaf");
449   
450   if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
451     AddMatcherNode(new EmitIntegerMatcherNode(II->getValue(),N->getTypeNum(0)));
452     ResultOps.push_back(ResultVal::getTemp(NextTemporary++));
453     return;
454   }
455   
456   // If this is an explicit register reference, handle it.
457   if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
458     if (DI->getDef()->isSubClassOf("Register")) {
459       AddMatcherNode(new EmitRegisterMatcherNode(DI->getDef(),
460                                                  N->getTypeNum(0)));
461       ResultOps.push_back(ResultVal::getTemp(NextTemporary++));
462       return;
463     }
464     
465     if (DI->getDef()->getName() == "zero_reg") {
466       AddMatcherNode(new EmitRegisterMatcherNode(0, N->getTypeNum(0)));
467       ResultOps.push_back(ResultVal::getTemp(NextTemporary++));
468       return;
469     }
470     
471 #if 0
472     if (DI->getDef()->isSubClassOf("RegisterClass")) {
473       // Handle a reference to a register class. This is used
474       // in COPY_TO_SUBREG instructions.
475       // FIXME: Implement.
476     }
477 #endif
478   }
479   
480   errs() << "unhandled leaf node: \n";
481   N->dump();
482 }
483
484 void MatcherGen::EmitResultInstructionAsOperand(const TreePatternNode *N,
485                                          SmallVectorImpl<ResultVal> &ResultOps){
486   Record *Op = N->getOperator();
487   const CodeGenTarget &CGT = CGP.getTargetInfo();
488   CodeGenInstruction &II = CGT.getInstruction(Op->getName());
489   const DAGInstruction &Inst = CGP.getInstruction(Op);
490   
491   // FIXME: Handle (set x, (foo))
492   
493   if (II.isVariadic) // FIXME: Handle variadic instructions.
494     return AddMatcherNode(new EmitNodeMatcherNode(Pattern));
495     
496   // FIXME: Handle OptInFlag, HasInFlag, HasOutFlag
497   // FIXME: Handle Chains.
498   unsigned NumResults = Inst.getNumResults();    
499
500   
501   // Loop over all of the operands of the instruction pattern, emitting code
502   // to fill them all in.  The node 'N' usually has number children equal to
503   // the number of input operands of the instruction.  However, in cases
504   // where there are predicate operands for an instruction, we need to fill
505   // in the 'execute always' values.  Match up the node operands to the
506   // instruction operands to do this.
507   SmallVector<ResultVal, 8> Ops;
508   for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.OperandList.size();
509        InstOpNo != e; ++InstOpNo) {
510     
511     // Determine what to emit for this operand.
512     Record *OperandNode = II.OperandList[InstOpNo].Rec;
513     if ((OperandNode->isSubClassOf("PredicateOperand") ||
514          OperandNode->isSubClassOf("OptionalDefOperand")) &&
515         !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
516       // This is a predicate or optional def operand; emit the
517       // 'default ops' operands.
518       const DAGDefaultOperand &DefaultOp =
519         CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
520       for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
521         EmitResultOperand(DefaultOp.DefaultOps[i], Ops);
522       continue;
523     }
524     
525     // Otherwise this is a normal operand or a predicate operand without
526     // 'execute always'; emit it.
527     EmitResultOperand(N->getChild(ChildNo), Ops);
528     ++ChildNo;
529   }
530   
531   // FIXME: Chain.
532   // FIXME: Flag
533   
534   
535   
536   return;
537 }
538
539 void MatcherGen::EmitResultOperand(const TreePatternNode *N,
540                                    SmallVectorImpl<ResultVal> &ResultOps) {
541   // This is something selected from the pattern we matched.
542   if (!N->getName().empty()) {
543     //errs() << "unhandled named node: \n";
544     //N->dump();
545     return;
546   }
547
548   if (N->isLeaf())
549     return EmitResultLeafAsOperand(N, ResultOps);
550
551   Record *OpRec = N->getOperator();
552   if (OpRec->isSubClassOf("Instruction"))
553     return EmitResultInstructionAsOperand(N, ResultOps);
554   if (OpRec->isSubClassOf("SDNodeXForm"))
555     // FIXME: implement.
556     return;
557   errs() << "Unknown result node to emit code for: " << *N << '\n';
558   throw std::string("Unknown node in result pattern!");
559 }
560
561 void MatcherGen::EmitResultCode() {
562   // FIXME: Handle Ops.
563   // FIXME: Ops should be vector of "ResultValue> which is either an index into
564   // the results vector is is a temp result.
565   SmallVector<ResultVal, 8> Ops;
566   EmitResultOperand(Pattern.getDstPattern(), Ops);
567   //AddMatcherNode(new EmitNodeMatcherNode(Pattern));
568 }
569
570
571 MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
572                                            const CodeGenDAGPatterns &CGP) {
573   MatcherGen Gen(Pattern, CGP);
574
575   // Generate the code for the matcher.
576   Gen.EmitMatcherCode();
577   
578   // If the match succeeds, then we generate Pattern.
579   Gen.EmitResultCode();
580
581   // Unconditional match.
582   return Gen.GetMatcher();
583 }
584
585
586