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/SmallVector.h"
14 #include "llvm/ADT/StringMap.h"
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
27 } Kind : 2; // True if temporary, false if recorded.
29 static ResultVal getRecorded(unsigned N) {
36 static ResultVal getTemp(unsigned N) {
43 bool isTemp() const { return Kind == Temporary; }
44 bool isRecorded() const { return Kind == Recorded; }
46 unsigned getTempNo() const {
51 unsigned getRecordedNo() const {
59 const PatternToMatch &Pattern;
60 const CodeGenDAGPatterns &CGP;
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;
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
70 StringMap<unsigned> VariableMap;
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
75 unsigned NextRecordedOperandNo;
77 /// NextTemporary - As we generate code, this indicates the next temporary
78 /// ID that will be generated.
79 unsigned NextTemporary;
81 /// InputChains - This maintains the position in the recorded nodes array of
82 /// all of the recorded input chains.
83 SmallVector<unsigned, 2> InputChains;
85 /// Matcher - This is the top level of the generated matcher, the result.
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;
92 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
95 delete PatWithNoTypes;
98 void EmitMatcherCode();
99 void EmitResultCode();
101 MatcherNode *GetMatcher() const { return Matcher; }
102 MatcherNode *GetCurPredicate() const { return CurPredicate; }
104 void AddMatcherNode(MatcherNode *NewNode);
105 void InferPossibleTypes();
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);
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);
122 } // end anon namespace.
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!
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.
140 PatWithNoTypes = Pattern.getSrcPattern()->clone();
141 PatWithNoTypes->RemoveAllTypes();
143 // If there are types that are manifestly known, infer them.
144 InferPossibleTypes();
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;
157 bool MadeChange = true;
159 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
160 true/*Ignore reg constraints*/);
162 errs() << "Type constraint application shouldn't fail!";
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);
174 CurPredicate = NewNode;
178 //===----------------------------------------------------------------------===//
179 // Pattern Match Generation
180 //===----------------------------------------------------------------------===//
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()));
189 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
191 errs() << "Unknown leaf kind: " << *DI << "\n";
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")
204 if (LeafRec->isSubClassOf("ValueType"))
205 return AddMatcherNode(new CheckValueTypeMatcherNode(LeafRec->getName()));
207 if (LeafRec->isSubClassOf("CondCode"))
208 return AddMatcherNode(new CheckCondCodeMatcherNode(LeafRec->getName()));
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";
218 // Handle complex pattern.
219 const ComplexPattern &CP = CGP.getComplexPattern(LeafRec);
220 AddMatcherNode(new CheckComplexPatMatcherNode(CP));
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);
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
237 unsigned PrevOp = InputChains[InputChains.size()-2];
238 AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
244 errs() << "Unknown leaf kind: " << *N << "\n";
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());
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
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()));
271 AddMatcherNode(new CheckOrImmMatcherNode(II->getValue()));
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());
282 // Check that the current opcode lines up.
283 AddMatcherNode(new CheckOpcodeMatcherNode(CInfo.getEnumName()));
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.
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() +
294 // Remember all of the input chains our pattern will match.
295 InputChains.push_back(NextRecordedOperandNo);
296 ++NextRecordedOperandNo;
297 AddMatcherNode(new MoveParentMatcherNode());
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
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
308 unsigned PrevOp = InputChains[InputChains.size()-2];
309 AddMatcherNode(new CheckChainCompatibleMatcherNode(PrevOp));
312 // Don't look at the input chain when matching the tree pattern to the
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).
326 // | \ DAG's like cheese.
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.
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);
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
348 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
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);
360 AddMatcherNode(new CheckFoldableChainNodeMatcherNode());
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());
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();
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;
392 unsigned NumRecorded;
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
397 if (const ComplexPattern *AM = N->getComplexPatternInfo(CGP)) {
398 // Record the right number of operands.
399 NumRecorded = AM->getNumOperands()-1;
401 if (AM->hasProperty(SDNPHasChain))
402 NumRecorded += 2; // Input and output chains.
404 // If it is a normal named node, we must emit a 'Record' opcode.
405 AddMatcherNode(new RecordMatcherNode("$" + N->getName()));
408 NextRecordedOperandNo += NumRecorded;
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));
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]));
425 EmitLeafMatchCode(N);
427 EmitOperatorMatchCode(N, NodeNoTypes);
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())
435 CheckPatternPredicateMatcherNode(Pattern.getPredicateCheck()));
437 // Emit the matcher for the pattern structure and types.
438 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
442 //===----------------------------------------------------------------------===//
443 // Node Result Generation
444 //===----------------------------------------------------------------------===//
446 void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
447 SmallVectorImpl<ResultVal> &ResultOps){
448 assert(N->isLeaf() && "Must be a leaf");
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++));
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(),
461 ResultOps.push_back(ResultVal::getTemp(NextTemporary++));
465 if (DI->getDef()->getName() == "zero_reg") {
466 AddMatcherNode(new EmitRegisterMatcherNode(0, N->getTypeNum(0)));
467 ResultOps.push_back(ResultVal::getTemp(NextTemporary++));
472 if (DI->getDef()->isSubClassOf("RegisterClass")) {
473 // Handle a reference to a register class. This is used
474 // in COPY_TO_SUBREG instructions.
480 errs() << "unhandled leaf node: \n";
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);
491 // FIXME: Handle (set x, (foo))
493 if (II.isVariadic) // FIXME: Handle variadic instructions.
494 return AddMatcherNode(new EmitNodeMatcherNode(Pattern));
496 // FIXME: Handle OptInFlag, HasInFlag, HasOutFlag
497 // FIXME: Handle Chains.
498 unsigned NumResults = Inst.getNumResults();
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) {
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);
525 // Otherwise this is a normal operand or a predicate operand without
526 // 'execute always'; emit it.
527 EmitResultOperand(N->getChild(ChildNo), Ops);
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";
549 return EmitResultLeafAsOperand(N, ResultOps);
551 Record *OpRec = N->getOperator();
552 if (OpRec->isSubClassOf("Instruction"))
553 return EmitResultInstructionAsOperand(N, ResultOps);
554 if (OpRec->isSubClassOf("SDNodeXForm"))
557 errs() << "Unknown result node to emit code for: " << *N << '\n';
558 throw std::string("Unknown node in result pattern!");
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));
571 MatcherNode *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
572 const CodeGenDAGPatterns &CGP) {
573 MatcherGen Gen(Pattern, CGP);
575 // Generate the code for the matcher.
576 Gen.EmitMatcherCode();
578 // If the match succeeds, then we generate Pattern.
579 Gen.EmitResultCode();
581 // Unconditional match.
582 return Gen.GetMatcher();