1 //===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "DAGISelMatcher.h"
11 #include "CodeGenDAGPatterns.h"
13 #include "llvm/ADT/StringMap.h"
18 const PatternToMatch &Pattern;
19 const CodeGenDAGPatterns &CGP;
21 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
22 /// out with all of the types removed. This allows us to insert type checks
23 /// as we scan the tree.
24 TreePatternNode *PatWithNoTypes;
26 /// VariableMap - A map from variable names ('$dst') to the recorded operand
27 /// number that they were captured as. These are biased by 1 to make
29 StringMap<unsigned> VariableMap;
30 unsigned NextRecordedOperandNo;
32 MatcherNodeWithChild *Matcher;
33 MatcherNodeWithChild *CurPredicate;
35 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
38 delete PatWithNoTypes;
41 void EmitMatcherCode();
43 MatcherNodeWithChild *GetMatcher() const { return Matcher; }
44 MatcherNodeWithChild *GetCurPredicate() const { return CurPredicate; }
46 void AddMatcherNode(MatcherNodeWithChild *NewNode);
47 void InferPossibleTypes();
48 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
49 void EmitLeafMatchCode(const TreePatternNode *N);
50 void EmitOperatorMatchCode(const TreePatternNode *N,
51 TreePatternNode *NodeNoTypes);
54 } // end anon namespace.
56 MatcherGen::MatcherGen(const PatternToMatch &pattern,
57 const CodeGenDAGPatterns &cgp)
58 : Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
59 Matcher(0), CurPredicate(0) {
60 // We need to produce the matcher tree for the patterns source pattern. To do
61 // this we need to match the structure as well as the types. To do the type
62 // matching, we want to figure out the fewest number of type checks we need to
63 // emit. For example, if there is only one integer type supported by a
64 // target, there should be no type comparisons at all for integer patterns!
66 // To figure out the fewest number of type checks needed, clone the pattern,
67 // remove the types, then perform type inference on the pattern as a whole.
68 // If there are unresolved types, emit an explicit check for those types,
69 // apply the type to the tree, then rerun type inference. Iterate until all
70 // types are resolved.
72 PatWithNoTypes = Pattern.getSrcPattern()->clone();
73 PatWithNoTypes->RemoveAllTypes();
75 // If there are types that are manifestly known, infer them.
79 /// InferPossibleTypes - As we emit the pattern, we end up generating type
80 /// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
81 /// want to propagate implied types as far throughout the tree as possible so
82 /// that we avoid doing redundant type checks. This does the type propagation.
83 void MatcherGen::InferPossibleTypes() {
84 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
85 // diagnostics, which we know are impossible at this point.
86 TreePattern &TP = *CGP.pf_begin()->second;
89 bool MadeChange = true;
91 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
92 true/*Ignore reg constraints*/);
94 errs() << "Type constraint application shouldn't fail!";
100 /// AddMatcherNode - Add a matcher node to the current graph we're building.
101 void MatcherGen::AddMatcherNode(MatcherNodeWithChild *NewNode) {
102 if (CurPredicate != 0)
103 CurPredicate->setChild(NewNode);
106 CurPredicate = NewNode;
111 /// EmitLeafMatchCode - Generate matching code for leaf nodes.
112 void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
113 assert(N->isLeaf() && "Not a leaf?");
114 // Direct match against an integer constant.
115 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
116 return AddMatcherNode(new CheckIntegerMatcherNode(II->getValue()));
118 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
120 errs() << "Unknown leaf kind: " << *DI << "\n";
124 Record *LeafRec = DI->getDef();
125 if (// Handle register references. Nothing to do here, they always match.
126 LeafRec->isSubClassOf("RegisterClass") ||
127 LeafRec->isSubClassOf("PointerLikeRegClass") ||
128 LeafRec->isSubClassOf("Register") ||
129 // Place holder for SRCVALUE nodes. Nothing to do here.
130 LeafRec->getName() == "srcvalue")
133 if (LeafRec->isSubClassOf("ValueType"))
134 return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
136 if (LeafRec->isSubClassOf("CondCode"))
137 return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
139 if (LeafRec->isSubClassOf("ComplexPattern")) {
140 // We can't model ComplexPattern uses that don't have their name taken yet.
141 // The OPC_CheckComplexPattern operation implicitly records the results.
142 if (N->getName().empty()) {
143 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
147 // Handle complex pattern.
148 const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
149 return AddMatcherNode(new CheckComplexPatMatcherNode(CP));
152 errs() << "Unknown leaf kind: " << *N << "\n";
156 void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
157 TreePatternNode *NodeNoTypes) {
158 assert(!N->isLeaf() && "Not an operator?");
159 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
161 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
162 // a constant without a predicate fn that has more that one bit set, handle
163 // this as a special case. This is usually for targets that have special
164 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
165 // handling stuff). Using these instructions is often far more efficient
166 // than materializing the constant. Unfortunately, both the instcombiner
167 // and the dag combiner can often infer that bits are dead, and thus drop
168 // them from the mask in the dag. For example, it might turn 'AND X, 255'
169 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
171 if ((N->getOperator()->getName() == "and" ||
172 N->getOperator()->getName() == "or") &&
173 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty()) {
174 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
175 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
176 if (N->getOperator()->getName() == "and")
177 AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
179 AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
181 // Match the LHS of the AND as appropriate.
182 AddMatcherNode(new MoveChildMatcherNode(0));
183 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
184 AddMatcherNode(new MoveParentMatcherNode());
190 // Check that the current opcode lines up.
191 AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
193 // If this node has a chain, then the chain is operand #0 is the SDNode, and
194 // the child numbers of the node are all offset by one.
196 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
197 // Record the input chain, which is always input #0 of the SDNode.
198 AddMatcherNode(new MoveChildMatcherNode(0));
199 ++NextRecordedOperandNo;
200 AddMatcherNode(new RecordMatcherNode("'" + N->getOperator()->getName() +
202 AddMatcherNode(new MoveParentMatcherNode());
204 // Don't look at the input chain when matching the tree pattern to the
208 // If this node is not the root and the subtree underneath it produces a
209 // chain, then the result of matching the node is also produce a chain.
210 // Beyond that, this means that we're also folding (at least) the root node
211 // into the node that produce the chain (for example, matching
212 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
213 // problematic, if the 'reg' node also uses the load (say, its chain).
218 // | \ DAG's like cheese.
224 // It would be invalid to fold XX and LD. In this case, folding the two
225 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
226 // To prevent this, we emit a dynamic check for legality before allowing
227 // this to be folded.
229 const TreePatternNode *Root = Pattern.getSrcPattern();
230 if (N != Root) { // Not the root of the pattern.
231 // If there is a node between the root and this node, then we definitely
232 // need to emit the check.
233 bool NeedCheck = !Root->hasChild(N);
235 // If it *is* an immediate child of the root, we can still need a check if
236 // the root SDNode has multiple inputs. For us, this means that it is an
237 // intrinsic, has multiple operands, or has other inputs like chain or
240 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
242 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
243 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
244 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
245 PInfo.getNumOperands() > 1 ||
246 PInfo.hasProperty(SDNPHasChain) ||
247 PInfo.hasProperty(SDNPInFlag) ||
248 PInfo.hasProperty(SDNPOptInFlag);
252 AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
256 // FIXME: Need to generate IsChainCompatible checks.
258 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
259 // Get the code suitable for matching this child. Move to the child, check
260 // it then move back to the parent.
261 AddMatcherNode(new MoveChildMatcherNode(OpNo));
262 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
263 AddMatcherNode(new MoveParentMatcherNode());
268 void MatcherGen::EmitMatchCode(const TreePatternNode *N,
269 TreePatternNode *NodeNoTypes) {
270 // If N and NodeNoTypes don't agree on a type, then this is a case where we
271 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
272 // reinfer any correlated types.
273 if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
274 AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
275 NodeNoTypes->setTypes(N->getExtTypes());
276 InferPossibleTypes();
279 // If this node has a name associated with it, capture it in VariableMap. If
280 // we already saw this in the pattern, emit code to verify dagness.
281 if (!N->getName().empty()) {
282 unsigned &VarMapEntry = VariableMap[N->getName()];
283 if (VarMapEntry == 0) {
284 VarMapEntry = NextRecordedOperandNo+1;
286 unsigned NumRecorded;
288 // If this is a complex pattern, the match operation for it will
289 // implicitly record all of the outputs of it (which may be more than
291 if (const ComplexPattern *AM = N->getComplexPatternInfo(CGP)) {
292 // Record the right number of operands.
293 NumRecorded = AM->getNumOperands()-1;
295 if (AM->hasProperty(SDNPHasChain))
296 NumRecorded += 2; // Input and output chains.
298 // If it is a normal named node, we must emit a 'Record' opcode.
299 AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
302 NextRecordedOperandNo += NumRecorded;
305 // If we get here, this is a second reference to a specific name. Since
306 // we already have checked that the first reference is valid, we don't
307 // have to recursively match it, just check that it's the same as the
308 // previously named thing.
309 AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
314 // If there are node predicates for this node, generate their checks.
315 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
316 AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
319 EmitLeafMatchCode(N);
321 EmitOperatorMatchCode(N, NodeNoTypes);
324 void MatcherGen::EmitMatcherCode() {
325 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
326 // feature is around, do the check).
327 if (!Pattern.getPredicateCheck().empty())
329 CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
331 // Emit the matcher for the pattern structure and types.
332 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
336 MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
337 const CodeGenDAGPatterns &CGP) {
338 MatcherGen Gen(Pattern, CGP);
340 // Generate the code for the matcher.
341 Gen.EmitMatcherCode();
343 // If the match succeeds, then we generate Pattern.
344 EmitNodeMatcherNode *Result = new EmitNodeMatcherNode(Pattern);
346 // Link it into the pattern.
347 if (MatcherNodeWithChild *Pred = Gen.GetCurPredicate()) {
348 Pred->setChild(Result);
349 return Gen.GetMatcher();
352 // Unconditional match.