blob: e793333eef5cca16c137f3c8861bea3977b35987 [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
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//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Support/Debug.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000019#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000020#include <algorithm>
Daniel Dunbar1a551802009-07-03 00:10:29 +000021#include <iostream>
Chris Lattner6cefb772008-01-05 22:25:12 +000022using namespace llvm;
23
24//===----------------------------------------------------------------------===//
25// Helpers for working with extended types.
26
27/// FilterVTs - Filter a list of VT's according to a predicate.
28///
29template<typename T>
Owen Anderson825b72b2009-08-11 20:47:22 +000030static std::vector<MVT::SimpleValueType>
31FilterVTs(const std::vector<MVT::SimpleValueType> &InVTs, T Filter) {
32 std::vector<MVT::SimpleValueType> Result;
Chris Lattner6cefb772008-01-05 22:25:12 +000033 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
34 if (Filter(InVTs[i]))
35 Result.push_back(InVTs[i]);
36 return Result;
37}
38
39template<typename T>
40static std::vector<unsigned char>
41FilterEVTs(const std::vector<unsigned char> &InVTs, T Filter) {
42 std::vector<unsigned char> Result;
43 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
Owen Anderson825b72b2009-08-11 20:47:22 +000044 if (Filter((MVT::SimpleValueType)InVTs[i]))
Chris Lattner6cefb772008-01-05 22:25:12 +000045 Result.push_back(InVTs[i]);
46 return Result;
47}
48
49static std::vector<unsigned char>
Owen Anderson825b72b2009-08-11 20:47:22 +000050ConvertVTs(const std::vector<MVT::SimpleValueType> &InVTs) {
Chris Lattner6cefb772008-01-05 22:25:12 +000051 std::vector<unsigned char> Result;
52 for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
53 Result.push_back(InVTs[i]);
54 return Result;
55}
56
Owen Anderson825b72b2009-08-11 20:47:22 +000057static inline bool isInteger(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000058 return EVT(VT).isInteger();
Duncan Sands83ec4b62008-06-06 12:08:01 +000059}
60
Owen Anderson825b72b2009-08-11 20:47:22 +000061static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000062 return EVT(VT).isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000063}
64
Owen Anderson825b72b2009-08-11 20:47:22 +000065static inline bool isVector(MVT::SimpleValueType VT) {
Owen Andersone50ed302009-08-10 22:56:29 +000066 return EVT(VT).isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000067}
68
Chris Lattner6cefb772008-01-05 22:25:12 +000069static bool LHSIsSubsetOfRHS(const std::vector<unsigned char> &LHS,
70 const std::vector<unsigned char> &RHS) {
71 if (LHS.size() > RHS.size()) return false;
72 for (unsigned i = 0, e = LHS.size(); i != e; ++i)
73 if (std::find(RHS.begin(), RHS.end(), LHS[i]) == RHS.end())
74 return false;
75 return true;
76}
77
Chris Lattner6cefb772008-01-05 22:25:12 +000078namespace llvm {
Owen Andersone50ed302009-08-10 22:56:29 +000079namespace EEVT {
Dan Gohman4b6fce42009-03-31 16:48:35 +000080/// isExtIntegerInVTs - Return true if the specified extended value type vector
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000081/// contains iAny or an integer value type.
Chris Lattner6cefb772008-01-05 22:25:12 +000082bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs) {
83 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000084 return EVTs[0] == MVT::iAny || !(FilterEVTs(EVTs, isInteger).empty());
Chris Lattner6cefb772008-01-05 22:25:12 +000085}
86
Dan Gohman4b6fce42009-03-31 16:48:35 +000087/// isExtFloatingPointInVTs - Return true if the specified extended value type
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000088/// vector contains fAny or a FP value type.
Chris Lattner6cefb772008-01-05 22:25:12 +000089bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
Bob Wilson61fc4cf2009-08-11 01:14:02 +000090 assert(!EVTs.empty() && "Cannot check for FP in empty ExtVT list!");
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000091 return EVTs[0] == MVT::fAny || !(FilterEVTs(EVTs, isFloatingPoint).empty());
Chris Lattner6cefb772008-01-05 22:25:12 +000092}
Bob Wilson61fc4cf2009-08-11 01:14:02 +000093
94/// isExtVectorInVTs - Return true if the specified extended value type
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000095/// vector contains vAny or a vector value type.
Bob Wilson61fc4cf2009-08-11 01:14:02 +000096bool isExtVectorInVTs(const std::vector<unsigned char> &EVTs) {
97 assert(!EVTs.empty() && "Cannot check for vector in empty ExtVT list!");
Bob Wilsoncdfa01b2009-08-29 05:53:25 +000098 return EVTs[0] == MVT::vAny || !(FilterEVTs(EVTs, isVector).empty());
Bob Wilson61fc4cf2009-08-11 01:14:02 +000099}
Owen Andersone50ed302009-08-10 22:56:29 +0000100} // end namespace EEVT.
Chris Lattner6cefb772008-01-05 22:25:12 +0000101} // end namespace llvm.
102
Daniel Dunbar6f5cc822009-08-23 09:47:37 +0000103bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
104 return LHS->getID() < RHS->getID();
105}
Scott Michel327d0652008-03-05 17:49:05 +0000106
107/// Dependent variable map for CodeGenDAGPattern variant generation
108typedef std::map<std::string, int> DepVarMap;
109
110/// Const iterator shorthand for DepVarMap
111typedef DepVarMap::const_iterator DepVarMap_citer;
112
113namespace {
114void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
115 if (N->isLeaf()) {
116 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
117 DepMap[N->getName()]++;
118 }
119 } else {
120 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
121 FindDepVarsOf(N->getChild(i), DepMap);
122 }
123}
124
125//! Find dependent variables within child patterns
126/*!
127 */
128void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
129 DepVarMap depcounts;
130 FindDepVarsOf(N, depcounts);
131 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
132 if (i->second > 1) { // std::pair<std::string, int>
133 DepVars.insert(i->first);
134 }
135 }
136}
137
138//! Dump the dependent variable set:
139void DumpDepVars(MultipleUseVarSet &DepVars) {
140 if (DepVars.empty()) {
Chris Lattner569f1212009-08-23 04:44:11 +0000141 DEBUG(errs() << "<empty set>");
Scott Michel327d0652008-03-05 17:49:05 +0000142 } else {
Chris Lattner569f1212009-08-23 04:44:11 +0000143 DEBUG(errs() << "[ ");
Scott Michel327d0652008-03-05 17:49:05 +0000144 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
145 i != e; ++i) {
Chris Lattner569f1212009-08-23 04:44:11 +0000146 DEBUG(errs() << (*i) << " ");
Scott Michel327d0652008-03-05 17:49:05 +0000147 }
Chris Lattner569f1212009-08-23 04:44:11 +0000148 DEBUG(errs() << "]");
Scott Michel327d0652008-03-05 17:49:05 +0000149 }
150}
151}
152
Chris Lattner6cefb772008-01-05 22:25:12 +0000153//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000154// PatternToMatch implementation
155//
156
157/// getPredicateCheck - Return a single string containing all of this
158/// pattern's predicates concatenated with "&&" operators.
159///
160std::string PatternToMatch::getPredicateCheck() const {
161 std::string PredicateCheck;
162 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
163 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
164 Record *Def = Pred->getDef();
165 if (!Def->isSubClassOf("Predicate")) {
166#ifndef NDEBUG
167 Def->dump();
168#endif
169 assert(0 && "Unknown predicate type!");
170 }
171 if (!PredicateCheck.empty())
172 PredicateCheck += " && ";
173 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
174 }
175 }
176
177 return PredicateCheck;
178}
179
180//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000181// SDTypeConstraint implementation
182//
183
184SDTypeConstraint::SDTypeConstraint(Record *R) {
185 OperandNo = R->getValueAsInt("OperandNum");
186
187 if (R->isSubClassOf("SDTCisVT")) {
188 ConstraintType = SDTCisVT;
189 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
190 } else if (R->isSubClassOf("SDTCisPtrTy")) {
191 ConstraintType = SDTCisPtrTy;
192 } else if (R->isSubClassOf("SDTCisInt")) {
193 ConstraintType = SDTCisInt;
194 } else if (R->isSubClassOf("SDTCisFP")) {
195 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +0000196 } else if (R->isSubClassOf("SDTCisVec")) {
197 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +0000198 } else if (R->isSubClassOf("SDTCisSameAs")) {
199 ConstraintType = SDTCisSameAs;
200 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
201 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
202 ConstraintType = SDTCisVTSmallerThanOp;
203 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
204 R->getValueAsInt("OtherOperandNum");
205 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
206 ConstraintType = SDTCisOpSmallerThanOp;
207 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
208 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000209 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
210 ConstraintType = SDTCisEltOfVec;
211 x.SDTCisEltOfVec_Info.OtherOperandNum =
212 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000213 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000214 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000215 exit(1);
216 }
217}
218
219/// getOperandNum - Return the node corresponding to operand #OpNo in tree
220/// N, which has NumResults results.
221TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
222 TreePatternNode *N,
223 unsigned NumResults) const {
224 assert(NumResults <= 1 &&
225 "We only work with nodes with zero or one result so far!");
226
227 if (OpNo >= (NumResults + N->getNumChildren())) {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000228 errs() << "Invalid operand number " << OpNo << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000229 N->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000230 errs() << '\n';
Chris Lattner6cefb772008-01-05 22:25:12 +0000231 exit(1);
232 }
233
234 if (OpNo < NumResults)
235 return N; // FIXME: need value #
236 else
237 return N->getChild(OpNo-NumResults);
238}
239
240/// ApplyTypeConstraint - Given a node in a pattern, apply this type
241/// constraint to the nodes operands. This returns true if it makes a
242/// change, false otherwise. If a type contradiction is found, throw an
243/// exception.
244bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
245 const SDNodeInfo &NodeInfo,
246 TreePattern &TP) const {
247 unsigned NumResults = NodeInfo.getNumResults();
248 assert(NumResults <= 1 &&
249 "We only work with nodes with zero or one result so far!");
250
251 // Check that the number of operands is sane. Negative operands -> varargs.
252 if (NodeInfo.getNumOperands() >= 0) {
253 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
254 TP.error(N->getOperator()->getName() + " node requires exactly " +
255 itostr(NodeInfo.getNumOperands()) + " operands!");
256 }
257
258 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
259
260 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
261
262 switch (ConstraintType) {
263 default: assert(0 && "Unknown constraint type!");
264 case SDTCisVT:
265 // Operand must be a particular type.
266 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
267 case SDTCisPtrTy: {
268 // Operand must be same as target pointer type.
Owen Anderson825b72b2009-08-11 20:47:22 +0000269 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000270 }
271 case SDTCisInt: {
272 // If there is only one integer type supported, this must be it.
Owen Anderson825b72b2009-08-11 20:47:22 +0000273 std::vector<MVT::SimpleValueType> IntVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000274 FilterVTs(CGT.getLegalValueTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000275
276 // If we found exactly one supported integer type, apply it.
277 if (IntVTs.size() == 1)
278 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000279 return NodeToApply->UpdateNodeType(MVT::iAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000280 }
281 case SDTCisFP: {
282 // If there is only one FP type supported, this must be it.
Owen Anderson825b72b2009-08-11 20:47:22 +0000283 std::vector<MVT::SimpleValueType> FPVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000284 FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000285
286 // If we found exactly one supported FP type, apply it.
287 if (FPVTs.size() == 1)
288 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000289 return NodeToApply->UpdateNodeType(MVT::fAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000290 }
Bob Wilson36e3e662009-08-12 22:30:59 +0000291 case SDTCisVec: {
292 // If there is only one vector type supported, this must be it.
293 std::vector<MVT::SimpleValueType> VecVTs =
294 FilterVTs(CGT.getLegalValueTypes(), isVector);
295
296 // If we found exactly one supported vector type, apply it.
297 if (VecVTs.size() == 1)
298 return NodeToApply->UpdateNodeType(VecVTs[0], TP);
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000299 return NodeToApply->UpdateNodeType(MVT::vAny, TP);
Bob Wilson36e3e662009-08-12 22:30:59 +0000300 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000301 case SDTCisSameAs: {
302 TreePatternNode *OtherNode =
303 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
304 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
305 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
306 }
307 case SDTCisVTSmallerThanOp: {
308 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
309 // have an integer type that is smaller than the VT.
310 if (!NodeToApply->isLeaf() ||
311 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
312 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
313 ->isSubClassOf("ValueType"))
314 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000315 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000316 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000317 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000318 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
319
320 TreePatternNode *OtherNode =
321 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
322
323 // It must be integer.
Bill Wendling7529ece2009-12-25 13:35:40 +0000324 bool MadeChange = OtherNode->UpdateNodeType(MVT::iAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000325
326 // This code only handles nodes that have one type set. Assert here so
327 // that we can change this if we ever need to deal with multiple value
328 // types at this point.
329 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
330 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
Owen Anderson825b72b2009-08-11 20:47:22 +0000331 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
Bill Wendling7529ece2009-12-25 13:35:40 +0000332 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +0000333 }
334 case SDTCisOpSmallerThanOp: {
335 TreePatternNode *BigOperand =
336 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
337
338 // Both operands must be integer or FP, but we don't care which.
339 bool MadeChange = false;
340
341 // This code does not currently handle nodes which have multiple types,
342 // where some types are integer, and some are fp. Assert that this is not
343 // the case.
Owen Andersone50ed302009-08-10 22:56:29 +0000344 assert(!(EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
345 EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
346 !(EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
347 EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000348 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Owen Andersone50ed302009-08-10 22:56:29 +0000349 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000350 MadeChange |= BigOperand->UpdateNodeType(MVT::iAny, TP);
Owen Andersone50ed302009-08-10 22:56:29 +0000351 else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000352 MadeChange |= BigOperand->UpdateNodeType(MVT::fAny, TP);
Owen Andersone50ed302009-08-10 22:56:29 +0000353 if (EEVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000354 MadeChange |= NodeToApply->UpdateNodeType(MVT::iAny, TP);
Owen Andersone50ed302009-08-10 22:56:29 +0000355 else if (EEVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000356 MadeChange |= NodeToApply->UpdateNodeType(MVT::fAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000357
Owen Anderson825b72b2009-08-11 20:47:22 +0000358 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000359
Owen Andersone50ed302009-08-10 22:56:29 +0000360 if (EEVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000361 VTs = FilterVTs(VTs, isInteger);
Owen Andersone50ed302009-08-10 22:56:29 +0000362 } else if (EEVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000363 VTs = FilterVTs(VTs, isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000364 } else {
365 VTs.clear();
366 }
367
368 switch (VTs.size()) {
369 default: // Too many VT's to pick from.
370 case 0: break; // No info yet.
371 case 1:
Jim Grosbachda4231f2009-03-26 16:17:51 +0000372 // Only one VT of this flavor. Cannot ever satisfy the constraints.
Owen Anderson825b72b2009-08-11 20:47:22 +0000373 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
Chris Lattner6cefb772008-01-05 22:25:12 +0000374 case 2:
375 // If we have exactly two possible types, the little operand must be the
376 // small one, the big operand should be the big one. Common with
377 // float/double for example.
378 assert(VTs[0] < VTs[1] && "Should be sorted!");
379 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
380 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
381 break;
382 }
383 return MadeChange;
384 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000385 case SDTCisEltOfVec: {
386 TreePatternNode *OtherOperand =
Nate Begeman9008ca62009-04-27 18:41:29 +0000387 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum,
Nate Begemanb5af3342008-02-09 01:37:05 +0000388 N, NumResults);
389 if (OtherOperand->hasTypeSet()) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000390 if (!isVector(OtherOperand->getTypeNum(0)))
Nate Begemanb5af3342008-02-09 01:37:05 +0000391 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Owen Andersone50ed302009-08-10 22:56:29 +0000392 EVT IVT = OtherOperand->getTypeNum(0);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000393 IVT = IVT.getVectorElementType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000394 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000395 }
396 return false;
397 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000398 }
399 return false;
400}
401
402//===----------------------------------------------------------------------===//
403// SDNodeInfo implementation
404//
405SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
406 EnumName = R->getValueAsString("Opcode");
407 SDClassName = R->getValueAsString("SDClass");
408 Record *TypeProfile = R->getValueAsDef("TypeProfile");
409 NumResults = TypeProfile->getValueAsInt("NumResults");
410 NumOperands = TypeProfile->getValueAsInt("NumOperands");
411
412 // Parse the properties.
413 Properties = 0;
414 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
415 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
416 if (PropList[i]->getName() == "SDNPCommutative") {
417 Properties |= 1 << SDNPCommutative;
418 } else if (PropList[i]->getName() == "SDNPAssociative") {
419 Properties |= 1 << SDNPAssociative;
420 } else if (PropList[i]->getName() == "SDNPHasChain") {
421 Properties |= 1 << SDNPHasChain;
422 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen874ae252009-06-02 03:12:52 +0000423 Properties |= 1 << SDNPOutFlag;
Chris Lattner6cefb772008-01-05 22:25:12 +0000424 } else if (PropList[i]->getName() == "SDNPInFlag") {
425 Properties |= 1 << SDNPInFlag;
426 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
427 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000428 } else if (PropList[i]->getName() == "SDNPMayStore") {
429 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000430 } else if (PropList[i]->getName() == "SDNPMayLoad") {
431 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000432 } else if (PropList[i]->getName() == "SDNPSideEffect") {
433 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000434 } else if (PropList[i]->getName() == "SDNPMemOperand") {
435 Properties |= 1 << SDNPMemOperand;
Chris Lattner6cefb772008-01-05 22:25:12 +0000436 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000437 errs() << "Unknown SD Node property '" << PropList[i]->getName()
438 << "' on node '" << R->getName() << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +0000439 exit(1);
440 }
441 }
442
443
444 // Parse the type constraints.
445 std::vector<Record*> ConstraintList =
446 TypeProfile->getValueAsListOfDefs("Constraints");
447 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
448}
449
Chris Lattner22579812010-02-28 00:22:30 +0000450/// getKnownType - If the type constraints on this node imply a fixed type
451/// (e.g. all stores return void, etc), then return it as an
452/// MVT::SimpleValueType. Otherwise, return EEVT::isUnknown.
453unsigned SDNodeInfo::getKnownType() const {
454 unsigned NumResults = getNumResults();
455 assert(NumResults <= 1 &&
456 "We only work with nodes with zero or one result so far!");
457
458 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
459 // Make sure that this applies to the correct node result.
460 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
461 continue;
462
463 switch (TypeConstraints[i].ConstraintType) {
464 default: break;
465 case SDTypeConstraint::SDTCisVT:
466 return TypeConstraints[i].x.SDTCisVT_Info.VT;
467 case SDTypeConstraint::SDTCisPtrTy:
468 return MVT::iPTR;
469 }
470 }
471 return EEVT::isUnknown;
472}
473
Chris Lattner6cefb772008-01-05 22:25:12 +0000474//===----------------------------------------------------------------------===//
475// TreePatternNode implementation
476//
477
478TreePatternNode::~TreePatternNode() {
479#if 0 // FIXME: implement refcounted tree nodes!
480 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
481 delete getChild(i);
482#endif
483}
484
485/// UpdateNodeType - Set the node type of N to VT if VT contains
486/// information. If N already contains a conflicting type, then throw an
487/// exception. This returns true if any information was updated.
488///
489bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
490 TreePattern &TP) {
491 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
492
Owen Andersone50ed302009-08-10 22:56:29 +0000493 if (ExtVTs[0] == EEVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
Chris Lattner6cefb772008-01-05 22:25:12 +0000494 return false;
495 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
496 setTypes(ExtVTs);
497 return true;
498 }
499
Owen Anderson825b72b2009-08-11 20:47:22 +0000500 if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
501 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny ||
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000502 ExtVTs[0] == MVT::iAny)
Chris Lattner6cefb772008-01-05 22:25:12 +0000503 return false;
Owen Andersone50ed302009-08-10 22:56:29 +0000504 if (EEVT::isExtIntegerInVTs(ExtVTs)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000505 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000506 if (FVTs.size()) {
507 setTypes(ExtVTs);
508 return true;
509 }
510 }
511 }
Bob Wilsone035fa52009-01-05 17:52:54 +0000512
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000513 // Merge vAny with iAny/fAny. The latter include vector types so keep them
514 // as the more specific information.
515 if (ExtVTs[0] == MVT::vAny &&
516 (getExtTypeNum(0) == MVT::iAny || getExtTypeNum(0) == MVT::fAny))
517 return false;
518 if (getExtTypeNum(0) == MVT::vAny &&
519 (ExtVTs[0] == MVT::iAny || ExtVTs[0] == MVT::fAny)) {
520 setTypes(ExtVTs);
521 return true;
522 }
523
524 if (ExtVTs[0] == MVT::iAny &&
Owen Andersone50ed302009-08-10 22:56:29 +0000525 EEVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000526 assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000527 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000528 if (getExtTypes() == FVTs)
529 return false;
530 setTypes(FVTs);
531 return true;
532 }
Owen Anderson825b72b2009-08-11 20:47:22 +0000533 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
Owen Andersone50ed302009-08-10 22:56:29 +0000534 EEVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000535 //assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000536 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000537 if (getExtTypes() == FVTs)
538 return false;
539 if (FVTs.size()) {
540 setTypes(FVTs);
541 return true;
542 }
543 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000544 if (ExtVTs[0] == MVT::fAny &&
Owen Andersone50ed302009-08-10 22:56:29 +0000545 EEVT::isExtFloatingPointInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000546 assert(hasTypeSet() && "should be handled above!");
547 std::vector<unsigned char> FVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000548 FilterEVTs(getExtTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000549 if (getExtTypes() == FVTs)
550 return false;
551 setTypes(FVTs);
552 return true;
553 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000554 if (ExtVTs[0] == MVT::vAny &&
Bob Wilson36e3e662009-08-12 22:30:59 +0000555 EEVT::isExtVectorInVTs(getExtTypes())) {
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000556 assert(hasTypeSet() && "should be handled above!");
557 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isVector);
558 if (getExtTypes() == FVTs)
559 return false;
560 setTypes(FVTs);
561 return true;
562 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000563
Bob Wilson36e3e662009-08-12 22:30:59 +0000564 // If we know this is an int, FP, or vector type, and we are told it is a
565 // specific one, take the advice.
Chris Lattner6cefb772008-01-05 22:25:12 +0000566 //
567 // Similarly, we should probably set the type here to the intersection of
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000568 // {iAny|fAny|vAny} and ExtVTs
569 if ((getExtTypeNum(0) == MVT::iAny &&
Owen Andersone50ed302009-08-10 22:56:29 +0000570 EEVT::isExtIntegerInVTs(ExtVTs)) ||
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000571 (getExtTypeNum(0) == MVT::fAny &&
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000572 EEVT::isExtFloatingPointInVTs(ExtVTs)) ||
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000573 (getExtTypeNum(0) == MVT::vAny &&
Bob Wilson61fc4cf2009-08-11 01:14:02 +0000574 EEVT::isExtVectorInVTs(ExtVTs))) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000575 setTypes(ExtVTs);
576 return true;
577 }
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000578 if (getExtTypeNum(0) == MVT::iAny &&
Owen Anderson825b72b2009-08-11 20:47:22 +0000579 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000580 setTypes(ExtVTs);
581 return true;
582 }
583
584 if (isLeaf()) {
585 dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +0000586 errs() << " ";
Chris Lattner6cefb772008-01-05 22:25:12 +0000587 TP.error("Type inference contradiction found in node!");
588 } else {
589 TP.error("Type inference contradiction found in node " +
590 getOperator()->getName() + "!");
591 }
592 return true; // unreachable
593}
594
Chris Lattnerba1cff42010-02-23 07:50:58 +0000595static std::string GetTypeName(unsigned char TypeID) {
596 switch (TypeID) {
597 case MVT::Other: return "Other";
598 case MVT::iAny: return "iAny";
599 case MVT::fAny: return "fAny";
600 case MVT::vAny: return "vAny";
601 case EEVT::isUnknown: return "isUnknown";
602 case MVT::iPTR: return "iPTR";
603 case MVT::iPTRAny: return "iPTRAny";
604 default:
605 std::string VTName = llvm::getName((MVT::SimpleValueType)TypeID);
606 // Strip off EVT:: prefix if present.
607 if (VTName.substr(0,5) == "MVT::")
608 VTName = VTName.substr(5);
609 return VTName;
610 }
611}
612
Chris Lattner6cefb772008-01-05 22:25:12 +0000613
Daniel Dunbar1a551802009-07-03 00:10:29 +0000614void TreePatternNode::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000615 if (isLeaf()) {
616 OS << *getLeafValue();
617 } else {
Chris Lattnerba1cff42010-02-23 07:50:58 +0000618 OS << '(' << getOperator()->getName();
Chris Lattner6cefb772008-01-05 22:25:12 +0000619 }
620
621 // FIXME: At some point we should handle printing all the value types for
622 // nodes that are multiply typed.
Chris Lattnerba1cff42010-02-23 07:50:58 +0000623 if (getExtTypeNum(0) != EEVT::isUnknown)
624 OS << ':' << GetTypeName(getExtTypeNum(0));
Chris Lattner6cefb772008-01-05 22:25:12 +0000625
626 if (!isLeaf()) {
627 if (getNumChildren() != 0) {
628 OS << " ";
629 getChild(0)->print(OS);
630 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
631 OS << ", ";
632 getChild(i)->print(OS);
633 }
634 }
635 OS << ")";
636 }
637
Dan Gohman0540e172008-10-15 06:17:21 +0000638 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
639 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000640 if (TransformFn)
641 OS << "<<X:" << TransformFn->getName() << ">>";
642 if (!getName().empty())
643 OS << ":$" << getName();
644
645}
646void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +0000647 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +0000648}
649
Scott Michel327d0652008-03-05 17:49:05 +0000650/// isIsomorphicTo - Return true if this node is recursively
651/// isomorphic to the specified node. For this comparison, the node's
652/// entire state is considered. The assigned name is ignored, since
653/// nodes with differing names are considered isomorphic. However, if
654/// the assigned name is present in the dependent variable set, then
655/// the assigned name is considered significant and the node is
656/// isomorphic if the names match.
657bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
658 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000659 if (N == this) return true;
660 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000661 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000662 getTransformFn() != N->getTransformFn())
663 return false;
664
665 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000666 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
667 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000668 return ((DI->getDef() == NDI->getDef())
669 && (DepVars.find(getName()) == DepVars.end()
670 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000671 }
672 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000673 return getLeafValue() == N->getLeafValue();
674 }
675
676 if (N->getOperator() != getOperator() ||
677 N->getNumChildren() != getNumChildren()) return false;
678 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000679 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000680 return false;
681 return true;
682}
683
684/// clone - Make a copy of this tree and all of its children.
685///
686TreePatternNode *TreePatternNode::clone() const {
687 TreePatternNode *New;
688 if (isLeaf()) {
689 New = new TreePatternNode(getLeafValue());
690 } else {
691 std::vector<TreePatternNode*> CChildren;
692 CChildren.reserve(Children.size());
693 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
694 CChildren.push_back(getChild(i)->clone());
695 New = new TreePatternNode(getOperator(), CChildren);
696 }
697 New->setName(getName());
698 New->setTypes(getExtTypes());
Dan Gohman0540e172008-10-15 06:17:21 +0000699 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000700 New->setTransformFn(getTransformFn());
701 return New;
702}
703
Chris Lattner47661322010-02-14 22:22:58 +0000704/// RemoveAllTypes - Recursively strip all the types of this tree.
705void TreePatternNode::RemoveAllTypes() {
706 removeTypes();
707 if (isLeaf()) return;
708 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
709 getChild(i)->RemoveAllTypes();
710}
711
712
Chris Lattner6cefb772008-01-05 22:25:12 +0000713/// SubstituteFormalArguments - Replace the formal arguments in this tree
714/// with actual values specified by ArgMap.
715void TreePatternNode::
716SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
717 if (isLeaf()) return;
718
719 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
720 TreePatternNode *Child = getChild(i);
721 if (Child->isLeaf()) {
722 Init *Val = Child->getLeafValue();
723 if (dynamic_cast<DefInit*>(Val) &&
724 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
725 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000726 TreePatternNode *NewChild = ArgMap[Child->getName()];
727 assert(NewChild && "Couldn't find formal argument!");
728 assert((Child->getPredicateFns().empty() ||
729 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
730 "Non-empty child predicate clobbered!");
731 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000732 }
733 } else {
734 getChild(i)->SubstituteFormalArguments(ArgMap);
735 }
736 }
737}
738
739
740/// InlinePatternFragments - If this pattern refers to any pattern
741/// fragments, inline them into place, giving us a pattern without any
742/// PatFrag references.
743TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
744 if (isLeaf()) return this; // nothing to do.
745 Record *Op = getOperator();
746
747 if (!Op->isSubClassOf("PatFrag")) {
748 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000749 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
750 TreePatternNode *Child = getChild(i);
751 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
752
753 assert((Child->getPredicateFns().empty() ||
754 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
755 "Non-empty child predicate clobbered!");
756
757 setChild(i, NewChild);
758 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000759 return this;
760 }
761
762 // Otherwise, we found a reference to a fragment. First, look up its
763 // TreePattern record.
764 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
765
766 // Verify that we are passing the right number of operands.
767 if (Frag->getNumArgs() != Children.size())
768 TP.error("'" + Op->getName() + "' fragment requires " +
769 utostr(Frag->getNumArgs()) + " operands!");
770
771 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
772
Dan Gohman0540e172008-10-15 06:17:21 +0000773 std::string Code = Op->getValueAsCode("Predicate");
774 if (!Code.empty())
775 FragTree->addPredicateFn("Predicate_"+Op->getName());
776
Chris Lattner6cefb772008-01-05 22:25:12 +0000777 // Resolve formal arguments to their actual value.
778 if (Frag->getNumArgs()) {
779 // Compute the map of formal to actual arguments.
780 std::map<std::string, TreePatternNode*> ArgMap;
781 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
782 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
783
784 FragTree->SubstituteFormalArguments(ArgMap);
785 }
786
787 FragTree->setName(getName());
788 FragTree->UpdateNodeType(getExtTypes(), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000789
790 // Transfer in the old predicates.
791 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
792 FragTree->addPredicateFn(getPredicateFns()[i]);
793
Chris Lattner6cefb772008-01-05 22:25:12 +0000794 // Get a new copy of this fragment to stitch into here.
795 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000796
797 // The fragment we inlined could have recursive inlining that is needed. See
798 // if there are any pattern fragments in it and inline them as needed.
799 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000800}
801
802/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000803/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +0000804/// references from the register file information, for example.
805///
806static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
Chris Lattner523f6a52010-02-14 21:10:15 +0000807 TreePattern &TP) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000808 // Some common return values
Owen Andersone50ed302009-08-10 22:56:29 +0000809 std::vector<unsigned char> Unknown(1, EEVT::isUnknown);
Owen Anderson825b72b2009-08-11 20:47:22 +0000810 std::vector<unsigned char> Other(1, MVT::Other);
Chris Lattner6cefb772008-01-05 22:25:12 +0000811
812 // Check to see if this is a register or a register class...
813 if (R->isSubClassOf("RegisterClass")) {
814 if (NotRegisters)
815 return Unknown;
816 const CodeGenRegisterClass &RC =
817 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
818 return ConvertVTs(RC.getValueTypes());
819 } else if (R->isSubClassOf("PatFrag")) {
820 // Pattern fragment types will be resolved when they are inlined.
821 return Unknown;
822 } else if (R->isSubClassOf("Register")) {
823 if (NotRegisters)
824 return Unknown;
825 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
826 return T.getRegisterVTs(R);
827 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
828 // Using a VTSDNode or CondCodeSDNode.
829 return Other;
830 } else if (R->isSubClassOf("ComplexPattern")) {
831 if (NotRegisters)
832 return Unknown;
833 std::vector<unsigned char>
834 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
835 return ComplexPat;
Chris Lattnera938ac62009-07-29 20:43:05 +0000836 } else if (R->isSubClassOf("PointerLikeRegClass")) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000837 Other[0] = MVT::iPTR;
Chris Lattner6cefb772008-01-05 22:25:12 +0000838 return Other;
839 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
840 R->getName() == "zero_reg") {
841 // Placeholder.
842 return Unknown;
843 }
844
845 TP.error("Unknown node flavor used in pattern: " + R->getName());
846 return Other;
847}
848
Chris Lattnere67bde52008-01-06 05:36:50 +0000849
850/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
851/// CodeGenIntrinsic information for it, otherwise return a null pointer.
852const CodeGenIntrinsic *TreePatternNode::
853getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
854 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
855 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
856 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
857 return 0;
858
859 unsigned IID =
860 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
861 return &CDP.getIntrinsicInfo(IID);
862}
863
Chris Lattner47661322010-02-14 22:22:58 +0000864/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
865/// return the ComplexPattern information, otherwise return null.
866const ComplexPattern *
867TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
868 if (!isLeaf()) return 0;
869
870 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
871 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
872 return &CGP.getComplexPattern(DI->getDef());
873 return 0;
874}
875
876/// NodeHasProperty - Return true if this node has the specified property.
877bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +0000878 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +0000879 if (isLeaf()) {
880 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
881 return CP->hasProperty(Property);
882 return false;
883 }
884
885 Record *Operator = getOperator();
886 if (!Operator->isSubClassOf("SDNode")) return false;
887
888 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
889}
890
891
892
893
894/// TreeHasProperty - Return true if any node in this tree has the specified
895/// property.
896bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +0000897 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +0000898 if (NodeHasProperty(Property, CGP))
899 return true;
900 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
901 if (getChild(i)->TreeHasProperty(Property, CGP))
902 return true;
903 return false;
904}
905
Evan Cheng6bd95672008-06-16 20:29:38 +0000906/// isCommutativeIntrinsic - Return true if the node corresponds to a
907/// commutative intrinsic.
908bool
909TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
910 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
911 return Int->isCommutative;
912 return false;
913}
914
Chris Lattnere67bde52008-01-06 05:36:50 +0000915
Bob Wilson6c01ca92009-01-05 17:23:09 +0000916/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +0000917/// this node and its children in the tree. This returns true if it makes a
918/// change, false otherwise. If a type contradiction is found, throw an
919/// exception.
920bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +0000921 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +0000922 if (isLeaf()) {
923 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
924 // If it's a regclass or something else known, include the type.
925 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
Chris Lattner523f6a52010-02-14 21:10:15 +0000926 }
927
928 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000929 // Int inits are always integers. :)
Bob Wilsoncdfa01b2009-08-29 05:53:25 +0000930 bool MadeChange = UpdateNodeType(MVT::iAny, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000931
932 if (hasTypeSet()) {
933 // At some point, it may make sense for this tree pattern to have
934 // multiple types. Assert here that it does not, so we revisit this
935 // code when appropriate.
936 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000937 MVT::SimpleValueType VT = getTypeNum(0);
Chris Lattner6cefb772008-01-05 22:25:12 +0000938 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
939 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
940
941 VT = getTypeNum(0);
Owen Anderson825b72b2009-08-11 20:47:22 +0000942 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
Owen Andersone50ed302009-08-10 22:56:29 +0000943 unsigned Size = EVT(VT).getSizeInBits();
Chris Lattner6cefb772008-01-05 22:25:12 +0000944 // Make sure that the value is representable for this type.
945 if (Size < 32) {
946 int Val = (II->getValue() << (32-Size)) >> (32-Size);
Scott Michel0123b7d2008-02-15 23:05:48 +0000947 if (Val != II->getValue()) {
Bill Wendling27926af2008-02-26 10:45:29 +0000948 // If sign-extended doesn't fit, does it fit as unsigned?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000949 unsigned ValueMask;
950 unsigned UnsignedVal;
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +0000951 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
Duncan Sands83ec4b62008-06-06 12:08:01 +0000952 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +0000953
Bill Wendling27926af2008-02-26 10:45:29 +0000954 if ((ValueMask & UnsignedVal) != UnsignedVal) {
955 TP.error("Integer value '" + itostr(II->getValue())+
956 "' is out of range for type '" +
957 getEnumName(getTypeNum(0)) + "'!");
958 }
959 }
Nick Lewyckyfc4c2552009-06-17 04:23:52 +0000960 }
961 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000962 }
963
964 return MadeChange;
965 }
966 return false;
967 }
968
969 // special handling for set, which isn't really an SDNode.
970 if (getOperator()->getName() == "set") {
971 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
972 unsigned NC = getNumChildren();
973 bool MadeChange = false;
974 for (unsigned i = 0; i < NC-1; ++i) {
975 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
976 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
977
978 // Types of operands must match.
979 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
980 TP);
981 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
982 TP);
Owen Anderson825b72b2009-08-11 20:47:22 +0000983 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000984 }
985 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +0000986 }
987
988 if (getOperator()->getName() == "implicit" ||
989 getOperator()->getName() == "parallel") {
Chris Lattner6cefb772008-01-05 22:25:12 +0000990 bool MadeChange = false;
991 for (unsigned i = 0; i < getNumChildren(); ++i)
992 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Owen Anderson825b72b2009-08-11 20:47:22 +0000993 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000994 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +0000995 }
996
997 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +0000998 bool MadeChange = false;
999 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1000 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
Dan Gohmanf8c73942009-04-13 15:38:05 +00001001 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001002 }
1003
1004 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001005 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001006
Chris Lattner6cefb772008-01-05 22:25:12 +00001007 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001008 unsigned NumRetVTs = Int->IS.RetVTs.size();
1009 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001010
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001011 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1012 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1013
1014 if (getNumChildren() != NumParamVTs + NumRetVTs)
Chris Lattnere67bde52008-01-06 05:36:50 +00001015 TP.error("Intrinsic '" + Int->Name + "' expects " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001016 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1017 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001018
1019 // Apply type info to the intrinsic ID.
Owen Anderson825b72b2009-08-11 20:47:22 +00001020 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001021
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001022 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001023 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
Chris Lattner6cefb772008-01-05 22:25:12 +00001024 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1025 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1026 }
1027 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001028 }
1029
1030 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001031 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1032
1033 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1034 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1035 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1036 // Branch, etc. do not produce results and top-level forms in instr pattern
1037 // must have void types.
1038 if (NI.getNumResults() == 0)
Owen Anderson825b72b2009-08-11 20:47:22 +00001039 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001040
Chris Lattner6cefb772008-01-05 22:25:12 +00001041 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00001042 }
1043
1044 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001045 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1046 bool MadeChange = false;
1047 unsigned NumResults = Inst.getNumResults();
1048
1049 assert(NumResults <= 1 &&
1050 "Only supports zero or one result instrs!");
1051
1052 CodeGenInstruction &InstInfo =
1053 CDP.getTargetInfo().getInstruction(getOperator()->getName());
1054 // Apply the result type to the node
1055 if (NumResults == 0 || InstInfo.NumDefs == 0) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001056 MadeChange = UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001057 } else {
1058 Record *ResultNode = Inst.getResult(0);
1059
Chris Lattnera938ac62009-07-29 20:43:05 +00001060 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001061 std::vector<unsigned char> VT;
Owen Anderson825b72b2009-08-11 20:47:22 +00001062 VT.push_back(MVT::iPTR);
Chris Lattner6cefb772008-01-05 22:25:12 +00001063 MadeChange = UpdateNodeType(VT, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001064 } else if (ResultNode->getName() == "unknown") {
1065 std::vector<unsigned char> VT;
Owen Andersone50ed302009-08-10 22:56:29 +00001066 VT.push_back(EEVT::isUnknown);
Christopher Lamb5b415372008-03-11 09:33:47 +00001067 MadeChange = UpdateNodeType(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001068 } else {
1069 assert(ResultNode->isSubClassOf("RegisterClass") &&
1070 "Operands should be register classes!");
1071
1072 const CodeGenRegisterClass &RC =
1073 CDP.getTargetInfo().getRegisterClass(ResultNode);
1074 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1075 }
1076 }
1077
1078 unsigned ChildNo = 0;
1079 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1080 Record *OperandNode = Inst.getOperand(i);
1081
1082 // If the instruction expects a predicate or optional def operand, we
1083 // codegen this by setting the operand to it's default value if it has a
1084 // non-empty DefaultOps field.
1085 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1086 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1087 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1088 continue;
1089
1090 // Verify that we didn't run out of provided operands.
1091 if (ChildNo >= getNumChildren())
1092 TP.error("Instruction '" + getOperator()->getName() +
1093 "' expects more operands than were provided.");
1094
Owen Anderson825b72b2009-08-11 20:47:22 +00001095 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +00001096 TreePatternNode *Child = getChild(ChildNo++);
1097 if (OperandNode->isSubClassOf("RegisterClass")) {
1098 const CodeGenRegisterClass &RC =
1099 CDP.getTargetInfo().getRegisterClass(OperandNode);
1100 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
1101 } else if (OperandNode->isSubClassOf("Operand")) {
1102 VT = getValueType(OperandNode->getValueAsDef("Type"));
1103 MadeChange |= Child->UpdateNodeType(VT, TP);
Chris Lattnera938ac62009-07-29 20:43:05 +00001104 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001105 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +00001106 } else if (OperandNode->getName() == "unknown") {
Owen Andersone50ed302009-08-10 22:56:29 +00001107 MadeChange |= Child->UpdateNodeType(EEVT::isUnknown, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001108 } else {
1109 assert(0 && "Unknown operand type!");
1110 abort();
1111 }
1112 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1113 }
Christopher Lamb5b415372008-03-11 09:33:47 +00001114
Christopher Lamb02f69372008-03-10 04:16:09 +00001115 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +00001116 TP.error("Instruction '" + getOperator()->getName() +
1117 "' was provided too many operands!");
1118
1119 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00001120 }
Chris Lattner6eb30122010-02-23 05:51:07 +00001121
1122 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1123
1124 // Node transforms always take one operand.
1125 if (getNumChildren() != 1)
1126 TP.error("Node transform '" + getOperator()->getName() +
1127 "' requires one operand!");
1128
1129 // If either the output or input of the xform does not have exact
1130 // type info. We assume they must be the same. Otherwise, it is perfectly
1131 // legal to transform from one type to a completely different type.
1132 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1133 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1134 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1135 return MadeChange;
1136 }
1137 return false;
Chris Lattner6cefb772008-01-05 22:25:12 +00001138}
1139
1140/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1141/// RHS of a commutative operation, not the on LHS.
1142static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1143 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1144 return true;
1145 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1146 return true;
1147 return false;
1148}
1149
1150
1151/// canPatternMatch - If it is impossible for this pattern to match on this
1152/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001153/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001154/// that can never possibly work), and to prevent the pattern permuter from
1155/// generating stuff that is useless.
1156bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001157 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001158 if (isLeaf()) return true;
1159
1160 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1161 if (!getChild(i)->canPatternMatch(Reason, CDP))
1162 return false;
1163
1164 // If this is an intrinsic, handle cases that would make it not match. For
1165 // example, if an operand is required to be an immediate.
1166 if (getOperator()->isSubClassOf("Intrinsic")) {
1167 // TODO:
1168 return true;
1169 }
1170
1171 // If this node is a commutative operator, check that the LHS isn't an
1172 // immediate.
1173 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001174 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1175 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001176 // Scan all of the operands of the node and make sure that only the last one
1177 // is a constant node, unless the RHS also is.
1178 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001179 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1180 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001181 if (OnlyOnRHSOfCommutative(getChild(i))) {
1182 Reason="Immediate value must be on the RHS of commutative operators!";
1183 return false;
1184 }
1185 }
1186 }
1187
1188 return true;
1189}
1190
1191//===----------------------------------------------------------------------===//
1192// TreePattern implementation
1193//
1194
1195TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001196 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001197 isInputPattern = isInput;
1198 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1199 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1200}
1201
1202TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001203 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001204 isInputPattern = isInput;
1205 Trees.push_back(ParseTreePattern(Pat));
1206}
1207
1208TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001209 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001210 isInputPattern = isInput;
1211 Trees.push_back(Pat);
1212}
1213
1214
1215
1216void TreePattern::error(const std::string &Msg) const {
1217 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001218 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001219}
1220
1221TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1222 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1223 if (!OpDef) error("Pattern has unexpected operator type!");
1224 Record *Operator = OpDef->getDef();
1225
1226 if (Operator->isSubClassOf("ValueType")) {
1227 // If the operator is a ValueType, then this must be "type cast" of a leaf
1228 // node.
1229 if (Dag->getNumArgs() != 1)
1230 error("Type cast only takes one operand!");
1231
1232 Init *Arg = Dag->getArg(0);
1233 TreePatternNode *New;
1234 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1235 Record *R = DI->getDef();
1236 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001237 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001238 std::vector<std::pair<Init*, std::string> >()));
1239 return ParseTreePattern(Dag);
1240 }
Chris Lattner43e47542010-03-08 18:36:19 +00001241
1242 // Input argument?
1243 if (R->getName() == "node") {
1244 if (Dag->getArgName(0).empty())
1245 error("'node' argument requires a name to match with operand list");
1246 Args.push_back(Dag->getArgName(0));
1247 }
1248
Chris Lattner6cefb772008-01-05 22:25:12 +00001249 New = new TreePatternNode(DI);
1250 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1251 New = ParseTreePattern(DI);
1252 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1253 New = new TreePatternNode(II);
1254 if (!Dag->getArgName(0).empty())
1255 error("Constant int argument should not have a name!");
1256 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1257 // Turn this into an IntInit.
1258 Init *II = BI->convertInitializerTo(new IntRecTy());
1259 if (II == 0 || !dynamic_cast<IntInit*>(II))
1260 error("Bits value must be constants!");
1261
1262 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1263 if (!Dag->getArgName(0).empty())
1264 error("Constant int argument should not have a name!");
1265 } else {
1266 Arg->dump();
1267 error("Unknown leaf value for tree pattern!");
1268 return 0;
1269 }
1270
1271 // Apply the type cast.
1272 New->UpdateNodeType(getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001273 if (New->getNumChildren() == 0)
1274 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001275 return New;
1276 }
1277
1278 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001279 if (!Operator->isSubClassOf("PatFrag") &&
1280 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001281 !Operator->isSubClassOf("Instruction") &&
1282 !Operator->isSubClassOf("SDNodeXForm") &&
1283 !Operator->isSubClassOf("Intrinsic") &&
1284 Operator->getName() != "set" &&
1285 Operator->getName() != "implicit" &&
1286 Operator->getName() != "parallel")
1287 error("Unrecognized node '" + Operator->getName() + "'!");
1288
1289 // Check to see if this is something that is illegal in an input pattern.
1290 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1291 Operator->isSubClassOf("SDNodeXForm")))
1292 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1293
1294 std::vector<TreePatternNode*> Children;
1295
1296 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1297 Init *Arg = Dag->getArg(i);
1298 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1299 Children.push_back(ParseTreePattern(DI));
1300 if (Children.back()->getName().empty())
1301 Children.back()->setName(Dag->getArgName(i));
1302 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1303 Record *R = DefI->getDef();
1304 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1305 // TreePatternNode if its own.
1306 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001307 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001308 std::vector<std::pair<Init*, std::string> >()));
1309 --i; // Revisit this node...
1310 } else {
1311 TreePatternNode *Node = new TreePatternNode(DefI);
1312 Node->setName(Dag->getArgName(i));
1313 Children.push_back(Node);
1314
1315 // Input argument?
1316 if (R->getName() == "node") {
1317 if (Dag->getArgName(i).empty())
1318 error("'node' argument requires a name to match with operand list");
1319 Args.push_back(Dag->getArgName(i));
1320 }
1321 }
1322 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1323 TreePatternNode *Node = new TreePatternNode(II);
1324 if (!Dag->getArgName(i).empty())
1325 error("Constant int argument should not have a name!");
1326 Children.push_back(Node);
1327 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1328 // Turn this into an IntInit.
1329 Init *II = BI->convertInitializerTo(new IntRecTy());
1330 if (II == 0 || !dynamic_cast<IntInit*>(II))
1331 error("Bits value must be constants!");
1332
1333 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1334 if (!Dag->getArgName(i).empty())
1335 error("Constant int argument should not have a name!");
1336 Children.push_back(Node);
1337 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001338 errs() << '"';
Chris Lattner6cefb772008-01-05 22:25:12 +00001339 Arg->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001340 errs() << "\": ";
Chris Lattner6cefb772008-01-05 22:25:12 +00001341 error("Unknown leaf value for tree pattern!");
1342 }
1343 }
1344
1345 // If the operator is an intrinsic, then this is just syntactic sugar for for
1346 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1347 // convert the intrinsic name to a number.
1348 if (Operator->isSubClassOf("Intrinsic")) {
1349 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1350 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1351
1352 // If this intrinsic returns void, it must have side-effects and thus a
1353 // chain.
Owen Anderson825b72b2009-08-11 20:47:22 +00001354 if (Int.IS.RetVTs[0] == MVT::isVoid) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001355 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1356 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1357 // Has side-effects, requires chain.
1358 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1359 } else {
1360 // Otherwise, no chain.
1361 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1362 }
1363
1364 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1365 Children.insert(Children.begin(), IIDNode);
1366 }
1367
Nate Begeman7cee8172009-03-19 05:21:56 +00001368 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1369 Result->setName(Dag->getName());
1370 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001371}
1372
1373/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001374/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001375/// otherwise. Throw an exception if a type contradiction is found.
1376bool TreePattern::InferAllTypes() {
1377 bool MadeChange = true;
1378 while (MadeChange) {
1379 MadeChange = false;
1380 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1381 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1382 }
1383
1384 bool HasUnresolvedTypes = false;
1385 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1386 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1387 return !HasUnresolvedTypes;
1388}
1389
Daniel Dunbar1a551802009-07-03 00:10:29 +00001390void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001391 OS << getRecord()->getName();
1392 if (!Args.empty()) {
1393 OS << "(" << Args[0];
1394 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1395 OS << ", " << Args[i];
1396 OS << ")";
1397 }
1398 OS << ": ";
1399
1400 if (Trees.size() > 1)
1401 OS << "[\n";
1402 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1403 OS << "\t";
1404 Trees[i]->print(OS);
1405 OS << "\n";
1406 }
1407
1408 if (Trees.size() > 1)
1409 OS << "]\n";
1410}
1411
Daniel Dunbar1a551802009-07-03 00:10:29 +00001412void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00001413
1414//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001415// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001416//
1417
Chris Lattnerfe718932008-01-06 01:10:31 +00001418CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001419 Intrinsics = LoadIntrinsics(Records, false);
1420 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001421 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001422 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001423 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001424 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001425 ParseDefaultOperands();
1426 ParseInstructions();
1427 ParsePatterns();
1428
1429 // Generate variants. For example, commutative patterns can match
1430 // multiple ways. Add them to PatternsToMatch as well.
1431 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001432
1433 // Infer instruction flags. For example, we can detect loads,
1434 // stores, and side effects in many cases by examining an
1435 // instruction's pattern.
1436 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001437}
1438
Chris Lattnerfe718932008-01-06 01:10:31 +00001439CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00001440 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001441 E = PatternFragments.end(); I != E; ++I)
1442 delete I->second;
1443}
1444
1445
Chris Lattnerfe718932008-01-06 01:10:31 +00001446Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001447 Record *N = Records.getDef(Name);
1448 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001449 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner6cefb772008-01-05 22:25:12 +00001450 exit(1);
1451 }
1452 return N;
1453}
1454
1455// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001456void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001457 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1458 while (!Nodes.empty()) {
1459 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1460 Nodes.pop_back();
1461 }
1462
Jim Grosbachda4231f2009-03-26 16:17:51 +00001463 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001464 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1465 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1466 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1467}
1468
1469/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1470/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001471void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001472 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1473 while (!Xforms.empty()) {
1474 Record *XFormNode = Xforms.back();
1475 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1476 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001477 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001478
1479 Xforms.pop_back();
1480 }
1481}
1482
Chris Lattnerfe718932008-01-06 01:10:31 +00001483void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001484 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1485 while (!AMs.empty()) {
1486 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1487 AMs.pop_back();
1488 }
1489}
1490
1491
1492/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1493/// file, building up the PatternFragments map. After we've collected them all,
1494/// inline fragments together as necessary, so that there are no references left
1495/// inside a pattern fragment to a pattern fragment.
1496///
Chris Lattnerfe718932008-01-06 01:10:31 +00001497void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001498 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1499
Chris Lattnerdc32f982008-01-05 22:43:57 +00001500 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001501 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1502 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1503 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1504 PatternFragments[Fragments[i]] = P;
1505
Chris Lattnerdc32f982008-01-05 22:43:57 +00001506 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001507 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001508 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001509
Chris Lattnerdc32f982008-01-05 22:43:57 +00001510 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001511 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1512
1513 // Parse the operands list.
1514 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1515 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1516 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001517 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001518 if (!OpsOp ||
1519 (OpsOp->getDef()->getName() != "ops" &&
1520 OpsOp->getDef()->getName() != "outs" &&
1521 OpsOp->getDef()->getName() != "ins"))
1522 P->error("Operands list should start with '(ops ... '!");
1523
1524 // Copy over the arguments.
1525 Args.clear();
1526 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1527 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1528 static_cast<DefInit*>(OpsList->getArg(j))->
1529 getDef()->getName() != "node")
1530 P->error("Operands list should all be 'node' values.");
1531 if (OpsList->getArgName(j).empty())
1532 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001533 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001534 P->error("'" + OpsList->getArgName(j) +
1535 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001536 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001537 Args.push_back(OpsList->getArgName(j));
1538 }
1539
Chris Lattnerdc32f982008-01-05 22:43:57 +00001540 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001541 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001542 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001543
Chris Lattnerdc32f982008-01-05 22:43:57 +00001544 // If there is a code init for this fragment, keep track of the fact that
1545 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001546 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001547 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001548 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001549
1550 // If there is a node transformation corresponding to this, keep track of
1551 // it.
1552 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1553 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1554 P->getOnlyTree()->setTransformFn(Transform);
1555 }
1556
Chris Lattner6cefb772008-01-05 22:25:12 +00001557 // Now that we've parsed all of the tree fragments, do a closure on them so
1558 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001559 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1560 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001561 ThePat->InlinePatternFragments();
1562
1563 // Infer as many types as possible. Don't worry about it if we don't infer
1564 // all of them, some may depend on the inputs of the pattern.
1565 try {
1566 ThePat->InferAllTypes();
1567 } catch (...) {
1568 // If this pattern fragment is not supported by this target (no types can
1569 // satisfy its constraints), just ignore it. If the bogus pattern is
1570 // actually used by instructions, the type consistency error will be
1571 // reported there.
1572 }
1573
1574 // If debugging, print out the pattern fragment result.
1575 DEBUG(ThePat->dump());
1576 }
1577}
1578
Chris Lattnerfe718932008-01-06 01:10:31 +00001579void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001580 std::vector<Record*> DefaultOps[2];
1581 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1582 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1583
1584 // Find some SDNode.
1585 assert(!SDNodes.empty() && "No SDNodes parsed?");
1586 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1587
1588 for (unsigned iter = 0; iter != 2; ++iter) {
1589 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1590 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1591
1592 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1593 // SomeSDnode so that we can parse this.
1594 std::vector<std::pair<Init*, std::string> > Ops;
1595 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1596 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1597 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001598 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001599
1600 // Create a TreePattern to parse this.
1601 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1602 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1603
1604 // Copy the operands over into a DAGDefaultOperand.
1605 DAGDefaultOperand DefaultOpInfo;
1606
1607 TreePatternNode *T = P.getTree(0);
1608 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1609 TreePatternNode *TPN = T->getChild(op);
1610 while (TPN->ApplyTypeConstraints(P, false))
1611 /* Resolve all types */;
1612
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001613 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001614 if (iter == 0)
1615 throw "Value #" + utostr(i) + " of PredicateOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001616 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Chris Lattner6cefb772008-01-05 22:25:12 +00001617 else
1618 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
Chris Lattner53d09bd2010-02-23 05:59:10 +00001619 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001620 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001621 DefaultOpInfo.DefaultOps.push_back(TPN);
1622 }
1623
1624 // Insert it into the DefaultOperands map so we can find it later.
1625 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1626 }
1627 }
1628}
1629
1630/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1631/// instruction input. Return true if this is a real use.
1632static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1633 std::map<std::string, TreePatternNode*> &InstInputs,
1634 std::vector<Record*> &InstImpInputs) {
1635 // No name -> not interesting.
1636 if (Pat->getName().empty()) {
1637 if (Pat->isLeaf()) {
1638 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1639 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1640 I->error("Input " + DI->getDef()->getName() + " must be named!");
1641 else if (DI && DI->getDef()->isSubClassOf("Register"))
1642 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001643 }
1644 return false;
1645 }
1646
1647 Record *Rec;
1648 if (Pat->isLeaf()) {
1649 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1650 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1651 Rec = DI->getDef();
1652 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001653 Rec = Pat->getOperator();
1654 }
1655
1656 // SRCVALUE nodes are ignored.
1657 if (Rec->getName() == "srcvalue")
1658 return false;
1659
1660 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1661 if (!Slot) {
1662 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00001663 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00001664 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00001665 Record *SlotRec;
1666 if (Slot->isLeaf()) {
1667 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1668 } else {
1669 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1670 SlotRec = Slot->getOperator();
1671 }
1672
1673 // Ensure that the inputs agree if we've already seen this input.
1674 if (Rec != SlotRec)
1675 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1676 if (Slot->getExtTypes() != Pat->getExtTypes())
1677 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00001678 return true;
1679}
1680
1681/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1682/// part of "I", the instruction), computing the set of inputs and outputs of
1683/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001684void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001685FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1686 std::map<std::string, TreePatternNode*> &InstInputs,
1687 std::map<std::string, TreePatternNode*>&InstResults,
1688 std::vector<Record*> &InstImpInputs,
1689 std::vector<Record*> &InstImpResults) {
1690 if (Pat->isLeaf()) {
1691 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1692 if (!isUse && Pat->getTransformFn())
1693 I->error("Cannot specify a transform function for a non-input value!");
1694 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001695 }
1696
1697 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001698 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1699 TreePatternNode *Dest = Pat->getChild(i);
1700 if (!Dest->isLeaf())
1701 I->error("implicitly defined value should be a register!");
1702
1703 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1704 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1705 I->error("implicitly defined value should be a register!");
1706 InstImpResults.push_back(Val->getDef());
1707 }
1708 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001709 }
1710
1711 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00001712 // If this is not a set, verify that the children nodes are not void typed,
1713 // and recurse.
1714 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001715 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00001716 I->error("Cannot have void nodes inside of patterns!");
1717 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1718 InstImpInputs, InstImpResults);
1719 }
1720
1721 // If this is a non-leaf node with no children, treat it basically as if
1722 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00001723 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00001724
1725 if (!isUse && Pat->getTransformFn())
1726 I->error("Cannot specify a transform function for a non-input value!");
1727 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00001728 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001729
1730 // Otherwise, this is a set, validate and collect instruction results.
1731 if (Pat->getNumChildren() == 0)
1732 I->error("set requires operands!");
1733
1734 if (Pat->getTransformFn())
1735 I->error("Cannot specify a transform function on a set node!");
1736
1737 // Check the set destinations.
1738 unsigned NumDests = Pat->getNumChildren()-1;
1739 for (unsigned i = 0; i != NumDests; ++i) {
1740 TreePatternNode *Dest = Pat->getChild(i);
1741 if (!Dest->isLeaf())
1742 I->error("set destination should be a register!");
1743
1744 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1745 if (!Val)
1746 I->error("set destination should be a register!");
1747
1748 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00001749 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001750 if (Dest->getName().empty())
1751 I->error("set destination must have a name!");
1752 if (InstResults.count(Dest->getName()))
1753 I->error("cannot set '" + Dest->getName() +"' multiple times");
1754 InstResults[Dest->getName()] = Dest;
1755 } else if (Val->getDef()->isSubClassOf("Register")) {
1756 InstImpResults.push_back(Val->getDef());
1757 } else {
1758 I->error("set destination should be a register!");
1759 }
1760 }
1761
1762 // Verify and collect info from the computation.
1763 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1764 InstInputs, InstResults,
1765 InstImpInputs, InstImpResults);
1766}
1767
Dan Gohmanee4fa192008-04-03 00:02:49 +00001768//===----------------------------------------------------------------------===//
1769// Instruction Analysis
1770//===----------------------------------------------------------------------===//
1771
1772class InstAnalyzer {
1773 const CodeGenDAGPatterns &CDP;
1774 bool &mayStore;
1775 bool &mayLoad;
1776 bool &HasSideEffects;
1777public:
1778 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1779 bool &maystore, bool &mayload, bool &hse)
1780 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1781 }
1782
1783 /// Analyze - Analyze the specified instruction, returning true if the
1784 /// instruction had a pattern.
1785 bool Analyze(Record *InstRecord) {
1786 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1787 if (Pattern == 0) {
1788 HasSideEffects = 1;
1789 return false; // No pattern.
1790 }
1791
1792 // FIXME: Assume only the first tree is the pattern. The others are clobber
1793 // nodes.
1794 AnalyzeNode(Pattern->getTree(0));
1795 return true;
1796 }
1797
1798private:
1799 void AnalyzeNode(const TreePatternNode *N) {
1800 if (N->isLeaf()) {
1801 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1802 Record *LeafRec = DI->getDef();
1803 // Handle ComplexPattern leaves.
1804 if (LeafRec->isSubClassOf("ComplexPattern")) {
1805 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1806 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1807 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1808 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1809 }
1810 }
1811 return;
1812 }
1813
1814 // Analyze children.
1815 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1816 AnalyzeNode(N->getChild(i));
1817
1818 // Ignore set nodes, which are not SDNodes.
1819 if (N->getOperator()->getName() == "set")
1820 return;
1821
1822 // Get information about the SDNode for the operator.
1823 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1824
1825 // Notice properties of the node.
1826 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1827 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1828 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1829
1830 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1831 // If this is an intrinsic, analyze it.
1832 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1833 mayLoad = true;// These may load memory.
1834
1835 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1836 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1837
1838 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1839 // WriteMem intrinsics can have other strange effects.
1840 HasSideEffects = true;
1841 }
1842 }
1843
1844};
1845
1846static void InferFromPattern(const CodeGenInstruction &Inst,
1847 bool &MayStore, bool &MayLoad,
1848 bool &HasSideEffects,
1849 const CodeGenDAGPatterns &CDP) {
1850 MayStore = MayLoad = HasSideEffects = false;
1851
1852 bool HadPattern =
1853 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1854
1855 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1856 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1857 // If we decided that this is a store from the pattern, then the .td file
1858 // entry is redundant.
1859 if (MayStore)
1860 fprintf(stderr,
1861 "Warning: mayStore flag explicitly set on instruction '%s'"
1862 " but flag already inferred from pattern.\n",
1863 Inst.TheDef->getName().c_str());
1864 MayStore = true;
1865 }
1866
1867 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1868 // If we decided that this is a load from the pattern, then the .td file
1869 // entry is redundant.
1870 if (MayLoad)
1871 fprintf(stderr,
1872 "Warning: mayLoad flag explicitly set on instruction '%s'"
1873 " but flag already inferred from pattern.\n",
1874 Inst.TheDef->getName().c_str());
1875 MayLoad = true;
1876 }
1877
1878 if (Inst.neverHasSideEffects) {
1879 if (HadPattern)
1880 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1881 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1882 HasSideEffects = false;
1883 }
1884
1885 if (Inst.hasSideEffects) {
1886 if (HasSideEffects)
1887 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1888 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1889 HasSideEffects = true;
1890 }
1891}
1892
Chris Lattner6cefb772008-01-05 22:25:12 +00001893/// ParseInstructions - Parse all of the instructions, inlining and resolving
1894/// any fragments involved. This populates the Instructions list with fully
1895/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001896void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001897 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1898
1899 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1900 ListInit *LI = 0;
1901
1902 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1903 LI = Instrs[i]->getValueAsListInit("Pattern");
1904
1905 // If there is no pattern, only collect minimal information about the
1906 // instruction for its operand list. We have to assume that there is one
1907 // result, as we have no detailed info.
1908 if (!LI || LI->getSize() == 0) {
1909 std::vector<Record*> Results;
1910 std::vector<Record*> Operands;
1911
1912 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1913
1914 if (InstInfo.OperandList.size() != 0) {
1915 if (InstInfo.NumDefs == 0) {
1916 // These produce no results
1917 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1918 Operands.push_back(InstInfo.OperandList[j].Rec);
1919 } else {
1920 // Assume the first operand is the result.
1921 Results.push_back(InstInfo.OperandList[0].Rec);
1922
1923 // The rest are inputs.
1924 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1925 Operands.push_back(InstInfo.OperandList[j].Rec);
1926 }
1927 }
1928
1929 // Create and insert the instruction.
1930 std::vector<Record*> ImpResults;
1931 std::vector<Record*> ImpOperands;
1932 Instructions.insert(std::make_pair(Instrs[i],
1933 DAGInstruction(0, Results, Operands, ImpResults,
1934 ImpOperands)));
1935 continue; // no pattern.
1936 }
1937
1938 // Parse the instruction.
1939 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1940 // Inline pattern fragments into it.
1941 I->InlinePatternFragments();
1942
1943 // Infer as many types as possible. If we cannot infer all of them, we can
1944 // never do anything with this instruction pattern: report it to the user.
1945 if (!I->InferAllTypes())
1946 I->error("Could not infer all types in pattern!");
1947
1948 // InstInputs - Keep track of all of the inputs of the instruction, along
1949 // with the record they are declared as.
1950 std::map<std::string, TreePatternNode*> InstInputs;
1951
1952 // InstResults - Keep track of all the virtual registers that are 'set'
1953 // in the instruction, including what reg class they are.
1954 std::map<std::string, TreePatternNode*> InstResults;
1955
1956 std::vector<Record*> InstImpInputs;
1957 std::vector<Record*> InstImpResults;
1958
1959 // Verify that the top-level forms in the instruction are of void type, and
1960 // fill in the InstResults map.
1961 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1962 TreePatternNode *Pat = I->getTree(j);
Owen Anderson825b72b2009-08-11 20:47:22 +00001963 if (Pat->getExtTypeNum(0) != MVT::isVoid)
Chris Lattner6cefb772008-01-05 22:25:12 +00001964 I->error("Top-level forms in instruction pattern should have"
1965 " void types");
1966
1967 // Find inputs and outputs, and verify the structure of the uses/defs.
1968 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1969 InstImpInputs, InstImpResults);
1970 }
1971
1972 // Now that we have inputs and outputs of the pattern, inspect the operands
1973 // list for the instruction. This determines the order that operands are
1974 // added to the machine instruction the node corresponds to.
1975 unsigned NumResults = InstResults.size();
1976
1977 // Parse the operands list from the (ops) list, validating it.
1978 assert(I->getArgList().empty() && "Args list should still be empty here!");
1979 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1980
1981 // Check that all of the results occur first in the list.
1982 std::vector<Record*> Results;
1983 TreePatternNode *Res0Node = NULL;
1984 for (unsigned i = 0; i != NumResults; ++i) {
1985 if (i == CGI.OperandList.size())
1986 I->error("'" + InstResults.begin()->first +
1987 "' set but does not appear in operand list!");
1988 const std::string &OpName = CGI.OperandList[i].Name;
1989
1990 // Check that it exists in InstResults.
1991 TreePatternNode *RNode = InstResults[OpName];
1992 if (RNode == 0)
1993 I->error("Operand $" + OpName + " does not exist in operand list!");
1994
1995 if (i == 0)
1996 Res0Node = RNode;
1997 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1998 if (R == 0)
1999 I->error("Operand $" + OpName + " should be a set destination: all "
2000 "outputs must occur before inputs in operand list!");
2001
2002 if (CGI.OperandList[i].Rec != R)
2003 I->error("Operand $" + OpName + " class mismatch!");
2004
2005 // Remember the return type.
2006 Results.push_back(CGI.OperandList[i].Rec);
2007
2008 // Okay, this one checks out.
2009 InstResults.erase(OpName);
2010 }
2011
2012 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2013 // the copy while we're checking the inputs.
2014 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2015
2016 std::vector<TreePatternNode*> ResultNodeOperands;
2017 std::vector<Record*> Operands;
2018 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2019 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2020 const std::string &OpName = Op.Name;
2021 if (OpName.empty())
2022 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2023
2024 if (!InstInputsCheck.count(OpName)) {
2025 // If this is an predicate operand or optional def operand with an
2026 // DefaultOps set filled in, we can ignore this. When we codegen it,
2027 // we will do so as always executed.
2028 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2029 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2030 // Does it have a non-empty DefaultOps field? If so, ignore this
2031 // operand.
2032 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2033 continue;
2034 }
2035 I->error("Operand $" + OpName +
2036 " does not appear in the instruction pattern");
2037 }
2038 TreePatternNode *InVal = InstInputsCheck[OpName];
2039 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2040
2041 if (InVal->isLeaf() &&
2042 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2043 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2044 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2045 I->error("Operand $" + OpName + "'s register class disagrees"
2046 " between the operand and pattern");
2047 }
2048 Operands.push_back(Op.Rec);
2049
2050 // Construct the result for the dest-pattern operand list.
2051 TreePatternNode *OpNode = InVal->clone();
2052
2053 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00002054 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002055
2056 // Promote the xform function to be an explicit node if set.
2057 if (Record *Xform = OpNode->getTransformFn()) {
2058 OpNode->setTransformFn(0);
2059 std::vector<TreePatternNode*> Children;
2060 Children.push_back(OpNode);
2061 OpNode = new TreePatternNode(Xform, Children);
2062 }
2063
2064 ResultNodeOperands.push_back(OpNode);
2065 }
2066
2067 if (!InstInputsCheck.empty())
2068 I->error("Input operand $" + InstInputsCheck.begin()->first +
2069 " occurs in pattern but not in operands list!");
2070
2071 TreePatternNode *ResultPattern =
2072 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2073 // Copy fully inferred output node type to instruction result pattern.
2074 if (NumResults > 0)
2075 ResultPattern->setTypes(Res0Node->getExtTypes());
2076
2077 // Create and insert the instruction.
2078 // FIXME: InstImpResults and InstImpInputs should not be part of
2079 // DAGInstruction.
2080 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2081 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2082
2083 // Use a temporary tree pattern to infer all types and make sure that the
2084 // constructed result is correct. This depends on the instruction already
2085 // being inserted into the Instructions map.
2086 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2087 Temp.InferAllTypes();
2088
2089 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2090 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2091
2092 DEBUG(I->dump());
2093 }
2094
2095 // If we can, convert the instructions to be patterns that are matched!
Benjamin Kramer5b9e7ef2009-08-23 10:39:21 +00002096 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2097 Instructions.begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00002098 E = Instructions.end(); II != E; ++II) {
2099 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00002100 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00002101 if (I == 0) continue; // No pattern.
2102
2103 // FIXME: Assume only the first tree is the pattern. The others are clobber
2104 // nodes.
2105 TreePatternNode *Pattern = I->getTree(0);
2106 TreePatternNode *SrcPattern;
2107 if (Pattern->getOperator()->getName() == "set") {
2108 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2109 } else{
2110 // Not a set (store or something?)
2111 SrcPattern = Pattern;
2112 }
2113
Chris Lattner6cefb772008-01-05 22:25:12 +00002114 Record *Instr = II->first;
Chris Lattner25b6f912010-02-23 06:16:51 +00002115 AddPatternToMatch(I,
2116 PatternToMatch(Instr->getValueAsListInit("Predicates"),
Chris Lattner967d54a2010-02-23 06:35:45 +00002117 SrcPattern,
2118 TheInst.getResultPattern(),
Chris Lattner25b6f912010-02-23 06:16:51 +00002119 TheInst.getImpResults(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002120 Instr->getValueAsInt("AddedComplexity"),
2121 Instr->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002122 }
2123}
2124
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002125
2126typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2127
Chris Lattner967d54a2010-02-23 06:35:45 +00002128static void FindNames(const TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00002129 std::map<std::string, NameRecord> &Names,
2130 const TreePattern *PatternTop) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002131 if (!P->getName().empty()) {
2132 NameRecord &Rec = Names[P->getName()];
2133 // If this is the first instance of the name, remember the node.
2134 if (Rec.second++ == 0)
2135 Rec.first = P;
Chris Lattnera27234e2010-02-23 07:22:28 +00002136 else if (Rec.first->getExtTypes() != P->getExtTypes())
2137 PatternTop->error("repetition of value: $" + P->getName() +
2138 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002139 }
Chris Lattner967d54a2010-02-23 06:35:45 +00002140
2141 if (!P->isLeaf()) {
2142 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattnera27234e2010-02-23 07:22:28 +00002143 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00002144 }
2145}
2146
Chris Lattner25b6f912010-02-23 06:16:51 +00002147void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2148 const PatternToMatch &PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00002149 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00002150 std::string Reason;
2151 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
Chris Lattner967d54a2010-02-23 06:35:45 +00002152 Pattern->error("Pattern can never match: " + Reason);
Chris Lattner25b6f912010-02-23 06:16:51 +00002153
Chris Lattner405f1252010-03-01 22:29:19 +00002154 // If the source pattern's root is a complex pattern, that complex pattern
2155 // must specify the nodes it can potentially match.
2156 if (const ComplexPattern *CP =
2157 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2158 if (CP->getRootNodes().empty())
2159 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2160 " could match");
2161
2162
Chris Lattner967d54a2010-02-23 06:35:45 +00002163 // Find all of the named values in the input and output, ensure they have the
2164 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002165 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattnera27234e2010-02-23 07:22:28 +00002166 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2167 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00002168
2169 // Scan all of the named values in the destination pattern, rejecting them if
2170 // they don't exist in the input pattern.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002171 for (std::map<std::string, NameRecord>::iterator
Chris Lattnerba1cff42010-02-23 07:50:58 +00002172 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002173 if (SrcNames[I->first].first == 0)
Chris Lattner967d54a2010-02-23 06:35:45 +00002174 Pattern->error("Pattern has input without matching name in output: $" +
2175 I->first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00002176
2177#if 0
2178 const std::vector<unsigned char> &SrcTypeVec =
2179 SrcNames[I->first].first->getExtTypes();
2180 const std::vector<unsigned char> &DstTypeVec =
2181 I->second.first->getExtTypes();
2182 if (SrcTypeVec == DstTypeVec) continue;
2183
2184 std::string SrcType, DstType;
2185 for (unsigned i = 0, e = SrcTypeVec.size(); i != e; ++i)
2186 SrcType += ":" + GetTypeName(SrcTypeVec[i]);
2187 for (unsigned i = 0, e = DstTypeVec.size(); i != e; ++i)
2188 DstType += ":" + GetTypeName(DstTypeVec[i]);
2189
2190 Pattern->error("Variable $" + I->first +
2191 " has different types in source (" + SrcType +
2192 ") and dest (" + DstType + ") pattern!");
2193#endif
2194 }
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00002195
2196 // Scan all of the named values in the source pattern, rejecting them if the
2197 // name isn't used in the dest, and isn't used to tie two values together.
2198 for (std::map<std::string, NameRecord>::iterator
2199 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2200 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2201 Pattern->error("Pattern has dead named input: $" + I->first);
2202
Chris Lattner25b6f912010-02-23 06:16:51 +00002203 PatternsToMatch.push_back(PTM);
2204}
2205
2206
Dan Gohmanee4fa192008-04-03 00:02:49 +00002207
2208void CodeGenDAGPatterns::InferInstructionFlags() {
2209 std::map<std::string, CodeGenInstruction> &InstrDescs =
2210 Target.getInstructions();
2211 for (std::map<std::string, CodeGenInstruction>::iterator
2212 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2213 CodeGenInstruction &InstInfo = II->second;
2214 // Determine properties of the instruction from its pattern.
2215 bool MayStore, MayLoad, HasSideEffects;
2216 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2217 InstInfo.mayStore = MayStore;
2218 InstInfo.mayLoad = MayLoad;
2219 InstInfo.hasSideEffects = HasSideEffects;
2220 }
2221}
2222
Chris Lattnerfe718932008-01-06 01:10:31 +00002223void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002224 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2225
2226 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2227 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2228 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2229 Record *Operator = OpDef->getDef();
2230 TreePattern *Pattern;
2231 if (Operator->getName() != "parallel")
2232 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2233 else {
2234 std::vector<Init*> Values;
David Greenee1b46912009-06-08 20:23:18 +00002235 RecTy *ListTy = 0;
2236 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002237 Values.push_back(Tree->getArg(j));
David Greenee1b46912009-06-08 20:23:18 +00002238 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2239 if (TArg == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002240 errs() << "In dag: " << Tree->getAsString();
2241 errs() << " -- Untyped argument in pattern\n";
David Greenee1b46912009-06-08 20:23:18 +00002242 assert(0 && "Untyped argument in pattern");
2243 }
2244 if (ListTy != 0) {
2245 ListTy = resolveTypes(ListTy, TArg->getType());
2246 if (ListTy == 0) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00002247 errs() << "In dag: " << Tree->getAsString();
2248 errs() << " -- Incompatible types in pattern arguments\n";
David Greenee1b46912009-06-08 20:23:18 +00002249 assert(0 && "Incompatible types in pattern arguments");
2250 }
2251 }
2252 else {
Bill Wendlingee1f6b02009-06-09 18:49:42 +00002253 ListTy = TArg->getType();
David Greenee1b46912009-06-08 20:23:18 +00002254 }
2255 }
2256 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
Chris Lattner6cefb772008-01-05 22:25:12 +00002257 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2258 }
2259
2260 // Inline pattern fragments into it.
2261 Pattern->InlinePatternFragments();
2262
2263 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2264 if (LI->getSize() == 0) continue; // no pattern.
2265
2266 // Parse the instruction.
2267 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2268
2269 // Inline pattern fragments into it.
2270 Result->InlinePatternFragments();
2271
2272 if (Result->getNumTrees() != 1)
2273 Result->error("Cannot handle instructions producing instructions "
2274 "with temporaries yet!");
2275
2276 bool IterateInference;
2277 bool InferredAllPatternTypes, InferredAllResultTypes;
2278 do {
2279 // Infer as many types as possible. If we cannot infer all of them, we
2280 // can never do anything with this pattern: report it to the user.
2281 InferredAllPatternTypes = Pattern->InferAllTypes();
2282
2283 // Infer as many types as possible. If we cannot infer all of them, we
2284 // can never do anything with this pattern: report it to the user.
2285 InferredAllResultTypes = Result->InferAllTypes();
2286
2287 // Apply the type of the result to the source pattern. This helps us
2288 // resolve cases where the input type is known to be a pointer type (which
2289 // is considered resolved), but the result knows it needs to be 32- or
2290 // 64-bits. Infer the other way for good measure.
2291 IterateInference = Pattern->getTree(0)->
2292 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2293 IterateInference |= Result->getTree(0)->
2294 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2295 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002296
Chris Lattner6cefb772008-01-05 22:25:12 +00002297 // Verify that we inferred enough types that we can do something with the
2298 // pattern and result. If these fire the user has to add type casts.
2299 if (!InferredAllPatternTypes)
2300 Pattern->error("Could not infer all types in pattern!");
2301 if (!InferredAllResultTypes)
2302 Result->error("Could not infer all types in pattern result!");
2303
2304 // Validate that the input pattern is correct.
2305 std::map<std::string, TreePatternNode*> InstInputs;
2306 std::map<std::string, TreePatternNode*> InstResults;
2307 std::vector<Record*> InstImpInputs;
2308 std::vector<Record*> InstImpResults;
2309 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2310 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2311 InstInputs, InstResults,
2312 InstImpInputs, InstImpResults);
2313
2314 // Promote the xform function to be an explicit node if set.
2315 TreePatternNode *DstPattern = Result->getOnlyTree();
2316 std::vector<TreePatternNode*> ResultNodeOperands;
2317 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2318 TreePatternNode *OpNode = DstPattern->getChild(ii);
2319 if (Record *Xform = OpNode->getTransformFn()) {
2320 OpNode->setTransformFn(0);
2321 std::vector<TreePatternNode*> Children;
2322 Children.push_back(OpNode);
2323 OpNode = new TreePatternNode(Xform, Children);
2324 }
2325 ResultNodeOperands.push_back(OpNode);
2326 }
2327 DstPattern = Result->getOnlyTree();
2328 if (!DstPattern->isLeaf())
2329 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2330 ResultNodeOperands);
2331 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2332 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2333 Temp.InferAllTypes();
2334
Chris Lattner6cefb772008-01-05 22:25:12 +00002335
Chris Lattner25b6f912010-02-23 06:16:51 +00002336 AddPatternToMatch(Pattern,
2337 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2338 Pattern->getTree(0),
2339 Temp.getOnlyTree(), InstImpResults,
Chris Lattner117ccb72010-03-01 22:09:11 +00002340 Patterns[i]->getValueAsInt("AddedComplexity"),
2341 Patterns[i]->getID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002342 }
2343}
2344
2345/// CombineChildVariants - Given a bunch of permutations of each child of the
2346/// 'operator' node, put them together in all possible ways.
2347static void CombineChildVariants(TreePatternNode *Orig,
2348 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2349 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002350 CodeGenDAGPatterns &CDP,
2351 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002352 // Make sure that each operand has at least one variant to choose from.
2353 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2354 if (ChildVariants[i].empty())
2355 return;
2356
2357 // The end result is an all-pairs construction of the resultant pattern.
2358 std::vector<unsigned> Idxs;
2359 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002360 bool NotDone;
2361 do {
2362#ifndef NDEBUG
Chris Lattneraaf54862010-02-27 06:51:44 +00002363 DEBUG(if (!Idxs.empty()) {
2364 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2365 for (unsigned i = 0; i < Idxs.size(); ++i) {
2366 errs() << Idxs[i] << " ";
2367 }
2368 errs() << "]\n";
2369 });
Scott Michel327d0652008-03-05 17:49:05 +00002370#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002371 // Create the variant and add it to the output list.
2372 std::vector<TreePatternNode*> NewChildren;
2373 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2374 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2375 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2376
2377 // Copy over properties.
2378 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002379 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002380 R->setTransformFn(Orig->getTransformFn());
2381 R->setTypes(Orig->getExtTypes());
2382
Scott Michel327d0652008-03-05 17:49:05 +00002383 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002384 std::string ErrString;
2385 if (!R->canPatternMatch(ErrString, CDP)) {
2386 delete R;
2387 } else {
2388 bool AlreadyExists = false;
2389
2390 // Scan to see if this pattern has already been emitted. We can get
2391 // duplication due to things like commuting:
2392 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2393 // which are the same pattern. Ignore the dups.
2394 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002395 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002396 AlreadyExists = true;
2397 break;
2398 }
2399
2400 if (AlreadyExists)
2401 delete R;
2402 else
2403 OutVariants.push_back(R);
2404 }
2405
Scott Michel327d0652008-03-05 17:49:05 +00002406 // Increment indices to the next permutation by incrementing the
2407 // indicies from last index backward, e.g., generate the sequence
2408 // [0, 0], [0, 1], [1, 0], [1, 1].
2409 int IdxsIdx;
2410 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2411 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2412 Idxs[IdxsIdx] = 0;
2413 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002414 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002415 }
Scott Michel327d0652008-03-05 17:49:05 +00002416 NotDone = (IdxsIdx >= 0);
2417 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002418}
2419
2420/// CombineChildVariants - A helper function for binary operators.
2421///
2422static void CombineChildVariants(TreePatternNode *Orig,
2423 const std::vector<TreePatternNode*> &LHS,
2424 const std::vector<TreePatternNode*> &RHS,
2425 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002426 CodeGenDAGPatterns &CDP,
2427 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002428 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2429 ChildVariants.push_back(LHS);
2430 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002431 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002432}
2433
2434
2435static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2436 std::vector<TreePatternNode *> &Children) {
2437 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2438 Record *Operator = N->getOperator();
2439
2440 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002441 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002442 N->getTransformFn()) {
2443 Children.push_back(N);
2444 return;
2445 }
2446
2447 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2448 Children.push_back(N->getChild(0));
2449 else
2450 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2451
2452 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2453 Children.push_back(N->getChild(1));
2454 else
2455 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2456}
2457
2458/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2459/// the (potentially recursive) pattern by using algebraic laws.
2460///
2461static void GenerateVariantsOf(TreePatternNode *N,
2462 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002463 CodeGenDAGPatterns &CDP,
2464 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002465 // We cannot permute leaves.
2466 if (N->isLeaf()) {
2467 OutVariants.push_back(N);
2468 return;
2469 }
2470
2471 // Look up interesting info about the node.
2472 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2473
Jim Grosbachda4231f2009-03-26 16:17:51 +00002474 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002475 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002476 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002477 std::vector<TreePatternNode*> MaximalChildren;
2478 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2479
2480 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2481 // permutations.
2482 if (MaximalChildren.size() == 3) {
2483 // Find the variants of all of our maximal children.
2484 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002485 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2486 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2487 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002488
2489 // There are only two ways we can permute the tree:
2490 // (A op B) op C and A op (B op C)
2491 // Within these forms, we can also permute A/B/C.
2492
2493 // Generate legal pair permutations of A/B/C.
2494 std::vector<TreePatternNode*> ABVariants;
2495 std::vector<TreePatternNode*> BAVariants;
2496 std::vector<TreePatternNode*> ACVariants;
2497 std::vector<TreePatternNode*> CAVariants;
2498 std::vector<TreePatternNode*> BCVariants;
2499 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002500 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2501 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2502 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2503 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2504 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2505 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002506
2507 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002508 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2509 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2510 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2511 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2512 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2513 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002514
2515 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002516 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2517 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2518 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2519 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2520 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2521 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002522 return;
2523 }
2524 }
2525
2526 // Compute permutations of all children.
2527 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2528 ChildVariants.resize(N->getNumChildren());
2529 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002530 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002531
2532 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002533 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002534
2535 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002536 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2537 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2538 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2539 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002540 // Don't count children which are actually register references.
2541 unsigned NC = 0;
2542 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2543 TreePatternNode *Child = N->getChild(i);
2544 if (Child->isLeaf())
2545 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2546 Record *RR = DI->getDef();
2547 if (RR->isSubClassOf("Register"))
2548 continue;
2549 }
2550 NC++;
2551 }
2552 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002553 if (isCommIntrinsic) {
2554 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2555 // operands are the commutative operands, and there might be more operands
2556 // after those.
2557 assert(NC >= 3 &&
2558 "Commutative intrinsic should have at least 3 childrean!");
2559 std::vector<std::vector<TreePatternNode*> > Variants;
2560 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2561 Variants.push_back(ChildVariants[2]);
2562 Variants.push_back(ChildVariants[1]);
2563 for (unsigned i = 3; i != NC; ++i)
2564 Variants.push_back(ChildVariants[i]);
2565 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2566 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002567 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002568 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002569 }
2570}
2571
2572
2573// GenerateVariants - Generate variants. For example, commutative patterns can
2574// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002575void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner569f1212009-08-23 04:44:11 +00002576 DEBUG(errs() << "Generating instruction variants.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002577
2578 // Loop over all of the patterns we've collected, checking to see if we can
2579 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002580 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002581 // the .td file having to contain tons of variants of instructions.
2582 //
2583 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2584 // intentionally do not reconsider these. Any variants of added patterns have
2585 // already been added.
2586 //
2587 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002588 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002589 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002590 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner569f1212009-08-23 04:44:11 +00002591 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel327d0652008-03-05 17:49:05 +00002592 DEBUG(DumpDepVars(DepVars));
Chris Lattner569f1212009-08-23 04:44:11 +00002593 DEBUG(errs() << "\n");
Scott Michel327d0652008-03-05 17:49:05 +00002594 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002595
2596 assert(!Variants.empty() && "Must create at least original variant!");
2597 Variants.erase(Variants.begin()); // Remove the original pattern.
2598
2599 if (Variants.empty()) // No variants for this pattern.
2600 continue;
2601
Chris Lattner569f1212009-08-23 04:44:11 +00002602 DEBUG(errs() << "FOUND VARIANTS OF: ";
2603 PatternsToMatch[i].getSrcPattern()->dump();
2604 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002605
2606 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2607 TreePatternNode *Variant = Variants[v];
2608
Chris Lattner569f1212009-08-23 04:44:11 +00002609 DEBUG(errs() << " VAR#" << v << ": ";
2610 Variant->dump();
2611 errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002612
2613 // Scan to see if an instruction or explicit pattern already matches this.
2614 bool AlreadyExists = false;
2615 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00002616 // Skip if the top level predicates do not match.
2617 if (PatternsToMatch[i].getPredicates() !=
2618 PatternsToMatch[p].getPredicates())
2619 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00002620 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002621 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner569f1212009-08-23 04:44:11 +00002622 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002623 AlreadyExists = true;
2624 break;
2625 }
2626 }
2627 // If we already have it, ignore the variant.
2628 if (AlreadyExists) continue;
2629
2630 // Otherwise, add it to the list of patterns we have.
2631 PatternsToMatch.
2632 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2633 Variant, PatternsToMatch[i].getDstPattern(),
2634 PatternsToMatch[i].getDstRegs(),
Chris Lattner117ccb72010-03-01 22:09:11 +00002635 PatternsToMatch[i].getAddedComplexity(),
2636 Record::getNewUID()));
Chris Lattner6cefb772008-01-05 22:25:12 +00002637 }
2638
Chris Lattner569f1212009-08-23 04:44:11 +00002639 DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00002640 }
2641}
2642