blob: 402a239ec5512e973dc251137950688537e8c4a7 [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"
Chris Lattnerda272d12010-02-15 08:04:42 +000013#include "Record.h"
Jim Grosbach4a6d7352011-03-11 02:19:02 +000014#include "llvm/ADT/DenseMap.h"
Chris Lattner785d16f2010-02-17 02:16:19 +000015#include "llvm/ADT/SmallVector.h"
Chris Lattnerda272d12010-02-15 08:04:42 +000016#include "llvm/ADT/StringMap.h"
Chris Lattner8e946be2010-02-21 03:22:59 +000017#include <utility>
Chris Lattnerda272d12010-02-15 08:04:42 +000018using namespace llvm;
19
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000020
Chris Lattner8e946be2010-02-21 03:22:59 +000021/// getRegisterValueType - Look up and return the ValueType of the specified
22/// register. If the register is a member of multiple register classes which
23/// have different associated types, return MVT::Other.
24static MVT::SimpleValueType getRegisterValueType(Record *R,
25 const CodeGenTarget &T) {
26 bool FoundRC = false;
27 MVT::SimpleValueType VT = MVT::Other;
28 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
29 std::vector<Record*>::const_iterator Element;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000030
Chris Lattner8e946be2010-02-21 03:22:59 +000031 for (unsigned rc = 0, e = RCs.size(); rc != e; ++rc) {
32 const CodeGenRegisterClass &RC = RCs[rc];
33 if (!std::count(RC.Elements.begin(), RC.Elements.end(), R))
34 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000035
Chris Lattner8e946be2010-02-21 03:22:59 +000036 if (!FoundRC) {
37 FoundRC = true;
38 VT = RC.getValueTypeNum(0);
39 continue;
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000040 }
Chris Lattner67ea6a72010-03-01 22:49:06 +000041
42 // If this occurs in multiple register classes, they all have to agree.
43 assert(VT == RC.getValueTypeNum(0));
Chris Lattner8e946be2010-02-21 03:22:59 +000044 }
45 return VT;
46}
47
48
49namespace {
Chris Lattnerda272d12010-02-15 08:04:42 +000050 class MatcherGen {
51 const PatternToMatch &Pattern;
52 const CodeGenDAGPatterns &CGP;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000053
Chris Lattnerda272d12010-02-15 08:04:42 +000054 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
55 /// out with all of the types removed. This allows us to insert type checks
56 /// as we scan the tree.
57 TreePatternNode *PatWithNoTypes;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000058
Chris Lattnerda272d12010-02-15 08:04:42 +000059 /// VariableMap - A map from variable names ('$dst') to the recorded operand
60 /// number that they were captured as. These are biased by 1 to make
61 /// insertion easier.
62 StringMap<unsigned> VariableMap;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000063
Chris Lattnerc94fa4c2010-02-19 00:27:40 +000064 /// NextRecordedOperandNo - As we emit opcodes to record matched values in
65 /// the RecordedNodes array, this keeps track of which slot will be next to
66 /// record into.
Chris Lattnerda272d12010-02-15 08:04:42 +000067 unsigned NextRecordedOperandNo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000068
Chris Lattner8e946be2010-02-21 03:22:59 +000069 /// MatchedChainNodes - This maintains the position in the recorded nodes
70 /// array of all of the recorded input nodes that have chains.
71 SmallVector<unsigned, 2> MatchedChainNodes;
Chris Lattner02f73582010-02-24 05:33:42 +000072
Chris Lattner8950bca2010-12-23 17:03:20 +000073 /// MatchedGlueResultNodes - This maintains the position in the recorded
74 /// nodes array of all of the recorded input nodes that have glue results.
75 SmallVector<unsigned, 2> MatchedGlueResultNodes;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000076
Chris Lattner57bf8a42010-03-04 01:23:08 +000077 /// MatchedComplexPatterns - This maintains a list of all of the
78 /// ComplexPatterns that we need to check. The patterns are known to have
79 /// names which were recorded. The second element of each pair is the first
80 /// slot number that the OPC_CheckComplexPat opcode drops the matched
81 /// results into.
82 SmallVector<std::pair<const TreePatternNode*,
83 unsigned>, 2> MatchedComplexPatterns;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000084
Chris Lattner8e946be2010-02-21 03:22:59 +000085 /// PhysRegInputs - List list has an entry for each explicitly specified
86 /// physreg input to the pattern. The first elt is the Register node, the
87 /// second is the recorded slot number the input pattern match saved it in.
88 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000089
Chris Lattner785d16f2010-02-17 02:16:19 +000090 /// Matcher - This is the top level of the generated matcher, the result.
Chris Lattnerb21ba712010-02-25 02:04:40 +000091 Matcher *TheMatcher;
Jim Grosbachfbadcd02010-12-21 16:16:00 +000092
Chris Lattner785d16f2010-02-17 02:16:19 +000093 /// CurPredicate - As we emit matcher nodes, this points to the latest check
Chris Lattnerbd8227f2010-02-18 02:53:41 +000094 /// which should have future checks stuck into its Next position.
Chris Lattnerb21ba712010-02-25 02:04:40 +000095 Matcher *CurPredicate;
Jim Grosbach4a6d7352011-03-11 02:19:02 +000096
97 /// RegisterDefMap - A map of register record definitions to the
98 /// corresponding target CodeGenRegister entry.
99 DenseMap<const Record *, const CodeGenRegister *> RegisterDefMap;
Chris Lattnerda272d12010-02-15 08:04:42 +0000100 public:
101 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000102
Chris Lattnerda272d12010-02-15 08:04:42 +0000103 ~MatcherGen() {
104 delete PatWithNoTypes;
105 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000106
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000107 bool EmitMatcherCode(unsigned Variant);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000108 void EmitResultCode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000109
Chris Lattnerb21ba712010-02-25 02:04:40 +0000110 Matcher *GetMatcher() const { return TheMatcher; }
Chris Lattnerda272d12010-02-15 08:04:42 +0000111 private:
Chris Lattnerb21ba712010-02-25 02:04:40 +0000112 void AddMatcher(Matcher *NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000113 void InferPossibleTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000114
Chris Lattnerb49985a2010-02-18 06:47:49 +0000115 // Matcher Generation.
Chris Lattnerda272d12010-02-15 08:04:42 +0000116 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
117 void EmitLeafMatchCode(const TreePatternNode *N);
118 void EmitOperatorMatchCode(const TreePatternNode *N,
119 TreePatternNode *NodeNoTypes);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000120
Chris Lattnerb49985a2010-02-18 06:47:49 +0000121 // Result Code Generation.
Chris Lattner8e946be2010-02-21 03:22:59 +0000122 unsigned getNamedArgumentSlot(StringRef Name) {
123 unsigned VarMapEntry = VariableMap[Name];
124 assert(VarMapEntry != 0 &&
125 "Variable referenced but not defined and not caught earlier!");
126 return VarMapEntry-1;
127 }
128
129 /// GetInstPatternNode - Get the pattern for an instruction.
130 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
131 const TreePatternNode *N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000132
Chris Lattnerb49985a2010-02-18 06:47:49 +0000133 void EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000134 SmallVectorImpl<unsigned> &ResultOps);
135 void EmitResultOfNamedOperand(const TreePatternNode *N,
136 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000137 void EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000138 SmallVectorImpl<unsigned> &ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000139 void EmitResultInstructionAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000140 SmallVectorImpl<unsigned> &ResultOps);
141 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
142 SmallVectorImpl<unsigned> &ResultOps);
143 };
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000144
Chris Lattnerda272d12010-02-15 08:04:42 +0000145} // end anon namespace.
146
147MatcherGen::MatcherGen(const PatternToMatch &pattern,
148 const CodeGenDAGPatterns &cgp)
Chris Lattner853b9192010-02-19 00:33:13 +0000149: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
Chris Lattner01bcd942010-03-01 22:46:42 +0000150 TheMatcher(0), CurPredicate(0) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000151 // We need to produce the matcher tree for the patterns source pattern. To do
152 // this we need to match the structure as well as the types. To do the type
153 // matching, we want to figure out the fewest number of type checks we need to
154 // emit. For example, if there is only one integer type supported by a
155 // target, there should be no type comparisons at all for integer patterns!
156 //
157 // To figure out the fewest number of type checks needed, clone the pattern,
158 // remove the types, then perform type inference on the pattern as a whole.
159 // If there are unresolved types, emit an explicit check for those types,
160 // apply the type to the tree, then rerun type inference. Iterate until all
161 // types are resolved.
162 //
163 PatWithNoTypes = Pattern.getSrcPattern()->clone();
164 PatWithNoTypes->RemoveAllTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000165
Chris Lattnerda272d12010-02-15 08:04:42 +0000166 // If there are types that are manifestly known, infer them.
167 InferPossibleTypes();
Jim Grosbach4a6d7352011-03-11 02:19:02 +0000168
169 // Populate the map from records to CodeGenRegister entries.
170 const CodeGenTarget &CGT = CGP.getTargetInfo();
171 const std::vector<CodeGenRegister> &Registers = CGT.getRegisters();
172 for (unsigned i = 0, e = Registers.size(); i != e; ++i)
173 RegisterDefMap[Registers[i].TheDef] = &Registers[i];
Chris Lattnerda272d12010-02-15 08:04:42 +0000174}
175
176/// InferPossibleTypes - As we emit the pattern, we end up generating type
177/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we
178/// want to propagate implied types as far throughout the tree as possible so
179/// that we avoid doing redundant type checks. This does the type propagation.
180void MatcherGen::InferPossibleTypes() {
181 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
182 // diagnostics, which we know are impossible at this point.
183 TreePattern &TP = *CGP.pf_begin()->second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000184
Chris Lattnerda272d12010-02-15 08:04:42 +0000185 try {
186 bool MadeChange = true;
187 while (MadeChange)
188 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
189 true/*Ignore reg constraints*/);
190 } catch (...) {
191 errs() << "Type constraint application shouldn't fail!";
192 abort();
193 }
194}
195
196
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000197/// AddMatcher - Add a matcher node to the current graph we're building.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000198void MatcherGen::AddMatcher(Matcher *NewNode) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000199 if (CurPredicate != 0)
Chris Lattnerbd8227f2010-02-18 02:53:41 +0000200 CurPredicate->setNext(NewNode);
Chris Lattnerda272d12010-02-15 08:04:42 +0000201 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000202 TheMatcher = NewNode;
Chris Lattnerda272d12010-02-15 08:04:42 +0000203 CurPredicate = NewNode;
204}
205
206
Chris Lattnerb49985a2010-02-18 06:47:49 +0000207//===----------------------------------------------------------------------===//
208// Pattern Match Generation
209//===----------------------------------------------------------------------===//
Chris Lattnerda272d12010-02-15 08:04:42 +0000210
211/// EmitLeafMatchCode - Generate matching code for leaf nodes.
212void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
213 assert(N->isLeaf() && "Not a leaf?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000214
Chris Lattnerda272d12010-02-15 08:04:42 +0000215 // Direct match against an integer constant.
Chris Lattnerbd8965a2010-03-01 07:27:07 +0000216 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
217 // If this is the root of the dag we're matching, we emit a redundant opcode
218 // check to ensure that this gets folded into the normal top-level
219 // OpcodeSwitch.
220 if (N == Pattern.getSrcPattern()) {
221 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
222 AddMatcher(new CheckOpcodeMatcher(NI));
223 }
224
Chris Lattnerb21ba712010-02-25 02:04:40 +0000225 return AddMatcher(new CheckIntegerMatcher(II->getValue()));
Chris Lattnerbd8965a2010-03-01 07:27:07 +0000226 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000227
Chris Lattnerda272d12010-02-15 08:04:42 +0000228 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
229 if (DI == 0) {
230 errs() << "Unknown leaf kind: " << *DI << "\n";
231 abort();
232 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000233
Chris Lattnerda272d12010-02-15 08:04:42 +0000234 Record *LeafRec = DI->getDef();
235 if (// Handle register references. Nothing to do here, they always match.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000236 LeafRec->isSubClassOf("RegisterClass") ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000237 LeafRec->isSubClassOf("PointerLikeRegClass") ||
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +0000238 LeafRec->isSubClassOf("SubRegIndex") ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000239 // Place holder for SRCVALUE nodes. Nothing to do here.
240 LeafRec->getName() == "srcvalue")
241 return;
Chris Lattner8e946be2010-02-21 03:22:59 +0000242
243 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000244 // record the register
Chris Lattner8e946be2010-02-21 03:22:59 +0000245 if (LeafRec->isSubClassOf("Register")) {
Chris Lattner0cebe612010-03-01 02:24:17 +0000246 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(),
247 NextRecordedOperandNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000248 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
249 return;
250 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000251
Chris Lattnerda272d12010-02-15 08:04:42 +0000252 if (LeafRec->isSubClassOf("ValueType"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000253 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000254
Chris Lattnerda272d12010-02-15 08:04:42 +0000255 if (LeafRec->isSubClassOf("CondCode"))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000256 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000257
Chris Lattnerda272d12010-02-15 08:04:42 +0000258 if (LeafRec->isSubClassOf("ComplexPattern")) {
Chris Lattnerc2676b22010-02-17 00:11:30 +0000259 // We can't model ComplexPattern uses that don't have their name taken yet.
260 // The OPC_CheckComplexPattern operation implicitly records the results.
261 if (N->getName().empty()) {
Chris Lattner53a2f602010-02-16 23:16:25 +0000262 errs() << "We expect complex pattern uses to have names: " << *N << "\n";
263 exit(1);
264 }
Chris Lattner1f2ed5f2010-02-22 22:18:05 +0000265
Chris Lattner57bf8a42010-03-04 01:23:08 +0000266 // Remember this ComplexPattern so that we can emit it after all the other
267 // structural matches are done.
268 MatchedComplexPatterns.push_back(std::make_pair(N, 0));
Chris Lattner8dc4f2b2010-02-17 06:08:25 +0000269 return;
Chris Lattnerda272d12010-02-15 08:04:42 +0000270 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000271
Chris Lattnerda272d12010-02-15 08:04:42 +0000272 errs() << "Unknown leaf kind: " << *N << "\n";
273 abort();
274}
275
276void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
277 TreePatternNode *NodeNoTypes) {
278 assert(!N->isLeaf() && "Not an operator?");
279 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000280
Chris Lattnerda272d12010-02-15 08:04:42 +0000281 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
282 // a constant without a predicate fn that has more that one bit set, handle
283 // this as a special case. This is usually for targets that have special
284 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
285 // handling stuff). Using these instructions is often far more efficient
286 // than materializing the constant. Unfortunately, both the instcombiner
287 // and the dag combiner can often infer that bits are dead, and thus drop
288 // them from the mask in the dag. For example, it might turn 'AND X, 255'
289 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
290 // to handle this.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000291 if ((N->getOperator()->getName() == "and" ||
Chris Lattnerda272d12010-02-15 08:04:42 +0000292 N->getOperator()->getName() == "or") &&
Chris Lattner8e946be2010-02-21 03:22:59 +0000293 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
294 N->getPredicateFns().empty()) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000295 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
296 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
Chris Lattnere9eeda82010-03-01 02:15:34 +0000297 // If this is at the root of the pattern, we emit a redundant
298 // CheckOpcode so that the following checks get factored properly under
299 // a single opcode check.
300 if (N == Pattern.getSrcPattern())
301 AddMatcher(new CheckOpcodeMatcher(CInfo));
302
303 // Emit the CheckAndImm/CheckOrImm node.
Chris Lattnerda272d12010-02-15 08:04:42 +0000304 if (N->getOperator()->getName() == "and")
Chris Lattnerb21ba712010-02-25 02:04:40 +0000305 AddMatcher(new CheckAndImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000306 else
Chris Lattnerb21ba712010-02-25 02:04:40 +0000307 AddMatcher(new CheckOrImmMatcher(II->getValue()));
Chris Lattnerda272d12010-02-15 08:04:42 +0000308
309 // Match the LHS of the AND as appropriate.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000310 AddMatcher(new MoveChildMatcher(0));
Chris Lattnerda272d12010-02-15 08:04:42 +0000311 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000312 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000313 return;
314 }
315 }
316 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000317
Chris Lattnerda272d12010-02-15 08:04:42 +0000318 // Check that the current opcode lines up.
Chris Lattnera230f962010-02-27 21:48:43 +0000319 AddMatcher(new CheckOpcodeMatcher(CInfo));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000320
Chris Lattner8e946be2010-02-21 03:22:59 +0000321 // If this node has memory references (i.e. is a load or store), tell the
322 // interpreter to capture them in the memref array.
323 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattnerb21ba712010-02-25 02:04:40 +0000324 AddMatcher(new RecordMemRefMatcher());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000325
Chris Lattnerda272d12010-02-15 08:04:42 +0000326 // If this node has a chain, then the chain is operand #0 is the SDNode, and
327 // the child numbers of the node are all offset by one.
328 unsigned OpNo = 0;
Chris Lattner6bc1b512010-02-16 19:19:58 +0000329 if (N->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000330 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000331 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner0cebe612010-03-01 02:24:17 +0000332 "' chained node",
333 NextRecordedOperandNo));
Chris Lattner785d16f2010-02-17 02:16:19 +0000334 // Remember all of the input chains our pattern will match.
Chris Lattner8e946be2010-02-21 03:22:59 +0000335 MatchedChainNodes.push_back(NextRecordedOperandNo++);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000336
Chris Lattner2f7ecde2010-02-17 01:34:15 +0000337 // Don't look at the input chain when matching the tree pattern to the
338 // SDNode.
Chris Lattnerda272d12010-02-15 08:04:42 +0000339 OpNo = 1;
340
Chris Lattner6bc1b512010-02-16 19:19:58 +0000341 // If this node is not the root and the subtree underneath it produces a
342 // chain, then the result of matching the node is also produce a chain.
343 // Beyond that, this means that we're also folding (at least) the root node
344 // into the node that produce the chain (for example, matching
345 // "(add reg, (load ptr))" as a add_with_memory on X86). This is
346 // problematic, if the 'reg' node also uses the load (say, its chain).
347 // Graphically:
348 //
349 // [LD]
350 // ^ ^
351 // | \ DAG's like cheese.
352 // / |
353 // / [YY]
354 // | ^
355 // [XX]--/
356 //
357 // It would be invalid to fold XX and LD. In this case, folding the two
358 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
359 // To prevent this, we emit a dynamic check for legality before allowing
360 // this to be folded.
361 //
362 const TreePatternNode *Root = Pattern.getSrcPattern();
363 if (N != Root) { // Not the root of the pattern.
Chris Lattnere39650a2010-02-16 06:10:58 +0000364 // If there is a node between the root and this node, then we definitely
365 // need to emit the check.
366 bool NeedCheck = !Root->hasChild(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000367
Chris Lattnere39650a2010-02-16 06:10:58 +0000368 // If it *is* an immediate child of the root, we can still need a check if
369 // the root SDNode has multiple inputs. For us, this means that it is an
370 // intrinsic, has multiple operands, or has other inputs like chain or
Chris Lattner8950bca2010-12-23 17:03:20 +0000371 // glue).
Chris Lattnere39650a2010-02-16 06:10:58 +0000372 if (!NeedCheck) {
373 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
374 NeedCheck =
375 Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
376 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
377 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
378 PInfo.getNumOperands() > 1 ||
379 PInfo.hasProperty(SDNPHasChain) ||
Chris Lattner036609b2010-12-23 18:28:41 +0000380 PInfo.hasProperty(SDNPInGlue) ||
381 PInfo.hasProperty(SDNPOptInGlue);
Chris Lattnere39650a2010-02-16 06:10:58 +0000382 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000383
Chris Lattnere39650a2010-02-16 06:10:58 +0000384 if (NeedCheck)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000385 AddMatcher(new CheckFoldableChainNodeMatcher());
Chris Lattnere39650a2010-02-16 06:10:58 +0000386 }
Chris Lattnerda272d12010-02-15 08:04:42 +0000387 }
Chris Lattner02f73582010-02-24 05:33:42 +0000388
Chris Lattner8950bca2010-12-23 17:03:20 +0000389 // If this node has an output glue and isn't the root, remember it.
Chris Lattner036609b2010-12-23 18:28:41 +0000390 if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
Chris Lattner02f73582010-02-24 05:33:42 +0000391 N != Pattern.getSrcPattern()) {
Chris Lattner8950bca2010-12-23 17:03:20 +0000392 // TODO: This redundantly records nodes with both glues and chains.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000393
Chris Lattner02f73582010-02-24 05:33:42 +0000394 // Record the node and remember it in our chained nodes list.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000395 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
Chris Lattner8950bca2010-12-23 17:03:20 +0000396 "' glue output node",
Chris Lattner0cebe612010-03-01 02:24:17 +0000397 NextRecordedOperandNo));
Chris Lattner8950bca2010-12-23 17:03:20 +0000398 // Remember all of the nodes with output glue our pattern will match.
399 MatchedGlueResultNodes.push_back(NextRecordedOperandNo++);
Chris Lattner02f73582010-02-24 05:33:42 +0000400 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000401
Chris Lattner8950bca2010-12-23 17:03:20 +0000402 // If this node is known to have an input glue or if it *might* have an input
403 // glue, capture it as the glue input of the pattern.
Chris Lattner036609b2010-12-23 18:28:41 +0000404 if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
405 N->NodeHasProperty(SDNPInGlue, CGP))
Chris Lattner8950bca2010-12-23 17:03:20 +0000406 AddMatcher(new CaptureGlueInputMatcher());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000407
Chris Lattnerda272d12010-02-15 08:04:42 +0000408 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
409 // Get the code suitable for matching this child. Move to the child, check
410 // it then move back to the parent.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000411 AddMatcher(new MoveChildMatcher(OpNo));
Chris Lattnerda272d12010-02-15 08:04:42 +0000412 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
Chris Lattnerb21ba712010-02-25 02:04:40 +0000413 AddMatcher(new MoveParentMatcher());
Chris Lattnerda272d12010-02-15 08:04:42 +0000414 }
415}
416
417
418void MatcherGen::EmitMatchCode(const TreePatternNode *N,
419 TreePatternNode *NodeNoTypes) {
420 // If N and NodeNoTypes don't agree on a type, then this is a case where we
421 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and
422 // reinfer any correlated types.
Chris Lattner084df622010-03-24 00:41:19 +0000423 SmallVector<unsigned, 2> ResultsToTypeCheck;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000424
Chris Lattner084df622010-03-24 00:41:19 +0000425 for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
426 if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
427 NodeNoTypes->setType(i, N->getExtType(i));
Chris Lattnerda272d12010-02-15 08:04:42 +0000428 InferPossibleTypes();
Chris Lattner084df622010-03-24 00:41:19 +0000429 ResultsToTypeCheck.push_back(i);
Chris Lattnerda272d12010-02-15 08:04:42 +0000430 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000431
Chris Lattnerda272d12010-02-15 08:04:42 +0000432 // If this node has a name associated with it, capture it in VariableMap. If
433 // we already saw this in the pattern, emit code to verify dagness.
434 if (!N->getName().empty()) {
435 unsigned &VarMapEntry = VariableMap[N->getName()];
436 if (VarMapEntry == 0) {
Chris Lattner20df2422010-02-22 23:33:44 +0000437 // If it is a named node, we must emit a 'Record' opcode.
Chris Lattner0cebe612010-03-01 02:24:17 +0000438 AddMatcher(new RecordMatcher("$" + N->getName(), NextRecordedOperandNo));
Chris Lattner20df2422010-02-22 23:33:44 +0000439 VarMapEntry = ++NextRecordedOperandNo;
Chris Lattnerda272d12010-02-15 08:04:42 +0000440 } else {
441 // If we get here, this is a second reference to a specific name. Since
442 // we already have checked that the first reference is valid, we don't
443 // have to recursively match it, just check that it's the same as the
444 // previously named thing.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000445 AddMatcher(new CheckSameMatcher(VarMapEntry-1));
Chris Lattnerda272d12010-02-15 08:04:42 +0000446 return;
447 }
448 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000449
Chris Lattnerda272d12010-02-15 08:04:42 +0000450 if (N->isLeaf())
451 EmitLeafMatchCode(N);
452 else
453 EmitOperatorMatchCode(N, NodeNoTypes);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000454
Chris Lattner6fd326b2010-03-07 07:20:49 +0000455 // If there are node predicates for this node, generate their checks.
456 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
457 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000458
Chris Lattner084df622010-03-24 00:41:19 +0000459 for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
460 AddMatcher(new CheckTypeMatcher(N->getType(ResultsToTypeCheck[i]),
461 ResultsToTypeCheck[i]));
Chris Lattnerda272d12010-02-15 08:04:42 +0000462}
463
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000464/// EmitMatcherCode - Generate the code that matches the predicate of this
465/// pattern for the specified Variant. If the variant is invalid this returns
466/// true and does not generate code, if it is valid, it returns false.
467bool MatcherGen::EmitMatcherCode(unsigned Variant) {
468 // If the root of the pattern is a ComplexPattern and if it is specified to
469 // match some number of root opcodes, these are considered to be our variants.
470 // Depending on which variant we're generating code for, emit the root opcode
471 // check.
472 if (const ComplexPattern *CP =
473 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000474 const std::vector<Record*> &OpNodes = CP->getRootNodes();
Chris Lattner405f1252010-03-01 22:29:19 +0000475 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
476 if (Variant >= OpNodes.size()) return true;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000477
Chris Lattner405f1252010-03-01 22:29:19 +0000478 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000479 } else {
480 if (Variant != 0) return true;
481 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000482
Chris Lattner9752fb12010-03-04 01:25:36 +0000483 // Emit the matcher for the pattern structure and types.
484 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000485
Chris Lattnerda272d12010-02-15 08:04:42 +0000486 // If the pattern has a predicate on it (e.g. only enabled when a subtarget
487 // feature is around, do the check).
488 if (!Pattern.getPredicateCheck().empty())
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000489 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000490
Chris Lattner57bf8a42010-03-04 01:23:08 +0000491 // Now that we've completed the structural type match, emit any ComplexPattern
492 // checks (e.g. addrmode matches). We emit this after the structural match
493 // because they are generally more expensive to evaluate and more difficult to
494 // factor.
Chris Lattner57bf8a42010-03-04 01:23:08 +0000495 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
496 const TreePatternNode *N = MatchedComplexPatterns[i].first;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000497
Chris Lattner57bf8a42010-03-04 01:23:08 +0000498 // Remember where the results of this match get stuck.
499 MatchedComplexPatterns[i].second = NextRecordedOperandNo;
500
501 // Get the slot we recorded the value in from the name on the node.
502 unsigned RecNodeEntry = VariableMap[N->getName()];
503 assert(!N->getName().empty() && RecNodeEntry &&
504 "Complex pattern should have a name and slot");
505 --RecNodeEntry; // Entries in VariableMap are biased.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000506
Chris Lattner57bf8a42010-03-04 01:23:08 +0000507 const ComplexPattern &CP =
508 CGP.getComplexPattern(((DefInit*)N->getLeafValue())->getDef());
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000509
Chris Lattner57bf8a42010-03-04 01:23:08 +0000510 // Emit a CheckComplexPat operation, which does the match (aborting if it
511 // fails) and pushes the matched operands onto the recorded nodes list.
512 AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
513 N->getName(), NextRecordedOperandNo));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000514
Chris Lattner57bf8a42010-03-04 01:23:08 +0000515 // Record the right number of operands.
516 NextRecordedOperandNo += CP.getNumOperands();
517 if (CP.hasProperty(SDNPHasChain)) {
518 // If the complex pattern has a chain, then we need to keep track of the
519 // fact that we just recorded a chain input. The chain input will be
520 // matched as the last operand of the predicate if it was successful.
521 ++NextRecordedOperandNo; // Chained node operand.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000522
Chris Lattner57bf8a42010-03-04 01:23:08 +0000523 // It is the last operand recorded.
524 assert(NextRecordedOperandNo > 1 &&
525 "Should have recorded input/result chains at least!");
526 MatchedChainNodes.push_back(NextRecordedOperandNo-1);
527 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000528
Chris Lattner8950bca2010-12-23 17:03:20 +0000529 // TODO: Complex patterns can't have output glues, if they did, we'd want
Chris Lattner57bf8a42010-03-04 01:23:08 +0000530 // to record them.
531 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000532
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000533 return false;
Chris Lattnerda272d12010-02-15 08:04:42 +0000534}
535
536
Chris Lattnerb49985a2010-02-18 06:47:49 +0000537//===----------------------------------------------------------------------===//
538// Node Result Generation
539//===----------------------------------------------------------------------===//
540
Chris Lattner8e946be2010-02-21 03:22:59 +0000541void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
542 SmallVectorImpl<unsigned> &ResultOps){
543 assert(!N->getName().empty() && "Operand not named!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000544
Chris Lattner8e946be2010-02-21 03:22:59 +0000545 // A reference to a complex pattern gets all of the results of the complex
546 // pattern's match.
547 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
Chris Lattner57bf8a42010-03-04 01:23:08 +0000548 unsigned SlotNo = 0;
549 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i)
550 if (MatchedComplexPatterns[i].first->getName() == N->getName()) {
551 SlotNo = MatchedComplexPatterns[i].second;
552 break;
553 }
554 assert(SlotNo != 0 && "Didn't get a slot number assigned?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000555
Chris Lattner20df2422010-02-22 23:33:44 +0000556 // The first slot entry is the node itself, the subsequent entries are the
557 // matched values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000558 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
Chris Lattner57bf8a42010-03-04 01:23:08 +0000559 ResultOps.push_back(SlotNo+i);
Chris Lattner8e946be2010-02-21 03:22:59 +0000560 return;
561 }
562
Chris Lattner57bf8a42010-03-04 01:23:08 +0000563 unsigned SlotNo = getNamedArgumentSlot(N->getName());
564
Chris Lattner8e946be2010-02-21 03:22:59 +0000565 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
566 // version of the immediate so that it doesn't get selected due to some other
567 // node use.
568 if (!N->isLeaf()) {
569 StringRef OperatorName = N->getOperator()->getName();
570 if (OperatorName == "imm" || OperatorName == "fpimm") {
Chris Lattnerb21ba712010-02-25 02:04:40 +0000571 AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
Chris Lattner8e946be2010-02-21 03:22:59 +0000572 ResultOps.push_back(NextRecordedOperandNo++);
573 return;
574 }
575 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000576
Chris Lattner8e946be2010-02-21 03:22:59 +0000577 ResultOps.push_back(SlotNo);
578}
579
Chris Lattnerb49985a2010-02-18 06:47:49 +0000580void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000581 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattner845c0422010-02-18 22:03:03 +0000582 assert(N->isLeaf() && "Must be a leaf");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000583
Chris Lattner845c0422010-02-18 22:03:03 +0000584 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +0000585 AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getType(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000586 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000587 return;
588 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000589
Chris Lattner845c0422010-02-18 22:03:03 +0000590 // If this is an explicit register reference, handle it.
591 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
592 if (DI->getDef()->isSubClassOf("Register")) {
Jim Grosbach4a6d7352011-03-11 02:19:02 +0000593 AddMatcher(new EmitRegisterMatcher(RegisterDefMap[DI->getDef()],
594 N->getType(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000595 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000596 return;
597 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000598
Chris Lattner845c0422010-02-18 22:03:03 +0000599 if (DI->getDef()->getName() == "zero_reg") {
Chris Lattnerd7349192010-03-19 21:37:09 +0000600 AddMatcher(new EmitRegisterMatcher(0, N->getType(0)));
Chris Lattner8e946be2010-02-21 03:22:59 +0000601 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattner845c0422010-02-18 22:03:03 +0000602 return;
603 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000604
Chris Lattner8e946be2010-02-21 03:22:59 +0000605 // Handle a reference to a register class. This is used
606 // in COPY_TO_SUBREG instructions.
Chris Lattner845c0422010-02-18 22:03:03 +0000607 if (DI->getDef()->isSubClassOf("RegisterClass")) {
Chris Lattner8e946be2010-02-21 03:22:59 +0000608 std::string Value = getQualifiedName(DI->getDef()) + "RegClassID";
Chris Lattnerb21ba712010-02-25 02:04:40 +0000609 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
Chris Lattner8e946be2010-02-21 03:22:59 +0000610 ResultOps.push_back(NextRecordedOperandNo++);
611 return;
Chris Lattner845c0422010-02-18 22:03:03 +0000612 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +0000613
614 // Handle a subregister index. This is used for INSERT_SUBREG etc.
615 if (DI->getDef()->isSubClassOf("SubRegIndex")) {
616 std::string Value = getQualifiedName(DI->getDef());
617 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
618 ResultOps.push_back(NextRecordedOperandNo++);
619 return;
620 }
Chris Lattner845c0422010-02-18 22:03:03 +0000621 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000622
Chris Lattnerb49985a2010-02-18 06:47:49 +0000623 errs() << "unhandled leaf node: \n";
624 N->dump();
625}
626
Chris Lattner8e946be2010-02-21 03:22:59 +0000627/// GetInstPatternNode - Get the pattern for an instruction.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000628///
Chris Lattner8e946be2010-02-21 03:22:59 +0000629const TreePatternNode *MatcherGen::
630GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
631 const TreePattern *InstPat = Inst.getPattern();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000632
Chris Lattner8e946be2010-02-21 03:22:59 +0000633 // FIXME2?: Assume actual pattern comes before "implicit".
634 TreePatternNode *InstPatNode;
635 if (InstPat)
636 InstPatNode = InstPat->getTree(0);
637 else if (/*isRoot*/ N == Pattern.getDstPattern())
638 InstPatNode = Pattern.getSrcPattern();
639 else
640 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000641
Chris Lattner8e946be2010-02-21 03:22:59 +0000642 if (InstPatNode && !InstPatNode->isLeaf() &&
643 InstPatNode->getOperator()->getName() == "set")
644 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000645
Chris Lattner8e946be2010-02-21 03:22:59 +0000646 return InstPatNode;
647}
648
Cameron Zwarich3a2d2552011-05-19 21:13:30 +0000649static bool
650mayInstNodeLoadOrStore(const TreePatternNode *N,
651 const CodeGenDAGPatterns &CGP) {
652 Record *Op = N->getOperator();
653 const CodeGenTarget &CGT = CGP.getTargetInfo();
654 CodeGenInstruction &II = CGT.getInstruction(Op);
655 return II.mayLoad || II.mayStore;
656}
657
658static unsigned
659numNodesThatMayLoadOrStore(const TreePatternNode *N,
660 const CodeGenDAGPatterns &CGP) {
661 if (N->isLeaf())
662 return 0;
663
664 Record *OpRec = N->getOperator();
665 if (!OpRec->isSubClassOf("Instruction"))
666 return 0;
667
668 unsigned Count = 0;
669 if (mayInstNodeLoadOrStore(N, CGP))
670 ++Count;
671
672 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
673 Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
674
675 return Count;
676}
677
Chris Lattner8e946be2010-02-21 03:22:59 +0000678void MatcherGen::
679EmitResultInstructionAsOperand(const TreePatternNode *N,
680 SmallVectorImpl<unsigned> &OutputOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000681 Record *Op = N->getOperator();
682 const CodeGenTarget &CGT = CGP.getTargetInfo();
Chris Lattnerf30187a2010-03-19 00:07:20 +0000683 CodeGenInstruction &II = CGT.getInstruction(Op);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000684 const DAGInstruction &Inst = CGP.getInstruction(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000685
Chris Lattner8e946be2010-02-21 03:22:59 +0000686 // If we can, get the pattern for the instruction we're generating. We derive
687 // a variety of information from this pattern, such as whether it has a chain.
688 //
689 // FIXME2: This is extremely dubious for several reasons, not the least of
690 // which it gives special status to instructions with patterns that Pat<>
691 // nodes can't duplicate.
692 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
693
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000694 // NodeHasChain - Whether the instruction node we're creating takes chains.
Chris Lattner8e946be2010-02-21 03:22:59 +0000695 bool NodeHasChain = InstPatNode &&
696 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000697
Chris Lattner8e946be2010-02-21 03:22:59 +0000698 bool isRoot = N == Pattern.getDstPattern();
699
Chris Lattner8950bca2010-12-23 17:03:20 +0000700 // TreeHasOutGlue - True if this tree has glue.
701 bool TreeHasInGlue = false, TreeHasOutGlue = false;
Chris Lattner8e946be2010-02-21 03:22:59 +0000702 if (isRoot) {
703 const TreePatternNode *SrcPat = Pattern.getSrcPattern();
Chris Lattner036609b2010-12-23 18:28:41 +0000704 TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
705 SrcPat->TreeHasProperty(SDNPInGlue, CGP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000706
Chris Lattner8e946be2010-02-21 03:22:59 +0000707 // FIXME2: this is checking the entire pattern, not just the node in
708 // question, doing this just for the root seems like a total hack.
Chris Lattner036609b2010-12-23 18:28:41 +0000709 TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
Chris Lattner8e946be2010-02-21 03:22:59 +0000710 }
711
712 // NumResults - This is the number of results produced by the instruction in
713 // the "outs" list.
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000714 unsigned NumResults = Inst.getNumResults();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000715
Chris Lattnerb49985a2010-02-18 06:47:49 +0000716 // Loop over all of the operands of the instruction pattern, emitting code
717 // to fill them all in. The node 'N' usually has number children equal to
718 // the number of input operands of the instruction. However, in cases
719 // where there are predicate operands for an instruction, we need to fill
720 // in the 'execute always' values. Match up the node operands to the
721 // instruction operands to do this.
Chris Lattner8e946be2010-02-21 03:22:59 +0000722 SmallVector<unsigned, 8> InstOps;
Chris Lattnerc240bb02010-11-01 04:03:32 +0000723 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.Operands.size();
Chris Lattnerb49985a2010-02-18 06:47:49 +0000724 InstOpNo != e; ++InstOpNo) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000725
Chris Lattnerb49985a2010-02-18 06:47:49 +0000726 // Determine what to emit for this operand.
Chris Lattnerc240bb02010-11-01 04:03:32 +0000727 Record *OperandNode = II.Operands[InstOpNo].Rec;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000728 if ((OperandNode->isSubClassOf("PredicateOperand") ||
729 OperandNode->isSubClassOf("OptionalDefOperand")) &&
730 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
731 // This is a predicate or optional def operand; emit the
732 // 'default ops' operands.
Eric Christopherae321ed2010-08-10 23:46:20 +0000733 const DAGDefaultOperand &DefaultOp
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000734 = CGP.getDefaultOperand(OperandNode);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000735 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
Chris Lattner8e946be2010-02-21 03:22:59 +0000736 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000737 continue;
738 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000739
Chris Lattner0be6fe72010-03-27 19:15:02 +0000740 const TreePatternNode *Child = N->getChild(ChildNo);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000741
Chris Lattnerb49985a2010-02-18 06:47:49 +0000742 // Otherwise this is a normal operand or a predicate operand without
743 // 'execute always'; emit it.
Chris Lattner0be6fe72010-03-27 19:15:02 +0000744 unsigned BeforeAddingNumOps = InstOps.size();
745 EmitResultOperand(Child, InstOps);
746 assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000747
Chris Lattner0be6fe72010-03-27 19:15:02 +0000748 // If the operand is an instruction and it produced multiple results, just
749 // take the first one.
750 if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
751 InstOps.resize(BeforeAddingNumOps+1);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000752
Chris Lattnerb49985a2010-02-18 06:47:49 +0000753 ++ChildNo;
754 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000755
Chris Lattner8950bca2010-12-23 17:03:20 +0000756 // If this node has input glue or explicitly specified input physregs, we
757 // need to add chained and glued copyfromreg nodes and materialize the glue
Chris Lattner8e946be2010-02-21 03:22:59 +0000758 // input.
759 if (isRoot && !PhysRegInputs.empty()) {
760 // Emit all of the CopyToReg nodes for the input physical registers. These
761 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
762 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
Chris Lattnerb21ba712010-02-25 02:04:40 +0000763 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
Chris Lattner92879532010-03-18 23:57:40 +0000764 PhysRegInputs[i].first));
Chris Lattner8950bca2010-12-23 17:03:20 +0000765 // Even if the node has no other glue inputs, the resultant node must be
766 // glued to the CopyFromReg nodes we just generated.
767 TreeHasInGlue = true;
Chris Lattner8e946be2010-02-21 03:22:59 +0000768 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000769
Chris Lattner8950bca2010-12-23 17:03:20 +0000770 // Result order: node results, chain, glue
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000771
Chris Lattner8e946be2010-02-21 03:22:59 +0000772 // Determine the result types.
773 SmallVector<MVT::SimpleValueType, 4> ResultVTs;
Chris Lattner0be6fe72010-03-27 19:15:02 +0000774 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
775 ResultVTs.push_back(N->getType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000776
Chris Lattner8e946be2010-02-21 03:22:59 +0000777 // If this is the root instruction of a pattern that has physical registers in
778 // its result pattern, add output VTs for them. For example, X86 has:
779 // (set AL, (mul ...))
780 // This also handles implicit results like:
781 // (implicit EFLAGS)
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000782 if (isRoot && !Pattern.getDstRegs().empty()) {
Chris Lattner92879532010-03-18 23:57:40 +0000783 // If the root came from an implicit def in the instruction handling stuff,
784 // don't re-add it.
785 Record *HandledReg = 0;
Chris Lattner9414ae52010-03-27 20:09:24 +0000786 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
Chris Lattner92879532010-03-18 23:57:40 +0000787 HandledReg = II.ImplicitDefs[0];
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000788
Chris Lattner92879532010-03-18 23:57:40 +0000789 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
790 Record *Reg = Pattern.getDstRegs()[i];
791 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
792 ResultVTs.push_back(getRegisterValueType(Reg, CGT));
793 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000794 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000795
Chris Lattner1e506312010-03-19 05:34:15 +0000796 // If this is the root of the pattern and the pattern we're matching includes
797 // a node that is variadic, mark the generated node as variadic so that it
798 // gets the excess operands from the input DAG.
Chris Lattner8e946be2010-02-21 03:22:59 +0000799 int NumFixedArityOperands = -1;
Chris Lattner1e506312010-03-19 05:34:15 +0000800 if (isRoot &&
801 (Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP)))
Chris Lattner8e946be2010-02-21 03:22:59 +0000802 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000803
Cameron Zwarich3a2d2552011-05-19 21:13:30 +0000804 // If this is the root node and multiple matched nodes in the input pattern
805 // have MemRefs in them, have the interpreter collect them and plop them onto
806 // this node. If there is just one node with MemRefs, leave them on that node
807 // even if it is not the root.
Chris Lattner8e946be2010-02-21 03:22:59 +0000808 //
Cameron Zwarich3a2d2552011-05-19 21:13:30 +0000809 // FIXME3: This is actively incorrect for result patterns with multiple
810 // memory-referencing instructions.
811 bool PatternHasMemOperands =
812 Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
813
814 bool NodeHasMemRefs = false;
815 if (PatternHasMemOperands) {
816 unsigned NumNodesThatLoadOrStore =
817 numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
818 bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
819 NumNodesThatLoadOrStore == 1;
820 NodeHasMemRefs =
821 NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
822 NumNodesThatLoadOrStore != 1));
823 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000824
Chris Lattner8950bca2010-12-23 17:03:20 +0000825 assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
Chris Lattner0be6fe72010-03-27 19:15:02 +0000826 "Node has no result");
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000827
Chris Lattnerb21ba712010-02-25 02:04:40 +0000828 AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
Chris Lattnere86097a2010-02-28 02:31:26 +0000829 ResultVTs.data(), ResultVTs.size(),
830 InstOps.data(), InstOps.size(),
Chris Lattner8950bca2010-12-23 17:03:20 +0000831 NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
Chris Lattner6281cda2010-02-28 02:41:25 +0000832 NodeHasMemRefs, NumFixedArityOperands,
833 NextRecordedOperandNo));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000834
Chris Lattner8950bca2010-12-23 17:03:20 +0000835 // The non-chain and non-glue results of the newly emitted node get recorded.
Chris Lattner565a6f92010-02-21 23:54:05 +0000836 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000837 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
Chris Lattner77f2e272010-02-21 06:03:07 +0000838 OutputOps.push_back(NextRecordedOperandNo++);
Chris Lattner565a6f92010-02-21 23:54:05 +0000839 }
Chris Lattner8e946be2010-02-21 03:22:59 +0000840}
841
842void MatcherGen::
843EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
844 SmallVectorImpl<unsigned> &ResultOps) {
845 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
846
847 // Emit the operand.
848 SmallVector<unsigned, 8> InputOps;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000849
Chris Lattner8e946be2010-02-21 03:22:59 +0000850 // FIXME2: Could easily generalize this to support multiple inputs and outputs
851 // to the SDNodeXForm. For now we just support one input and one output like
852 // the old instruction selector.
853 assert(N->getNumChildren() == 1);
854 EmitResultOperand(N->getChild(0), InputOps);
855
856 // The input currently must have produced exactly one result.
857 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
858
Chris Lattnerb21ba712010-02-25 02:04:40 +0000859 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
Chris Lattner8e946be2010-02-21 03:22:59 +0000860 ResultOps.push_back(NextRecordedOperandNo++);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000861}
862
863void MatcherGen::EmitResultOperand(const TreePatternNode *N,
Chris Lattner8e946be2010-02-21 03:22:59 +0000864 SmallVectorImpl<unsigned> &ResultOps) {
Chris Lattnerb49985a2010-02-18 06:47:49 +0000865 // This is something selected from the pattern we matched.
Chris Lattner8e946be2010-02-21 03:22:59 +0000866 if (!N->getName().empty())
867 return EmitResultOfNamedOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000868
869 if (N->isLeaf())
870 return EmitResultLeafAsOperand(N, ResultOps);
871
872 Record *OpRec = N->getOperator();
873 if (OpRec->isSubClassOf("Instruction"))
874 return EmitResultInstructionAsOperand(N, ResultOps);
875 if (OpRec->isSubClassOf("SDNodeXForm"))
Chris Lattner8e946be2010-02-21 03:22:59 +0000876 return EmitResultSDNodeXFormAsOperand(N, ResultOps);
Chris Lattnerb49985a2010-02-18 06:47:49 +0000877 errs() << "Unknown result node to emit code for: " << *N << '\n';
878 throw std::string("Unknown node in result pattern!");
879}
880
881void MatcherGen::EmitResultCode() {
Chris Lattner01bcd942010-03-01 22:46:42 +0000882 // Patterns that match nodes with (potentially multiple) chain inputs have to
883 // merge them together into a token factor. This informs the generated code
884 // what all the chained nodes are.
885 if (!MatchedChainNodes.empty())
886 AddMatcher(new EmitMergeInputChainsMatcher
887 (MatchedChainNodes.data(), MatchedChainNodes.size()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000888
Chris Lattner565a6f92010-02-21 23:54:05 +0000889 // Codegen the root of the result pattern, capturing the resulting values.
Chris Lattner8e946be2010-02-21 03:22:59 +0000890 SmallVector<unsigned, 8> Ops;
Chris Lattnerb49985a2010-02-18 06:47:49 +0000891 EmitResultOperand(Pattern.getDstPattern(), Ops);
Chris Lattner8e946be2010-02-21 03:22:59 +0000892
Chris Lattner565a6f92010-02-21 23:54:05 +0000893 // At this point, we have however many values the result pattern produces.
894 // However, the input pattern might not need all of these. If there are
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000895 // excess values at the end (such as implicit defs of condition codes etc)
Chris Lattner8950bca2010-12-23 17:03:20 +0000896 // just lop them off. This doesn't need to worry about glue or chains, just
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000897 // explicit results.
Chris Lattner565a6f92010-02-21 23:54:05 +0000898 //
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000899 unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000900
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000901 // If the pattern also has (implicit) results, count them as well.
902 if (!Pattern.getDstRegs().empty()) {
903 // If the root came from an implicit def in the instruction handling stuff,
904 // don't re-add it.
905 Record *HandledReg = 0;
906 const TreePatternNode *DstPat = Pattern.getDstPattern();
907 if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
908 const CodeGenTarget &CGT = CGP.getTargetInfo();
909 CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
910
911 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
912 HandledReg = II.ImplicitDefs[0];
913 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000914
Chris Lattnerb4a52b02010-03-27 20:45:15 +0000915 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
916 Record *Reg = Pattern.getDstRegs()[i];
917 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
918 ++NumSrcResults;
919 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000920 }
921
Chris Lattner565a6f92010-02-21 23:54:05 +0000922 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
923 Ops.resize(NumSrcResults);
Chris Lattner02f73582010-02-24 05:33:42 +0000924
Chris Lattner8950bca2010-12-23 17:03:20 +0000925 // If the matched pattern covers nodes which define a glue result, emit a node
Chris Lattner02f73582010-02-24 05:33:42 +0000926 // that tells the matcher about them so that it can update their results.
Chris Lattner8950bca2010-12-23 17:03:20 +0000927 if (!MatchedGlueResultNodes.empty())
928 AddMatcher(new MarkGlueResultsMatcher(MatchedGlueResultNodes.data(),
929 MatchedGlueResultNodes.size()));
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000930
Chris Lattnerb21ba712010-02-25 02:04:40 +0000931 AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
Chris Lattnerb49985a2010-02-18 06:47:49 +0000932}
933
934
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000935/// ConvertPatternToMatcher - Create the matcher for the specified pattern with
936/// the specified variant. If the variant number is invalid, this returns null.
Chris Lattnerb21ba712010-02-25 02:04:40 +0000937Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000938 unsigned Variant,
Chris Lattnerc78f2a32010-02-28 20:49:53 +0000939 const CodeGenDAGPatterns &CGP) {
Chris Lattnerda272d12010-02-15 08:04:42 +0000940 MatcherGen Gen(Pattern, CGP);
941
942 // Generate the code for the matcher.
Chris Lattnerfa342fa2010-03-01 07:17:40 +0000943 if (Gen.EmitMatcherCode(Variant))
944 return 0;
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000945
Chris Lattner8e946be2010-02-21 03:22:59 +0000946 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
947 // FIXME2: Split result code out to another table, and make the matcher end
948 // with an "Emit <index>" command. This allows result generation stuff to be
949 // shared and factored?
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000950
Chris Lattnerda272d12010-02-15 08:04:42 +0000951 // If the match succeeds, then we generate Pattern.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000952 Gen.EmitResultCode();
Chris Lattnerda272d12010-02-15 08:04:42 +0000953
954 // Unconditional match.
Chris Lattnerb49985a2010-02-18 06:47:49 +0000955 return Gen.GetMatcher();
Chris Lattnerda272d12010-02-15 08:04:42 +0000956}