blob: e2ffb8e7171dac7a66cfea42797e1ac0bf26d8ce [file] [log] [blame]
Chris Lattnerda272d12010-02-15 08:04:42 +00001//===- 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"
Chris Lattner785d16f2010-02-17 02:16:19 +000013#include "llvm/ADT/SmallVector.h"
Chris Lattnerda272d12010-02-15 08:04:42 +000014#include "llvm/ADT/StringMap.h"
15using namespace llvm;
16
17namespace {
18 class MatcherGen {
19 const PatternToMatch &Pattern;
20 const CodeGenDAGPatterns &CGP;
21
22 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
23 /// out with all of the types removed. This allows us to insert type checks
24 /// as we scan the tree.
25 TreePatternNode *PatWithNoTypes;
26
27 /// VariableMap - A map from variable names ('$dst') to the recorded operand
28 /// number that they were captured as. These are biased by 1 to make
29 /// insertion easier.
30 StringMap<unsigned> VariableMap;
31 unsigned NextRecordedOperandNo;
32
Chris Lattner785d16f2010-02-17 02:16:19 +000033 /// InputChains - This maintains the position in the recorded nodes array of
34 /// all of the recorded input chains.
35 SmallVector<unsigned, 2> InputChains;
36
37 /// Matcher - This is the top level of the generated matcher, the result.
Chris Lattnerda272d12010-02-15 08:04:42 +000038 MatcherNodeWithChild *Matcher;
Chris Lattner785d16f2010-02-17 02:16:19 +000039
40 /// CurPredicate - As we emit matcher nodes, this points to the latest check
41 /// which should have future checks stuck into its child position.
Chris Lattnerda272d12010-02-15 08:04:42 +000042 MatcherNodeWithChild *CurPredicate;
43 public:
44 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
45
46 ~MatcherGen() {
47 delete PatWithNoTypes;
48 }
49
50 void EmitMatcherCode();
51
52 MatcherNodeWithChild *GetMatcher() const { return Matcher; }
53 MatcherNodeWithChild *GetCurPredicate() const { return CurPredicate; }
54 private:
55 void AddMatcherNode(MatcherNodeWithChild *NewNode);
56 void InferPossibleTypes();
57 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
58 void EmitLeafMatchCode(const TreePatternNode *N);
59 void EmitOperatorMatchCode(const TreePatternNode *N,
60 TreePatternNode *NodeNoTypes);
61 };
62
63} // end anon namespace.
64
65MatcherGen::MatcherGen(const PatternToMatch &pattern,
66 const CodeGenDAGPatterns &cgp)
67: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
68 Matcher(0), CurPredicate(0) {
69 // We need to produce the matcher tree for the patterns source pattern. To do
70 // this we need to match the structure as well as the types. To do the type
71 // matching, we want to figure out the fewest number of type checks we need to
72 // emit. For example, if there is only one integer type supported by a
73 // target, there should be no type comparisons at all for integer patterns!
74 //
75 // To figure out the fewest number of type checks needed, clone the pattern,
76 // remove the types, then perform type inference on the pattern as a whole.
77 // If there are unresolved types, emit an explicit check for those types,
78 // apply the type to the tree, then rerun type inference. Iterate until all
79 // types are resolved.
80 //
81 PatWithNoTypes = Pattern.getSrcPattern()->clone();
82 PatWithNoTypes->RemoveAllTypes();
83
84 // If there are types that are manifestly known, infer them.
85 InferPossibleTypes();
86}
87
88/// InferPossibleTypes - As we emit the pattern, we end up generating type
89/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
90/// want to propagate implied types as far throughout the tree as possible so
91/// that we avoid doing redundant type checks. This does the type propagation.
92void MatcherGen::InferPossibleTypes() {
93 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
94 // diagnostics, which we know are impossible at this point.
95 TreePattern &TP = *CGP.pf_begin()->second;
96
97 try {
98 bool MadeChange = true;
99 while (MadeChange)
100 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
101 true/*Ignore reg constraints*/);
102 } catch (...) {
103 errs() << "Type constraint application shouldn't fail!";
104 abort();
105 }
106}
107
108
109/// AddMatcherNode - Add a matcher node to the current graph we're building.
110void MatcherGen::AddMatcherNode(MatcherNodeWithChild *NewNode) {
111 if (CurPredicate != 0)
112 CurPredicate->setChild(NewNode);
113 else
114 Matcher = NewNode;
115 CurPredicate = NewNode;
116}
117
118
119
120/// EmitLeafMatchCode - Generate matching code for leaf nodes.
121void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
122 assert(N->isLeaf() && "Not a leaf?");
123 // Direct match against an integer constant.
124 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue()))
125 return AddMatcherNode(new CheckIntegerMatcherNode(II->getValue()));
126
127 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
128 if (DI == 0) {
129 errs() << "Unknown leaf kind: " << *DI << "\n";
130 abort();
131 }
132
133 Record *LeafRec = DI->getDef();
134 if (// Handle register references. Nothing to do here, they always match.
135 LeafRec->isSubClassOf("RegisterClass") ||
136 LeafRec->isSubClassOf("PointerLikeRegClass") ||
137 LeafRec->isSubClassOf("Register") ||
138 // Place holder for SRCVALUE nodes. Nothing to do here.
139 LeafRec->getName() == "srcvalue")
140 return;
141
142 if (LeafRec->isSubClassOf("ValueType"))
143 return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
144
145 if (LeafRec->isSubClassOf("CondCode"))
146 return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
147
148 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattnerc2676b22010-02-17 00:11:30 +0000149 // We can't model ComplexPattern uses that don't have their name taken yet.
150 // The OPC_CheckComplexPattern operation implicitly records the results.
151 if (N->getName().empty()) {
Chris Lattner53a2f602010-02-16 23:16:25 +0000152 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
153 exit(1);
154 }
155
Chris Lattnerda272d12010-02-15 08:04:42 +0000156 // Handle complex pattern.
157 const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000158 AddMatcherNode(new CheckComplexPatMatcherNode(CP));
159
160 // If the complex pattern has a chain, then we need to keep track of the
161 // fact that we just recorded a chain input. The chain input will be
162 // matched as the last operand of the predicate if it was successful.
163 if (CP.hasProperty(SDNPHasChain)) {
164 // It is the last operand recorded.
165 assert(NextRecordedOperandNo > 1 &&
166 "Should have recorded input/result chains at least!");
167 InputChains.push_back(NextRecordedOperandNo-1);
168 }
169 return;
Chris Lattnerda272d12010-02-15 08:04:42 +0000170 }
171
172 errs() << "Unknown leaf kind: " << *N << "\n";
173 abort();
174}
175
176void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
177 TreePatternNode *NodeNoTypes) {
178 assert(!N->isLeaf() && "Not an operator?");
179 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
180
181 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
182 // a constant without a predicate fn that has more that one bit set, handle
183 // this as a special case. This is usually for targets that have special
184 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
185 // handling stuff). Using these instructions is often far more efficient
186 // than materializing the constant. Unfortunately, both the instcombiner
187 // and the dag combiner can often infer that bits are dead, and thus drop
188 // them from the mask in the dag. For example, it might turn 'AND X, 255'
189 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
190 // to handle this.
191 if ((N->getOperator()->getName() == "and" ||
192 N->getOperator()->getName() == "or") &&
193 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty()) {
194 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
195 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
196 if (N->getOperator()->getName() == "and")
197 AddMatcherNode(new CheckAndImmMatcherNode(II->getValue()));
198 else
199 AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
200
201 // Match the LHS of the AND as appropriate.
202 AddMatcherNode(new MoveChildMatcherNode(0));
203 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
204 AddMatcherNode(new MoveParentMatcherNode());
205 return;
206 }
207 }
208 }
209
210 // Check that the current opcode lines up.
211 AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
212
213 // If this node has a chain, then the chain is operand #0 is the SDNode, and
214 // the child numbers of the node are all offset by one.
215 unsigned OpNo = 0;
Chris Lattner6bc1b512010-02-16 19:19:58 +0000216 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000217 // Record the input chain, which is always input #0 of the SDNode.
218 AddMatcherNode(new MoveChildMatcherNode(0));
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000219 AddMatcherNode(new RecordMatcherNode("'" + N->getOperator()->getName() +
220 "' input chain"));
Chris Lattner785d16f2010-02-17 02:16:19 +0000221
222 // Remember all of the input chains our pattern will match.
223 InputChains.push_back(NextRecordedOperandNo);
224 ++NextRecordedOperandNo;
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000225 AddMatcherNode(new MoveParentMatcherNode());
Chris Lattner785d16f2010-02-17 02:16:19 +0000226
227 // If this is the second (e.g. indbr(load) or store(add(load))) or third
228 // input chain (e.g. (store (add (load, load))) from msp430) we need to make
229 // sure that folding the chain won't induce cycles in the DAG. This could
230 // happen if there were an intermediate node between the indbr and load, for
231 // example.
232
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000233 // FIXME: Emit "IsChainCompatible(lastchain.getNode(), CurrentNode)".
Chris Lattner785d16f2010-02-17 02:16:19 +0000234 // Rename IsChainCompatible -> IsChainUnreachable, add comment about
235 // complexity.
236
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000237 // Don't look at the input chain when matching the tree pattern to the
238 // SDNode.
Chris Lattnerda272d12010-02-15 08:04:42 +0000239 OpNo = 1;
240
Chris Lattner6bc1b512010-02-16 19:19:58 +0000241 // If this node is not the root and the subtree underneath it produces a
242 // chain, then the result of matching the node is also produce a chain.
243 // Beyond that, this means that we're also folding (at least) the root node
244 // into the node that produce the chain (for example, matching
245 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
246 // problematic, if the 'reg' node also uses the load (say, its chain).
247 // Graphically:
248 //
249 // [LD]
250 // ^ ^
251 // | \ DAG's like cheese.
252 // / |
253 // / [YY]
254 // | ^
255 // [XX]--/
256 //
257 // It would be invalid to fold XX and LD. In this case, folding the two
258 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
259 // To prevent this, we emit a dynamic check for legality before allowing
260 // this to be folded.
261 //
262 const TreePatternNode *Root = Pattern.getSrcPattern();
263 if (N != Root) { // Not the root of the pattern.
Chris Lattnere39650a2010-02-16 06:10:58 +0000264 // If there is a node between the root and this node, then we definitely
265 // need to emit the check.
266 bool NeedCheck = !Root->hasChild(N);
267
268 // If it *is* an immediate child of the root, we can still need a check if
269 // the root SDNode has multiple inputs. For us, this means that it is an
270 // intrinsic, has multiple operands, or has other inputs like chain or
271 // flag).
272 if (!NeedCheck) {
273 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
274 NeedCheck =
275 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
276 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
277 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
278 PInfo.getNumOperands() > 1 ||
279 PInfo.hasProperty(SDNPHasChain) ||
280 PInfo.hasProperty(SDNPInFlag) ||
281 PInfo.hasProperty(SDNPOptInFlag);
282 }
283
284 if (NeedCheck)
Chris Lattner21390d72010-02-16 19:15:55 +0000285 AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
Chris Lattnere39650a2010-02-16 06:10:58 +0000286 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000287 }
288
Chris Lattnerda272d12010-02-15 08:04:42 +0000289 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
290 // Get the code suitable for matching this child. Move to the child, check
291 // it then move back to the parent.
Chris Lattnerc642b842010-02-17 01:27:29 +0000292 AddMatcherNode(new MoveChildMatcherNode(OpNo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000293 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
294 AddMatcherNode(new MoveParentMatcherNode());
295 }
296}
297
298
299void MatcherGen::EmitMatchCode(const TreePatternNode *N,
300 TreePatternNode *NodeNoTypes) {
301 // If N and NodeNoTypes don't agree on a type, then this is a case where we
302 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
303 // reinfer any correlated types.
304 if (NodeNoTypes->getExtTypes() != N->getExtTypes()) {
305 AddMatcherNode(new CheckTypeMatcherNode(N->getTypeNum(0)));
306 NodeNoTypes->setTypes(N->getExtTypes());
307 InferPossibleTypes();
308 }
309
Chris Lattnerda272d12010-02-15 08:04:42 +0000310 // If this node has a name associated with it, capture it in VariableMap. If
311 // we already saw this in the pattern, emit code to verify dagness.
312 if (!N->getName().empty()) {
313 unsigned &VarMapEntry = VariableMap[N->getName()];
314 if (VarMapEntry == 0) {
Chris Lattnere609a512010-02-17 00:31:50 +0000315 VarMapEntry = NextRecordedOperandNo+1;
316
317 unsigned NumRecorded;
Chris Lattner53a2f602010-02-16 23:16:25 +0000318
319 // If this is a complex pattern, the match operation for it will
320 // implicitly record all of the outputs of it (which may be more than
321 // one).
322 if (const ComplexPattern *AM = N->getComplexPatternInfo(CGP)) {
323 // Record the right number of operands.
Chris Lattnere609a512010-02-17 00:31:50 +0000324 NumRecorded = AM->getNumOperands()-1;
325
326 if (AM->hasProperty(SDNPHasChain))
327 NumRecorded += 2; // Input and output chains.
Chris Lattner53a2f602010-02-16 23:16:25 +0000328 } else {
329 // If it is a normal named node, we must emit a 'Record' opcode.
Chris Lattnerc642b842010-02-17 01:27:29 +0000330 AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
Chris Lattnere609a512010-02-17 00:31:50 +0000331 NumRecorded = 1;
Chris Lattner53a2f602010-02-16 23:16:25 +0000332 }
Chris Lattnere609a512010-02-17 00:31:50 +0000333 NextRecordedOperandNo += NumRecorded;
Chris Lattner53a2f602010-02-16 23:16:25 +0000334
Chris Lattnerda272d12010-02-15 08:04:42 +0000335 } else {
336 // If we get here, this is a second reference to a specific name. Since
337 // we already have checked that the first reference is valid, we don't
338 // have to recursively match it, just check that it's the same as the
339 // previously named thing.
340 AddMatcherNode(new CheckSameMatcherNode(VarMapEntry-1));
341 return;
342 }
343 }
344
345 // If there are node predicates for this node, generate their checks.
346 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
347 AddMatcherNode(new CheckPredicateMatcherNode(N->getPredicateFns()[i]));
348
349 if (N->isLeaf())
350 EmitLeafMatchCode(N);
351 else
352 EmitOperatorMatchCode(N, NodeNoTypes);
353}
354
355void MatcherGen::EmitMatcherCode() {
356 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
357 // feature is around, do the check).
358 if (!Pattern.getPredicateCheck().empty())
359 AddMatcherNode(new
360 CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
361
362 // Emit the matcher for the pattern structure and types.
363 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
364}
365
366
367MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
368 const CodeGenDAGPatterns &CGP) {
369 MatcherGen Gen(Pattern, CGP);
370
371 // Generate the code for the matcher.
372 Gen.EmitMatcherCode();
373
374 // If the match succeeds, then we generate Pattern.
375 EmitNodeMatcherNode *Result = new EmitNodeMatcherNode(Pattern);
376
377 // Link it into the pattern.
378 if (MatcherNodeWithChild *Pred = Gen.GetCurPredicate()) {
379 Pred->setChild(Result);
380 return Gen.GetMatcher();
381 }
382
383 // Unconditional match.
384 return Result;
385}
386
387
388