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