blob: 38ffa30ec851ada5da07430a5080ef7b6800cfb0 [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"
Jim Grosbach4a6d7352011-03-11 02:19:02 +000012#include "CodeGenRegisters.h"
Jim Grosbach4a6d7352011-03-11 02:19:02 +000013#include "llvm/ADT/DenseMap.h"
Chris Lattner785d16f2010-02-17 02:16:19 +000014#include "llvm/ADT/SmallVector.h"
Chris Lattnerda272d12010-02-15 08:04:42 +000015#include "llvm/ADT/StringMap.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000016#include "llvm/TableGen/Error.h"
17#include "llvm/TableGen/Record.h"
Chris Lattner8e946be2010-02-21 03:22:59 +000018#include <utility>
Chris Lattnerda272d12010-02-15 08:04:42 +000019using namespace llvm;
20
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000021
Chris Lattner8e946be2010-02-21 03:22:59 +000022/// getRegisterValueType - Look up and return the ValueType of the specified
23/// register. If the register is a member of multiple register classes which
24/// have different associated types, return MVT::Other.
25static MVT::SimpleValueType getRegisterValueType(Record *R,
26 const CodeGenTarget &T) {
27 bool FoundRC = false;
28 MVT::SimpleValueType VT = MVT::Other;
Jakob Stoklund Olesenae1920b2011-06-15 04:50:36 +000029 const CodeGenRegister *Reg = T.getRegBank().getReg(R);
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +000030 ArrayRef<CodeGenRegisterClass*> RCs = T.getRegBank().getRegClasses();
Jim Grosbachfbadcd02010-12-21 16:16:00 +000031
Chris Lattner8e946be2010-02-21 03:22:59 +000032 for (unsigned rc = 0, e = RCs.size(); rc != e; ++rc) {
Jakob Stoklund Olesen29f018c2011-09-29 22:28:37 +000033 const CodeGenRegisterClass &RC = *RCs[rc];
Jakob Stoklund Olesenae1920b2011-06-15 04:50:36 +000034 if (!RC.contains(Reg))
Chris Lattner8e946be2010-02-21 03:22:59 +000035 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000036
Chris Lattner8e946be2010-02-21 03:22:59 +000037 if (!FoundRC) {
38 FoundRC = true;
39 VT = RC.getValueTypeNum(0);
40 continue;
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000041 }
Chris Lattner67ea6a72010-03-01 22:49:06 +000042
43 // If this occurs in multiple register classes, they all have to agree.
44 assert(VT == RC.getValueTypeNum(0));
Chris Lattner8e946be2010-02-21 03:22:59 +000045 }
46 return VT;
47}
48
49
50namespace {
Chris Lattnerda272d12010-02-15 08:04:42 +000051 class MatcherGen {
52 const PatternToMatch &Pattern;
53 const CodeGenDAGPatterns &CGP;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000054
Chris Lattnerda272d12010-02-15 08:04:42 +000055 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
56 /// out with all of the types removed. This allows us to insert type checks
57 /// as we scan the tree.
58 TreePatternNode *PatWithNoTypes;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000059
Chris Lattnerda272d12010-02-15 08:04:42 +000060 /// VariableMap - A map from variable names ('$dst') to the recorded operand
61 /// number that they were captured as. These are biased by 1 to make
62 /// insertion easier.
63 StringMap<unsigned> VariableMap;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000064
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000065 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
66 /// the RecordedNodes array, this keeps track of which slot will be next to
67 /// record into.
Chris Lattnerda272d12010-02-15 08:04:42 +000068 unsigned NextRecordedOperandNo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000069
Chris Lattner8e946be2010-02-21 03:22:59 +000070 /// MatchedChainNodes - This maintains the position in the recorded nodes
71 /// array of all of the recorded input nodes that have chains.
72 SmallVector<unsigned, 2> MatchedChainNodes;
Chris Lattner02f73582010-02-24 05:33:42 +000073
Chris Lattner8950bca2010-12-23 17:03:20 +000074 /// MatchedGlueResultNodes - This maintains the position in the recorded
75 /// nodes array of all of the recorded input nodes that have glue results.
76 SmallVector<unsigned, 2> MatchedGlueResultNodes;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000077
Chris Lattner57bf8a42010-03-04 01:23:08 +000078 /// MatchedComplexPatterns - This maintains a list of all of the
79 /// ComplexPatterns that we need to check. The patterns are known to have
80 /// names which were recorded. The second element of each pair is the first
81 /// slot number that the OPC_CheckComplexPat opcode drops the matched
82 /// results into.
83 SmallVector<std::pair<const TreePatternNode*,
84 unsigned>, 2> MatchedComplexPatterns;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000085
Chris Lattner8e946be2010-02-21 03:22:59 +000086 /// PhysRegInputs - List list has an entry for each explicitly specified
87 /// physreg input to the pattern. The first elt is the Register node, the
88 /// second is the recorded slot number the input pattern match saved it in.
89 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000090
Chris Lattner785d16f2010-02-17 02:16:19 +000091 /// Matcher - This is the top level of the generated matcher, the result.
Chris Lattnerb21ba712010-02-25 02:04:40 +000092 Matcher *TheMatcher;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000093
Chris Lattner785d16f2010-02-17 02:16:19 +000094 /// CurPredicate - As we emit matcher nodes, this points to the latest check
Chris Lattnerbd8227f2010-02-18 02:53:41 +000095 /// which should have future checks stuck into its Next position.
Chris Lattnerb21ba712010-02-25 02:04:40 +000096 Matcher *CurPredicate;
Chris Lattnerda272d12010-02-15 08:04:42 +000097 public:
98 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
Jim Grosbachfbadcd02010-12-21 16:16:00 +000099
Chris Lattnerda272d12010-02-15 08:04:42 +0000100 ~MatcherGen() {
101 delete PatWithNoTypes;
102 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000103
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000104 bool EmitMatcherCode(unsigned Variant);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000105 void EmitResultCode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000106
Chris Lattnerb21ba712010-02-25 02:04:40 +0000107 Matcher *GetMatcher() const { return TheMatcher; }
Chris Lattnerda272d12010-02-15 08:04:42 +0000108 private:
Chris Lattnerb21ba712010-02-25 02:04:40 +0000109 void AddMatcher(Matcher *NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000110 void InferPossibleTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000111
Chris Lattnerb49985a2010-02-18 06:47:49 +0000112 // Matcher Generation.
Chris Lattnerda272d12010-02-15 08:04:42 +0000113 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
114 void EmitLeafMatchCode(const TreePatternNode *N);
115 void EmitOperatorMatchCode(const TreePatternNode *N,
116 TreePatternNode *NodeNoTypes);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000117
Chris Lattnerb49985a2010-02-18 06:47:49 +0000118 // Result Code Generation.
Chris Lattner8e946be2010-02-21 03:22:59 +0000119 unsigned getNamedArgumentSlot(StringRef Name) {
120 unsigned VarMapEntry = VariableMap[Name];
121 assert(VarMapEntry != 0 &&
122 "Variable referenced but not defined and not caught earlier!");
123 return VarMapEntry-1;
124 }
125
126 /// GetInstPatternNode - Get the pattern for an instruction.
127 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
128 const TreePatternNode *N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000129
Chris Lattnerb49985a2010-02-18 06:47:49 +0000130 void EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000131 SmallVectorImpl<unsigned> &ResultOps);
132 void EmitResultOfNamedOperand(const TreePatternNode *N,
133 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000134 void EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000135 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000136 void EmitResultInstructionAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000137 SmallVectorImpl<unsigned> &ResultOps);
138 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
139 SmallVectorImpl<unsigned> &ResultOps);
140 };
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000141
Chris Lattnerda272d12010-02-15 08:04:42 +0000142} // end anon namespace.
143
144MatcherGen::MatcherGen(const PatternToMatch &pattern,
145 const CodeGenDAGPatterns &cgp)
Chris Lattner853b9192010-02-19 00:33:13 +0000146: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
Chris Lattner01bcd942010-03-01 22:46:42 +0000147 TheMatcher(0), CurPredicate(0) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000148 // We need to produce the matcher tree for the patterns source pattern. To do
149 // this we need to match the structure as well as the types. To do the type
150 // matching, we want to figure out the fewest number of type checks we need to
151 // emit. For example, if there is only one integer type supported by a
152 // target, there should be no type comparisons at all for integer patterns!
153 //
154 // To figure out the fewest number of type checks needed, clone the pattern,
155 // remove the types, then perform type inference on the pattern as a whole.
156 // If there are unresolved types, emit an explicit check for those types,
157 // apply the type to the tree, then rerun type inference. Iterate until all
158 // types are resolved.
159 //
160 PatWithNoTypes = Pattern.getSrcPattern()->clone();
161 PatWithNoTypes->RemoveAllTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000162
Chris Lattnerda272d12010-02-15 08:04:42 +0000163 // If there are types that are manifestly known, infer them.
164 InferPossibleTypes();
165}
166
167/// InferPossibleTypes - As we emit the pattern, we end up generating type
168/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
169/// want to propagate implied types as far throughout the tree as possible so
170/// that we avoid doing redundant type checks. This does the type propagation.
171void MatcherGen::InferPossibleTypes() {
172 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
173 // diagnostics, which we know are impossible at this point.
174 TreePattern &TP = *CGP.pf_begin()->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000175
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000176 bool MadeChange = true;
177 while (MadeChange)
178 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
179 true/*Ignore reg constraints*/);
Chris Lattnerda272d12010-02-15 08:04:42 +0000180}
181
182
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000183/// AddMatcher - Add a matcher node to the current graph we're building.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000184void MatcherGen::AddMatcher(Matcher *NewNode) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000185 if (CurPredicate != 0)
Chris Lattnerbd8227f2010-02-18 02:53:41 +0000186 CurPredicate->setNext(NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000187 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000188 TheMatcher = NewNode;
Chris Lattnerda272d12010-02-15 08:04:42 +0000189 CurPredicate = NewNode;
190}
191
192
Chris Lattnerb49985a2010-02-18 06:47:49 +0000193//===----------------------------------------------------------------------===//
194// Pattern Match Generation
195//===----------------------------------------------------------------------===//
Chris Lattnerda272d12010-02-15 08:04:42 +0000196
197/// EmitLeafMatchCode - Generate matching code for leaf nodes.
198void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
199 assert(N->isLeaf() && "Not a leaf?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000200
Chris Lattnerda272d12010-02-15 08:04:42 +0000201 // Direct match against an integer constant.
Sean Silva6cfc8062012-10-10 20:24:43 +0000202 if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
Chris Lattnerbd8965a2010-03-01 07:27:07 +0000203 // If this is the root of the dag we're matching, we emit a redundant opcode
204 // check to ensure that this gets folded into the normal top-level
205 // OpcodeSwitch.
206 if (N == Pattern.getSrcPattern()) {
207 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
208 AddMatcher(new CheckOpcodeMatcher(NI));
209 }
210
Chris Lattnerb21ba712010-02-25 02:04:40 +0000211 return AddMatcher(new CheckIntegerMatcher(II->getValue()));
Chris Lattnerbd8965a2010-03-01 07:27:07 +0000212 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000213
Sean Silva6cfc8062012-10-10 20:24:43 +0000214 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Chris Lattnerda272d12010-02-15 08:04:42 +0000215 if (DI == 0) {
Chris Lattneref18cd32012-03-26 19:11:51 +0000216 errs() << "Unknown leaf kind: " << *N << "\n";
Chris Lattnerda272d12010-02-15 08:04:42 +0000217 abort();
218 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000219
Chris Lattnerda272d12010-02-15 08:04:42 +0000220 Record *LeafRec = DI->getDef();
221 if (// Handle register references. Nothing to do here, they always match.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000222 LeafRec->isSubClassOf("RegisterClass") ||
Owen Andersonbea6f612011-06-27 21:06:21 +0000223 LeafRec->isSubClassOf("RegisterOperand") ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000224 LeafRec->isSubClassOf("PointerLikeRegClass") ||
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +0000225 LeafRec->isSubClassOf("SubRegIndex") ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000226 // Place holder for SRCVALUE nodes. Nothing to do here.
227 LeafRec->getName() == "srcvalue")
228 return;
Chris Lattner8e946be2010-02-21 03:22:59 +0000229
230 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000231 // record the register
Chris Lattner8e946be2010-02-21 03:22:59 +0000232 if (LeafRec->isSubClassOf("Register")) {
Chris Lattner0cebe612010-03-01 02:24:17 +0000233 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(),
234 NextRecordedOperandNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000235 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
236 return;
237 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000238
Chris Lattnerda272d12010-02-15 08:04:42 +0000239 if (LeafRec->isSubClassOf("ValueType"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000240 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000241
Chris Lattnerda272d12010-02-15 08:04:42 +0000242 if (LeafRec->isSubClassOf("CondCode"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000243 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000244
Chris Lattnerda272d12010-02-15 08:04:42 +0000245 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattnerc2676b22010-02-17 00:11:30 +0000246 // We can't model ComplexPattern uses that don't have their name taken yet.
247 // The OPC_CheckComplexPattern operation implicitly records the results.
248 if (N->getName().empty()) {
Chris Lattner53a2f602010-02-16 23:16:25 +0000249 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
250 exit(1);
251 }
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000252
Chris Lattner57bf8a42010-03-04 01:23:08 +0000253 // Remember this ComplexPattern so that we can emit it after all the other
254 // structural matches are done.
255 MatchedComplexPatterns.push_back(std::make_pair(N, 0));
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000256 return;
Chris Lattnerda272d12010-02-15 08:04:42 +0000257 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000258
Chris Lattnerda272d12010-02-15 08:04:42 +0000259 errs() << "Unknown leaf kind: " << *N << "\n";
260 abort();
261}
262
263void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
264 TreePatternNode *NodeNoTypes) {
265 assert(!N->isLeaf() && "Not an operator?");
266 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000267
Chris Lattnerda272d12010-02-15 08:04:42 +0000268 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
269 // a constant without a predicate fn that has more that one bit set, handle
270 // this as a special case. This is usually for targets that have special
271 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
272 // handling stuff). Using these instructions is often far more efficient
273 // than materializing the constant. Unfortunately, both the instcombiner
274 // and the dag combiner can often infer that bits are dead, and thus drop
275 // them from the mask in the dag. For example, it might turn 'AND X, 255'
276 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
277 // to handle this.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000278 if ((N->getOperator()->getName() == "and" ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000279 N->getOperator()->getName() == "or") &&
Chris Lattner8e946be2010-02-21 03:22:59 +0000280 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
281 N->getPredicateFns().empty()) {
Sean Silva6cfc8062012-10-10 20:24:43 +0000282 if (IntInit *II = dyn_cast<IntInit>(N->getChild(1)->getLeafValue())) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000283 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
Chris Lattnere9eeda82010-03-01 02:15:34 +0000284 // If this is at the root of the pattern, we emit a redundant
285 // CheckOpcode so that the following checks get factored properly under
286 // a single opcode check.
287 if (N == Pattern.getSrcPattern())
288 AddMatcher(new CheckOpcodeMatcher(CInfo));
289
290 // Emit the CheckAndImm/CheckOrImm node.
Chris Lattnerda272d12010-02-15 08:04:42 +0000291 if (N->getOperator()->getName() == "and")
Chris Lattnerb21ba712010-02-25 02:04:40 +0000292 AddMatcher(new CheckAndImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000293 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000294 AddMatcher(new CheckOrImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000295
296 // Match the LHS of the AND as appropriate.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000297 AddMatcher(new MoveChildMatcher(0));
Chris Lattnerda272d12010-02-15 08:04:42 +0000298 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000299 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000300 return;
301 }
302 }
303 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000304
Chris Lattnerda272d12010-02-15 08:04:42 +0000305 // Check that the current opcode lines up.
Chris Lattnera230f962010-02-27 21:48:43 +0000306 AddMatcher(new CheckOpcodeMatcher(CInfo));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000307
Chris Lattner8e946be2010-02-21 03:22:59 +0000308 // If this node has memory references (i.e. is a load or store), tell the
309 // interpreter to capture them in the memref array.
310 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000311 AddMatcher(new RecordMemRefMatcher());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000312
Chris Lattnerda272d12010-02-15 08:04:42 +0000313 // If this node has a chain, then the chain is operand #0 is the SDNode, and
314 // the child numbers of the node are all offset by one.
315 unsigned OpNo = 0;
Chris Lattner6bc1b512010-02-16 19:19:58 +0000316 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000317 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000318 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner0cebe612010-03-01 02:24:17 +0000319 "' chained node",
320 NextRecordedOperandNo));
Chris Lattner785d16f2010-02-17 02:16:19 +0000321 // Remember all of the input chains our pattern will match.
Chris Lattner8e946be2010-02-21 03:22:59 +0000322 MatchedChainNodes.push_back(NextRecordedOperandNo++);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000323
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000324 // Don't look at the input chain when matching the tree pattern to the
325 // SDNode.
Chris Lattnerda272d12010-02-15 08:04:42 +0000326 OpNo = 1;
327
Chris Lattner6bc1b512010-02-16 19:19:58 +0000328 // If this node is not the root and the subtree underneath it produces a
329 // chain, then the result of matching the node is also produce a chain.
330 // Beyond that, this means that we're also folding (at least) the root node
331 // into the node that produce the chain (for example, matching
332 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
333 // problematic, if the 'reg' node also uses the load (say, its chain).
334 // Graphically:
335 //
336 // [LD]
337 // ^ ^
338 // | \ DAG's like cheese.
339 // / |
340 // / [YY]
341 // | ^
342 // [XX]--/
343 //
344 // It would be invalid to fold XX and LD. In this case, folding the two
345 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
346 // To prevent this, we emit a dynamic check for legality before allowing
347 // this to be folded.
348 //
349 const TreePatternNode *Root = Pattern.getSrcPattern();
350 if (N != Root) { // Not the root of the pattern.
Chris Lattnere39650a2010-02-16 06:10:58 +0000351 // If there is a node between the root and this node, then we definitely
352 // need to emit the check.
353 bool NeedCheck = !Root->hasChild(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000354
Chris Lattnere39650a2010-02-16 06:10:58 +0000355 // If it *is* an immediate child of the root, we can still need a check if
356 // the root SDNode has multiple inputs. For us, this means that it is an
357 // intrinsic, has multiple operands, or has other inputs like chain or
Chris Lattner8950bca2010-12-23 17:03:20 +0000358 // glue).
Chris Lattnere39650a2010-02-16 06:10:58 +0000359 if (!NeedCheck) {
360 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
361 NeedCheck =
362 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
363 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
364 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
365 PInfo.getNumOperands() > 1 ||
366 PInfo.hasProperty(SDNPHasChain) ||
Chris Lattner036609b2010-12-23 18:28:41 +0000367 PInfo.hasProperty(SDNPInGlue) ||
368 PInfo.hasProperty(SDNPOptInGlue);
Chris Lattnere39650a2010-02-16 06:10:58 +0000369 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000370
Chris Lattnere39650a2010-02-16 06:10:58 +0000371 if (NeedCheck)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000372 AddMatcher(new CheckFoldableChainNodeMatcher());
Chris Lattnere39650a2010-02-16 06:10:58 +0000373 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000374 }
Chris Lattner02f73582010-02-24 05:33:42 +0000375
Chris Lattner8950bca2010-12-23 17:03:20 +0000376 // If this node has an output glue and isn't the root, remember it.
Chris Lattner036609b2010-12-23 18:28:41 +0000377 if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
Chris Lattner02f73582010-02-24 05:33:42 +0000378 N != Pattern.getSrcPattern()) {
Chris Lattner8950bca2010-12-23 17:03:20 +0000379 // TODO: This redundantly records nodes with both glues and chains.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000380
Chris Lattner02f73582010-02-24 05:33:42 +0000381 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000382 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner8950bca2010-12-23 17:03:20 +0000383 "' glue output node",
Chris Lattner0cebe612010-03-01 02:24:17 +0000384 NextRecordedOperandNo));
Chris Lattner8950bca2010-12-23 17:03:20 +0000385 // Remember all of the nodes with output glue our pattern will match.
386 MatchedGlueResultNodes.push_back(NextRecordedOperandNo++);
Chris Lattner02f73582010-02-24 05:33:42 +0000387 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000388
Chris Lattner8950bca2010-12-23 17:03:20 +0000389 // If this node is known to have an input glue or if it *might* have an input
390 // glue, capture it as the glue input of the pattern.
Chris Lattner036609b2010-12-23 18:28:41 +0000391 if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
392 N->NodeHasProperty(SDNPInGlue, CGP))
Chris Lattner8950bca2010-12-23 17:03:20 +0000393 AddMatcher(new CaptureGlueInputMatcher());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000394
Chris Lattnerda272d12010-02-15 08:04:42 +0000395 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
396 // Get the code suitable for matching this child. Move to the child, check
397 // it then move back to the parent.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000398 AddMatcher(new MoveChildMatcher(OpNo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000399 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000400 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000401 }
402}
403
404
405void MatcherGen::EmitMatchCode(const TreePatternNode *N,
406 TreePatternNode *NodeNoTypes) {
407 // If N and NodeNoTypes don't agree on a type, then this is a case where we
408 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
409 // reinfer any correlated types.
Chris Lattner084df622010-03-24 00:41:19 +0000410 SmallVector<unsigned, 2> ResultsToTypeCheck;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000411
Chris Lattner084df622010-03-24 00:41:19 +0000412 for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
413 if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
414 NodeNoTypes->setType(i, N->getExtType(i));
Chris Lattnerda272d12010-02-15 08:04:42 +0000415 InferPossibleTypes();
Chris Lattner084df622010-03-24 00:41:19 +0000416 ResultsToTypeCheck.push_back(i);
Chris Lattnerda272d12010-02-15 08:04:42 +0000417 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000418
Chris Lattnerda272d12010-02-15 08:04:42 +0000419 // If this node has a name associated with it, capture it in VariableMap. If
420 // we already saw this in the pattern, emit code to verify dagness.
421 if (!N->getName().empty()) {
422 unsigned &VarMapEntry = VariableMap[N->getName()];
423 if (VarMapEntry == 0) {
Chris Lattner20df2422010-02-22 23:33:44 +0000424 // If it is a named node, we must emit a 'Record' opcode.
Chris Lattner0cebe612010-03-01 02:24:17 +0000425 AddMatcher(new RecordMatcher("$" + N->getName(), NextRecordedOperandNo));
Chris Lattner20df2422010-02-22 23:33:44 +0000426 VarMapEntry = ++NextRecordedOperandNo;
Chris Lattnerda272d12010-02-15 08:04:42 +0000427 } else {
428 // If we get here, this is a second reference to a specific name. Since
429 // we already have checked that the first reference is valid, we don't
430 // have to recursively match it, just check that it's the same as the
431 // previously named thing.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000432 AddMatcher(new CheckSameMatcher(VarMapEntry-1));
Chris Lattnerda272d12010-02-15 08:04:42 +0000433 return;
434 }
435 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000436
Chris Lattnerda272d12010-02-15 08:04:42 +0000437 if (N->isLeaf())
438 EmitLeafMatchCode(N);
439 else
440 EmitOperatorMatchCode(N, NodeNoTypes);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000441
Chris Lattner6fd326b2010-03-07 07:20:49 +0000442 // If there are node predicates for this node, generate their checks.
443 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
444 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000445
Chris Lattner084df622010-03-24 00:41:19 +0000446 for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
447 AddMatcher(new CheckTypeMatcher(N->getType(ResultsToTypeCheck[i]),
448 ResultsToTypeCheck[i]));
Chris Lattnerda272d12010-02-15 08:04:42 +0000449}
450
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000451/// EmitMatcherCode - Generate the code that matches the predicate of this
452/// pattern for the specified Variant. If the variant is invalid this returns
453/// true and does not generate code, if it is valid, it returns false.
454bool MatcherGen::EmitMatcherCode(unsigned Variant) {
455 // If the root of the pattern is a ComplexPattern and if it is specified to
456 // match some number of root opcodes, these are considered to be our variants.
457 // Depending on which variant we're generating code for, emit the root opcode
458 // check.
459 if (const ComplexPattern *CP =
460 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000461 const std::vector<Record*> &OpNodes = CP->getRootNodes();
Chris Lattner405f1252010-03-01 22:29:19 +0000462 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
463 if (Variant >= OpNodes.size()) return true;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000464
Chris Lattner405f1252010-03-01 22:29:19 +0000465 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000466 } else {
467 if (Variant != 0) return true;
468 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000469
Chris Lattner9752fb12010-03-04 01:25:36 +0000470 // Emit the matcher for the pattern structure and types.
471 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000472
Chris Lattnerda272d12010-02-15 08:04:42 +0000473 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
474 // feature is around, do the check).
475 if (!Pattern.getPredicateCheck().empty())
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000476 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000477
Chris Lattner57bf8a42010-03-04 01:23:08 +0000478 // Now that we've completed the structural type match, emit any ComplexPattern
479 // checks (e.g. addrmode matches). We emit this after the structural match
480 // because they are generally more expensive to evaluate and more difficult to
481 // factor.
Chris Lattner57bf8a42010-03-04 01:23:08 +0000482 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
483 const TreePatternNode *N = MatchedComplexPatterns[i].first;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000484
Chris Lattner57bf8a42010-03-04 01:23:08 +0000485 // Remember where the results of this match get stuck.
486 MatchedComplexPatterns[i].second = NextRecordedOperandNo;
487
488 // Get the slot we recorded the value in from the name on the node.
489 unsigned RecNodeEntry = VariableMap[N->getName()];
490 assert(!N->getName().empty() && RecNodeEntry &&
491 "Complex pattern should have a name and slot");
492 --RecNodeEntry; // Entries in VariableMap are biased.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000493
Chris Lattner57bf8a42010-03-04 01:23:08 +0000494 const ComplexPattern &CP =
David Greene05bce0b2011-07-29 22:43:06 +0000495 CGP.getComplexPattern(((DefInit*)N->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000496
Chris Lattner57bf8a42010-03-04 01:23:08 +0000497 // Emit a CheckComplexPat operation, which does the match (aborting if it
498 // fails) and pushes the matched operands onto the recorded nodes list.
499 AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
500 N->getName(), NextRecordedOperandNo));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000501
Chris Lattner57bf8a42010-03-04 01:23:08 +0000502 // Record the right number of operands.
503 NextRecordedOperandNo += CP.getNumOperands();
504 if (CP.hasProperty(SDNPHasChain)) {
505 // If the complex pattern has a chain, then we need to keep track of the
506 // fact that we just recorded a chain input. The chain input will be
507 // matched as the last operand of the predicate if it was successful.
508 ++NextRecordedOperandNo; // Chained node operand.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000509
Chris Lattner57bf8a42010-03-04 01:23:08 +0000510 // It is the last operand recorded.
511 assert(NextRecordedOperandNo > 1 &&
512 "Should have recorded input/result chains at least!");
513 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
514 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000515
Chris Lattner8950bca2010-12-23 17:03:20 +0000516 // TODO: Complex patterns can't have output glues, if they did, we'd want
Chris Lattner57bf8a42010-03-04 01:23:08 +0000517 // to record them.
518 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000519
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000520 return false;
Chris Lattnerda272d12010-02-15 08:04:42 +0000521}
522
523
Chris Lattnerb49985a2010-02-18 06:47:49 +0000524//===----------------------------------------------------------------------===//
525// Node Result Generation
526//===----------------------------------------------------------------------===//
527
Chris Lattner8e946be2010-02-21 03:22:59 +0000528void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
529 SmallVectorImpl<unsigned> &ResultOps){
530 assert(!N->getName().empty() && "Operand not named!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000531
Chris Lattner8e946be2010-02-21 03:22:59 +0000532 // A reference to a complex pattern gets all of the results of the complex
533 // pattern's match.
534 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
Chris Lattner57bf8a42010-03-04 01:23:08 +0000535 unsigned SlotNo = 0;
536 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i)
537 if (MatchedComplexPatterns[i].first->getName() == N->getName()) {
538 SlotNo = MatchedComplexPatterns[i].second;
539 break;
540 }
541 assert(SlotNo != 0 && "Didn't get a slot number assigned?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000542
Chris Lattner20df2422010-02-22 23:33:44 +0000543 // The first slot entry is the node itself, the subsequent entries are the
544 // matched values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000545 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Chris Lattner57bf8a42010-03-04 01:23:08 +0000546 ResultOps.push_back(SlotNo+i);
Chris Lattner8e946be2010-02-21 03:22:59 +0000547 return;
548 }
549
Chris Lattner57bf8a42010-03-04 01:23:08 +0000550 unsigned SlotNo = getNamedArgumentSlot(N->getName());
551
Chris Lattner8e946be2010-02-21 03:22:59 +0000552 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
553 // version of the immediate so that it doesn't get selected due to some other
554 // node use.
555 if (!N->isLeaf()) {
556 StringRef OperatorName = N->getOperator()->getName();
557 if (OperatorName == "imm" || OperatorName == "fpimm") {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000558 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000559 ResultOps.push_back(NextRecordedOperandNo++);
560 return;
561 }
562 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000563
Chris Lattner8e946be2010-02-21 03:22:59 +0000564 ResultOps.push_back(SlotNo);
565}
566
Chris Lattnerb49985a2010-02-18 06:47:49 +0000567void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000568 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattner845c0422010-02-18 22:03:03 +0000569 assert(N->isLeaf() && "Must be a leaf");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000570
Sean Silva6cfc8062012-10-10 20:24:43 +0000571 if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000572 AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getType(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000573 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000574 return;
575 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000576
Chris Lattner845c0422010-02-18 22:03:03 +0000577 // If this is an explicit register reference, handle it.
Sean Silva6cfc8062012-10-10 20:24:43 +0000578 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Owen Andersonbea6f612011-06-27 21:06:21 +0000579 Record *Def = DI->getDef();
580 if (Def->isSubClassOf("Register")) {
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +0000581 const CodeGenRegister *Reg =
Owen Andersonbea6f612011-06-27 21:06:21 +0000582 CGP.getTargetInfo().getRegBank().getReg(Def);
Jakob Stoklund Olesenabdbc842011-06-18 04:26:06 +0000583 AddMatcher(new EmitRegisterMatcher(Reg, N->getType(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000584 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000585 return;
586 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000587
Owen Andersonbea6f612011-06-27 21:06:21 +0000588 if (Def->getName() == "zero_reg") {
Chris Lattnerd7349192010-03-19 21:37:09 +0000589 AddMatcher(new EmitRegisterMatcher(0, N->getType(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000590 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000591 return;
592 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000593
Chris Lattner8e946be2010-02-21 03:22:59 +0000594 // Handle a reference to a register class. This is used
595 // in COPY_TO_SUBREG instructions.
Owen Andersonbea6f612011-06-27 21:06:21 +0000596 if (Def->isSubClassOf("RegisterOperand"))
597 Def = Def->getValueAsDef("RegClass");
598 if (Def->isSubClassOf("RegisterClass")) {
599 std::string Value = getQualifiedName(Def) + "RegClassID";
Chris Lattnerb21ba712010-02-25 02:04:40 +0000600 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
Chris Lattner8e946be2010-02-21 03:22:59 +0000601 ResultOps.push_back(NextRecordedOperandNo++);
602 return;
Chris Lattner845c0422010-02-18 22:03:03 +0000603 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +0000604
605 // Handle a subregister index. This is used for INSERT_SUBREG etc.
Owen Andersonbea6f612011-06-27 21:06:21 +0000606 if (Def->isSubClassOf("SubRegIndex")) {
607 std::string Value = getQualifiedName(Def);
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +0000608 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
609 ResultOps.push_back(NextRecordedOperandNo++);
610 return;
611 }
Chris Lattner845c0422010-02-18 22:03:03 +0000612 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000613
Chris Lattnerb49985a2010-02-18 06:47:49 +0000614 errs() << "unhandled leaf node: \n";
615 N->dump();
616}
617
Chris Lattner8e946be2010-02-21 03:22:59 +0000618/// GetInstPatternNode - Get the pattern for an instruction.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000619///
Chris Lattner8e946be2010-02-21 03:22:59 +0000620const TreePatternNode *MatcherGen::
621GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
622 const TreePattern *InstPat = Inst.getPattern();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000623
Chris Lattner8e946be2010-02-21 03:22:59 +0000624 // FIXME2?: Assume actual pattern comes before "implicit".
625 TreePatternNode *InstPatNode;
626 if (InstPat)
627 InstPatNode = InstPat->getTree(0);
628 else if (/*isRoot*/ N == Pattern.getDstPattern())
629 InstPatNode = Pattern.getSrcPattern();
630 else
631 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000632
Chris Lattner8e946be2010-02-21 03:22:59 +0000633 if (InstPatNode && !InstPatNode->isLeaf() &&
634 InstPatNode->getOperator()->getName() == "set")
635 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000636
Chris Lattner8e946be2010-02-21 03:22:59 +0000637 return InstPatNode;
638}
639
Cameron Zwarich3a2d2552011-05-19 21:13:30 +0000640static bool
641mayInstNodeLoadOrStore(const TreePatternNode *N,
642 const CodeGenDAGPatterns &CGP) {
643 Record *Op = N->getOperator();
644 const CodeGenTarget &CGT = CGP.getTargetInfo();
645 CodeGenInstruction &II = CGT.getInstruction(Op);
646 return II.mayLoad || II.mayStore;
647}
648
649static unsigned
650numNodesThatMayLoadOrStore(const TreePatternNode *N,
651 const CodeGenDAGPatterns &CGP) {
652 if (N->isLeaf())
653 return 0;
654
655 Record *OpRec = N->getOperator();
656 if (!OpRec->isSubClassOf("Instruction"))
657 return 0;
658
659 unsigned Count = 0;
660 if (mayInstNodeLoadOrStore(N, CGP))
661 ++Count;
662
663 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
664 Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
665
666 return Count;
667}
668
Chris Lattner8e946be2010-02-21 03:22:59 +0000669void MatcherGen::
670EmitResultInstructionAsOperand(const TreePatternNode *N,
671 SmallVectorImpl<unsigned> &OutputOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000672 Record *Op = N->getOperator();
673 const CodeGenTarget &CGT = CGP.getTargetInfo();
Chris Lattnerf30187a2010-03-19 00:07:20 +0000674 CodeGenInstruction &II = CGT.getInstruction(Op);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000675 const DAGInstruction &Inst = CGP.getInstruction(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000676
Chris Lattner8e946be2010-02-21 03:22:59 +0000677 // If we can, get the pattern for the instruction we're generating. We derive
678 // a variety of information from this pattern, such as whether it has a chain.
679 //
680 // FIXME2: This is extremely dubious for several reasons, not the least of
681 // which it gives special status to instructions with patterns that Pat<>
682 // nodes can't duplicate.
683 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
684
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000685 // NodeHasChain - Whether the instruction node we're creating takes chains.
Chris Lattner8e946be2010-02-21 03:22:59 +0000686 bool NodeHasChain = InstPatNode &&
687 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000688
Tim Northoverca578e72012-06-26 18:46:28 +0000689 // Instructions which load and store from memory should have a chain,
690 // regardless of whether they happen to have an internal pattern saying so.
691 if (Pattern.getSrcPattern()->TreeHasProperty(SDNPHasChain, CGP)
692 && (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad ||
693 II.hasSideEffects))
694 NodeHasChain = true;
695
Chris Lattner8e946be2010-02-21 03:22:59 +0000696 bool isRoot = N == Pattern.getDstPattern();
697
Chris Lattner8950bca2010-12-23 17:03:20 +0000698 // TreeHasOutGlue - True if this tree has glue.
699 bool TreeHasInGlue = false, TreeHasOutGlue = false;
Chris Lattner8e946be2010-02-21 03:22:59 +0000700 if (isRoot) {
701 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
Chris Lattner036609b2010-12-23 18:28:41 +0000702 TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
703 SrcPat->TreeHasProperty(SDNPInGlue, CGP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000704
Chris Lattner8e946be2010-02-21 03:22:59 +0000705 // FIXME2: this is checking the entire pattern, not just the node in
706 // question, doing this just for the root seems like a total hack.
Chris Lattner036609b2010-12-23 18:28:41 +0000707 TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
Chris Lattner8e946be2010-02-21 03:22:59 +0000708 }
709
710 // NumResults - This is the number of results produced by the instruction in
711 // the "outs" list.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000712 unsigned NumResults = Inst.getNumResults();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000713
Chris Lattnerb49985a2010-02-18 06:47:49 +0000714 // Loop over all of the operands of the instruction pattern, emitting code
715 // to fill them all in. The node 'N' usually has number children equal to
716 // the number of input operands of the instruction. However, in cases
717 // where there are predicate operands for an instruction, we need to fill
718 // in the 'execute always' values. Match up the node operands to the
719 // instruction operands to do this.
Chris Lattner8e946be2010-02-21 03:22:59 +0000720 SmallVector<unsigned, 8> InstOps;
Chris Lattnerc240bb02010-11-01 04:03:32 +0000721 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.Operands.size();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000722 InstOpNo != e; ++InstOpNo) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000723
Chris Lattnerb49985a2010-02-18 06:47:49 +0000724 // Determine what to emit for this operand.
Chris Lattnerc240bb02010-11-01 04:03:32 +0000725 Record *OperandNode = II.Operands[InstOpNo].Rec;
Tom Stellard6d3d7652012-09-06 14:15:52 +0000726 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattnerb49985a2010-02-18 06:47:49 +0000727 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
728 // This is a predicate or optional def operand; emit the
729 // 'default ops' operands.
Eric Christopherae321ed2010-08-10 23:46:20 +0000730 const DAGDefaultOperand &DefaultOp
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000731 = CGP.getDefaultOperand(OperandNode);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000732 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
Chris Lattner8e946be2010-02-21 03:22:59 +0000733 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000734 continue;
735 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000736
Chris Lattner0be6fe72010-03-27 19:15:02 +0000737 const TreePatternNode *Child = N->getChild(ChildNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000738
Chris Lattnerb49985a2010-02-18 06:47:49 +0000739 // Otherwise this is a normal operand or a predicate operand without
740 // 'execute always'; emit it.
Chris Lattner0be6fe72010-03-27 19:15:02 +0000741 unsigned BeforeAddingNumOps = InstOps.size();
742 EmitResultOperand(Child, InstOps);
743 assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000744
Chris Lattner0be6fe72010-03-27 19:15:02 +0000745 // If the operand is an instruction and it produced multiple results, just
746 // take the first one.
747 if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
748 InstOps.resize(BeforeAddingNumOps+1);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000749
Chris Lattnerb49985a2010-02-18 06:47:49 +0000750 ++ChildNo;
751 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000752
Chris Lattner8950bca2010-12-23 17:03:20 +0000753 // If this node has input glue or explicitly specified input physregs, we
754 // need to add chained and glued copyfromreg nodes and materialize the glue
Chris Lattner8e946be2010-02-21 03:22:59 +0000755 // input.
756 if (isRoot && !PhysRegInputs.empty()) {
757 // Emit all of the CopyToReg nodes for the input physical registers. These
758 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
759 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000760 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
Chris Lattner92879532010-03-18 23:57:40 +0000761 PhysRegInputs[i].first));
Chris Lattner8950bca2010-12-23 17:03:20 +0000762 // Even if the node has no other glue inputs, the resultant node must be
763 // glued to the CopyFromReg nodes we just generated.
764 TreeHasInGlue = true;
Chris Lattner8e946be2010-02-21 03:22:59 +0000765 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000766
Chris Lattner8950bca2010-12-23 17:03:20 +0000767 // Result order: node results, chain, glue
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000768
Chris Lattner8e946be2010-02-21 03:22:59 +0000769 // Determine the result types.
770 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
Chris Lattner0be6fe72010-03-27 19:15:02 +0000771 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
772 ResultVTs.push_back(N->getType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000773
Chris Lattner8e946be2010-02-21 03:22:59 +0000774 // If this is the root instruction of a pattern that has physical registers in
775 // its result pattern, add output VTs for them. For example, X86 has:
776 // (set AL, (mul ...))
777 // This also handles implicit results like:
778 // (implicit EFLAGS)
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000779 if (isRoot && !Pattern.getDstRegs().empty()) {
Chris Lattner92879532010-03-18 23:57:40 +0000780 // If the root came from an implicit def in the instruction handling stuff,
781 // don't re-add it.
782 Record *HandledReg = 0;
Chris Lattner9414ae52010-03-27 20:09:24 +0000783 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
Chris Lattner92879532010-03-18 23:57:40 +0000784 HandledReg = II.ImplicitDefs[0];
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000785
Chris Lattner92879532010-03-18 23:57:40 +0000786 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
787 Record *Reg = Pattern.getDstRegs()[i];
788 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
789 ResultVTs.push_back(getRegisterValueType(Reg, CGT));
790 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000791 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000792
Chris Lattner1e506312010-03-19 05:34:15 +0000793 // If this is the root of the pattern and the pattern we're matching includes
794 // a node that is variadic, mark the generated node as variadic so that it
795 // gets the excess operands from the input DAG.
Chris Lattner8e946be2010-02-21 03:22:59 +0000796 int NumFixedArityOperands = -1;
Chris Lattner1e506312010-03-19 05:34:15 +0000797 if (isRoot &&
798 (Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP)))
Chris Lattner8e946be2010-02-21 03:22:59 +0000799 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000800
Cameron Zwarich3a2d2552011-05-19 21:13:30 +0000801 // If this is the root node and multiple matched nodes in the input pattern
802 // have MemRefs in them, have the interpreter collect them and plop them onto
803 // this node. If there is just one node with MemRefs, leave them on that node
804 // even if it is not the root.
Chris Lattner8e946be2010-02-21 03:22:59 +0000805 //
Cameron Zwarich3a2d2552011-05-19 21:13:30 +0000806 // FIXME3: This is actively incorrect for result patterns with multiple
807 // memory-referencing instructions.
808 bool PatternHasMemOperands =
809 Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
810
811 bool NodeHasMemRefs = false;
812 if (PatternHasMemOperands) {
813 unsigned NumNodesThatLoadOrStore =
814 numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
815 bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
816 NumNodesThatLoadOrStore == 1;
817 NodeHasMemRefs =
818 NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
819 NumNodesThatLoadOrStore != 1));
820 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000821
Chris Lattner8950bca2010-12-23 17:03:20 +0000822 assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
Chris Lattner0be6fe72010-03-27 19:15:02 +0000823 "Node has no result");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000824
Chris Lattnerb21ba712010-02-25 02:04:40 +0000825 AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
Chris Lattnere86097a2010-02-28 02:31:26 +0000826 ResultVTs.data(), ResultVTs.size(),
827 InstOps.data(), InstOps.size(),
Chris Lattner8950bca2010-12-23 17:03:20 +0000828 NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
Chris Lattner6281cda2010-02-28 02:41:25 +0000829 NodeHasMemRefs, NumFixedArityOperands,
830 NextRecordedOperandNo));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000831
Chris Lattner8950bca2010-12-23 17:03:20 +0000832 // The non-chain and non-glue results of the newly emitted node get recorded.
Chris Lattner565a6f92010-02-21 23:54:05 +0000833 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000834 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
Chris Lattner77f2e272010-02-21 06:03:07 +0000835 OutputOps.push_back(NextRecordedOperandNo++);
Chris Lattner565a6f92010-02-21 23:54:05 +0000836 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000837}
838
839void MatcherGen::
840EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
841 SmallVectorImpl<unsigned> &ResultOps) {
842 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
843
844 // Emit the operand.
845 SmallVector<unsigned, 8> InputOps;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000846
Chris Lattner8e946be2010-02-21 03:22:59 +0000847 // FIXME2: Could easily generalize this to support multiple inputs and outputs
848 // to the SDNodeXForm. For now we just support one input and one output like
849 // the old instruction selector.
850 assert(N->getNumChildren() == 1);
851 EmitResultOperand(N->getChild(0), InputOps);
852
853 // The input currently must have produced exactly one result.
854 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
855
Chris Lattnerb21ba712010-02-25 02:04:40 +0000856 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
Chris Lattner8e946be2010-02-21 03:22:59 +0000857 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000858}
859
860void MatcherGen::EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000861 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000862 // This is something selected from the pattern we matched.
Chris Lattner8e946be2010-02-21 03:22:59 +0000863 if (!N->getName().empty())
864 return EmitResultOfNamedOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000865
866 if (N->isLeaf())
867 return EmitResultLeafAsOperand(N, ResultOps);
868
869 Record *OpRec = N->getOperator();
870 if (OpRec->isSubClassOf("Instruction"))
871 return EmitResultInstructionAsOperand(N, ResultOps);
872 if (OpRec->isSubClassOf("SDNodeXForm"))
Chris Lattner8e946be2010-02-21 03:22:59 +0000873 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000874 errs() << "Unknown result node to emit code for: " << *N << '\n';
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000875 PrintFatalError("Unknown node in result pattern!");
Chris Lattnerb49985a2010-02-18 06:47:49 +0000876}
877
878void MatcherGen::EmitResultCode() {
Chris Lattner01bcd942010-03-01 22:46:42 +0000879 // Patterns that match nodes with (potentially multiple) chain inputs have to
880 // merge them together into a token factor. This informs the generated code
881 // what all the chained nodes are.
882 if (!MatchedChainNodes.empty())
883 AddMatcher(new EmitMergeInputChainsMatcher
884 (MatchedChainNodes.data(), MatchedChainNodes.size()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000885
Chris Lattner565a6f92010-02-21 23:54:05 +0000886 // Codegen the root of the result pattern, capturing the resulting values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000887 SmallVector<unsigned, 8> Ops;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000888 EmitResultOperand(Pattern.getDstPattern(), Ops);
Chris Lattner8e946be2010-02-21 03:22:59 +0000889
Chris Lattner565a6f92010-02-21 23:54:05 +0000890 // At this point, we have however many values the result pattern produces.
891 // However, the input pattern might not need all of these. If there are
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000892 // excess values at the end (such as implicit defs of condition codes etc)
Chris Lattner8950bca2010-12-23 17:03:20 +0000893 // just lop them off. This doesn't need to worry about glue or chains, just
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000894 // explicit results.
Chris Lattner565a6f92010-02-21 23:54:05 +0000895 //
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000896 unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000897
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000898 // If the pattern also has (implicit) results, count them as well.
899 if (!Pattern.getDstRegs().empty()) {
900 // If the root came from an implicit def in the instruction handling stuff,
901 // don't re-add it.
902 Record *HandledReg = 0;
903 const TreePatternNode *DstPat = Pattern.getDstPattern();
904 if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
905 const CodeGenTarget &CGT = CGP.getTargetInfo();
906 CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
907
908 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
909 HandledReg = II.ImplicitDefs[0];
910 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000911
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000912 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
913 Record *Reg = Pattern.getDstRegs()[i];
914 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
915 ++NumSrcResults;
916 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000917 }
918
Chris Lattner565a6f92010-02-21 23:54:05 +0000919 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
920 Ops.resize(NumSrcResults);
Chris Lattner02f73582010-02-24 05:33:42 +0000921
Chris Lattner8950bca2010-12-23 17:03:20 +0000922 // If the matched pattern covers nodes which define a glue result, emit a node
Chris Lattner02f73582010-02-24 05:33:42 +0000923 // that tells the matcher about them so that it can update their results.
Chris Lattner8950bca2010-12-23 17:03:20 +0000924 if (!MatchedGlueResultNodes.empty())
925 AddMatcher(new MarkGlueResultsMatcher(MatchedGlueResultNodes.data(),
926 MatchedGlueResultNodes.size()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000927
Chris Lattnerb21ba712010-02-25 02:04:40 +0000928 AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
Chris Lattnerb49985a2010-02-18 06:47:49 +0000929}
930
931
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000932/// ConvertPatternToMatcher - Create the matcher for the specified pattern with
933/// the specified variant. If the variant number is invalid, this returns null.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000934Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000935 unsigned Variant,
Chris Lattnerc78f2a32010-02-28 20:49:53 +0000936 const CodeGenDAGPatterns &CGP) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000937 MatcherGen Gen(Pattern, CGP);
938
939 // Generate the code for the matcher.
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000940 if (Gen.EmitMatcherCode(Variant))
941 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000942
Chris Lattner8e946be2010-02-21 03:22:59 +0000943 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
944 // FIXME2: Split result code out to another table, and make the matcher end
945 // with an "Emit <index>" command. This allows result generation stuff to be
946 // shared and factored?
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000947
Chris Lattnerda272d12010-02-15 08:04:42 +0000948 // If the match succeeds, then we generate Pattern.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000949 Gen.EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +0000950
951 // Unconditional match.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000952 return Gen.GetMatcher();
Chris Lattnerda272d12010-02-15 08:04:42 +0000953}