blob: a03224cdd5a9742198805e3b7526d2d3ed185f86 [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 "llvm/Support/Streams.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000020#include <set>
Chuck Rose III9a79de32008-01-15 21:43:17 +000021#include <algorithm>
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>
Duncan Sands83ec4b62008-06-06 12:08:01 +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)
Duncan Sands83ec4b62008-06-06 12:08:01 +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>
Duncan Sands83ec4b62008-06-06 12:08:01 +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
Duncan Sands83ec4b62008-06-06 12:08:01 +000057static inline bool isInteger(MVT::SimpleValueType VT) {
58 return MVT(VT).isInteger();
59}
60
61static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
62 return MVT(VT).isFloatingPoint();
63}
64
65static inline bool isVector(MVT::SimpleValueType VT) {
66 return MVT(VT).isVector();
67}
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 {
Duncan Sands83ec4b62008-06-06 12:08:01 +000079namespace EMVT {
Dan Gohman4b6fce42009-03-31 16:48:35 +000080/// isExtIntegerInVTs - Return true if the specified extended value type vector
81/// contains isInt 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!");
84 return EVTs[0] == isInt || !(FilterEVTs(EVTs, isInteger).empty());
85}
86
Dan Gohman4b6fce42009-03-31 16:48:35 +000087/// isExtFloatingPointInVTs - Return true if the specified extended value type
Chris Lattner6cefb772008-01-05 22:25:12 +000088/// vector contains isFP or a FP value type.
89bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs) {
90 assert(!EVTs.empty() && "Cannot check for integer in empty ExtVT list!");
91 return EVTs[0] == isFP || !(FilterEVTs(EVTs, isFloatingPoint).empty());
92}
Duncan Sands83ec4b62008-06-06 12:08:01 +000093} // end namespace EMVT.
Chris Lattner6cefb772008-01-05 22:25:12 +000094} // end namespace llvm.
95
Scott Michel327d0652008-03-05 17:49:05 +000096
97/// Dependent variable map for CodeGenDAGPattern variant generation
98typedef std::map<std::string, int> DepVarMap;
99
100/// Const iterator shorthand for DepVarMap
101typedef DepVarMap::const_iterator DepVarMap_citer;
102
103namespace {
104void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
105 if (N->isLeaf()) {
106 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
107 DepMap[N->getName()]++;
108 }
109 } else {
110 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
111 FindDepVarsOf(N->getChild(i), DepMap);
112 }
113}
114
115//! Find dependent variables within child patterns
116/*!
117 */
118void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
119 DepVarMap depcounts;
120 FindDepVarsOf(N, depcounts);
121 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
122 if (i->second > 1) { // std::pair<std::string, int>
123 DepVars.insert(i->first);
124 }
125 }
126}
127
128//! Dump the dependent variable set:
129void DumpDepVars(MultipleUseVarSet &DepVars) {
130 if (DepVars.empty()) {
131 DOUT << "<empty set>";
132 } else {
133 DOUT << "[ ";
134 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
135 i != e; ++i) {
136 DOUT << (*i) << " ";
137 }
138 DOUT << "]";
139 }
140}
141}
142
Chris Lattner6cefb772008-01-05 22:25:12 +0000143//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +0000144// PatternToMatch implementation
145//
146
147/// getPredicateCheck - Return a single string containing all of this
148/// pattern's predicates concatenated with "&&" operators.
149///
150std::string PatternToMatch::getPredicateCheck() const {
151 std::string PredicateCheck;
152 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
153 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
154 Record *Def = Pred->getDef();
155 if (!Def->isSubClassOf("Predicate")) {
156#ifndef NDEBUG
157 Def->dump();
158#endif
159 assert(0 && "Unknown predicate type!");
160 }
161 if (!PredicateCheck.empty())
162 PredicateCheck += " && ";
163 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
164 }
165 }
166
167 return PredicateCheck;
168}
169
170//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +0000171// SDTypeConstraint implementation
172//
173
174SDTypeConstraint::SDTypeConstraint(Record *R) {
175 OperandNo = R->getValueAsInt("OperandNum");
176
177 if (R->isSubClassOf("SDTCisVT")) {
178 ConstraintType = SDTCisVT;
179 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
180 } else if (R->isSubClassOf("SDTCisPtrTy")) {
181 ConstraintType = SDTCisPtrTy;
182 } else if (R->isSubClassOf("SDTCisInt")) {
183 ConstraintType = SDTCisInt;
184 } else if (R->isSubClassOf("SDTCisFP")) {
185 ConstraintType = SDTCisFP;
186 } else if (R->isSubClassOf("SDTCisSameAs")) {
187 ConstraintType = SDTCisSameAs;
188 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
189 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
190 ConstraintType = SDTCisVTSmallerThanOp;
191 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
192 R->getValueAsInt("OtherOperandNum");
193 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
194 ConstraintType = SDTCisOpSmallerThanOp;
195 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
196 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +0000197 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
198 ConstraintType = SDTCisEltOfVec;
199 x.SDTCisEltOfVec_Info.OtherOperandNum =
200 R->getValueAsInt("OtherOpNum");
Chris Lattner6cefb772008-01-05 22:25:12 +0000201 } else {
202 cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
203 exit(1);
204 }
205}
206
207/// getOperandNum - Return the node corresponding to operand #OpNo in tree
208/// N, which has NumResults results.
209TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
210 TreePatternNode *N,
211 unsigned NumResults) const {
212 assert(NumResults <= 1 &&
213 "We only work with nodes with zero or one result so far!");
214
215 if (OpNo >= (NumResults + N->getNumChildren())) {
216 cerr << "Invalid operand number " << OpNo << " ";
217 N->dump();
218 cerr << '\n';
219 exit(1);
220 }
221
222 if (OpNo < NumResults)
223 return N; // FIXME: need value #
224 else
225 return N->getChild(OpNo-NumResults);
226}
227
228/// ApplyTypeConstraint - Given a node in a pattern, apply this type
229/// constraint to the nodes operands. This returns true if it makes a
230/// change, false otherwise. If a type contradiction is found, throw an
231/// exception.
232bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
233 const SDNodeInfo &NodeInfo,
234 TreePattern &TP) const {
235 unsigned NumResults = NodeInfo.getNumResults();
236 assert(NumResults <= 1 &&
237 "We only work with nodes with zero or one result so far!");
238
239 // Check that the number of operands is sane. Negative operands -> varargs.
240 if (NodeInfo.getNumOperands() >= 0) {
241 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
242 TP.error(N->getOperator()->getName() + " node requires exactly " +
243 itostr(NodeInfo.getNumOperands()) + " operands!");
244 }
245
246 const CodeGenTarget &CGT = TP.getDAGPatterns().getTargetInfo();
247
248 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
249
250 switch (ConstraintType) {
251 default: assert(0 && "Unknown constraint type!");
252 case SDTCisVT:
253 // Operand must be a particular type.
254 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
255 case SDTCisPtrTy: {
256 // Operand must be same as target pointer type.
257 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
258 }
259 case SDTCisInt: {
260 // If there is only one integer type supported, this must be it.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000261 std::vector<MVT::SimpleValueType> IntVTs =
262 FilterVTs(CGT.getLegalValueTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000263
264 // If we found exactly one supported integer type, apply it.
265 if (IntVTs.size() == 1)
266 return NodeToApply->UpdateNodeType(IntVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000267 return NodeToApply->UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000268 }
269 case SDTCisFP: {
270 // If there is only one FP type supported, this must be it.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000271 std::vector<MVT::SimpleValueType> FPVTs =
272 FilterVTs(CGT.getLegalValueTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000273
274 // If we found exactly one supported FP type, apply it.
275 if (FPVTs.size() == 1)
276 return NodeToApply->UpdateNodeType(FPVTs[0], TP);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000277 return NodeToApply->UpdateNodeType(EMVT::isFP, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000278 }
279 case SDTCisSameAs: {
280 TreePatternNode *OtherNode =
281 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
282 return NodeToApply->UpdateNodeType(OtherNode->getExtTypes(), TP) |
283 OtherNode->UpdateNodeType(NodeToApply->getExtTypes(), TP);
284 }
285 case SDTCisVTSmallerThanOp: {
286 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
287 // have an integer type that is smaller than the VT.
288 if (!NodeToApply->isLeaf() ||
289 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
290 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
291 ->isSubClassOf("ValueType"))
292 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000293 MVT::SimpleValueType VT =
Chris Lattner6cefb772008-01-05 22:25:12 +0000294 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Duncan Sands83ec4b62008-06-06 12:08:01 +0000295 if (!isInteger(VT))
Chris Lattner6cefb772008-01-05 22:25:12 +0000296 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
297
298 TreePatternNode *OtherNode =
299 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
300
301 // It must be integer.
302 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000303 MadeChange |= OtherNode->UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000304
305 // This code only handles nodes that have one type set. Assert here so
306 // that we can change this if we ever need to deal with multiple value
307 // types at this point.
308 assert(OtherNode->getExtTypes().size() == 1 && "Node has too many types!");
309 if (OtherNode->hasTypeSet() && OtherNode->getTypeNum(0) <= VT)
310 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
311 return false;
312 }
313 case SDTCisOpSmallerThanOp: {
314 TreePatternNode *BigOperand =
315 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
316
317 // Both operands must be integer or FP, but we don't care which.
318 bool MadeChange = false;
319
320 // This code does not currently handle nodes which have multiple types,
321 // where some types are integer, and some are fp. Assert that this is not
322 // the case.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000323 assert(!(EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes()) &&
324 EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) &&
325 !(EMVT::isExtIntegerInVTs(BigOperand->getExtTypes()) &&
326 EMVT::isExtFloatingPointInVTs(BigOperand->getExtTypes())) &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000327 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000328 if (EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes()))
329 MadeChange |= BigOperand->UpdateNodeType(EMVT::isInt, TP);
330 else if (EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes()))
331 MadeChange |= BigOperand->UpdateNodeType(EMVT::isFP, TP);
332 if (EMVT::isExtIntegerInVTs(BigOperand->getExtTypes()))
333 MadeChange |= NodeToApply->UpdateNodeType(EMVT::isInt, TP);
334 else if (EMVT::isExtFloatingPointInVTs(BigOperand->getExtTypes()))
335 MadeChange |= NodeToApply->UpdateNodeType(EMVT::isFP, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000336
Duncan Sands83ec4b62008-06-06 12:08:01 +0000337 std::vector<MVT::SimpleValueType> VTs = CGT.getLegalValueTypes();
338
339 if (EMVT::isExtIntegerInVTs(NodeToApply->getExtTypes())) {
340 VTs = FilterVTs(VTs, isInteger);
341 } else if (EMVT::isExtFloatingPointInVTs(NodeToApply->getExtTypes())) {
342 VTs = FilterVTs(VTs, isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000343 } else {
344 VTs.clear();
345 }
346
347 switch (VTs.size()) {
348 default: // Too many VT's to pick from.
349 case 0: break; // No info yet.
350 case 1:
Jim Grosbachda4231f2009-03-26 16:17:51 +0000351 // Only one VT of this flavor. Cannot ever satisfy the constraints.
Chris Lattner6cefb772008-01-05 22:25:12 +0000352 return NodeToApply->UpdateNodeType(MVT::Other, TP); // throw
353 case 2:
354 // If we have exactly two possible types, the little operand must be the
355 // small one, the big operand should be the big one. Common with
356 // float/double for example.
357 assert(VTs[0] < VTs[1] && "Should be sorted!");
358 MadeChange |= NodeToApply->UpdateNodeType(VTs[0], TP);
359 MadeChange |= BigOperand->UpdateNodeType(VTs[1], TP);
360 break;
361 }
362 return MadeChange;
363 }
Nate Begemanb5af3342008-02-09 01:37:05 +0000364 case SDTCisEltOfVec: {
365 TreePatternNode *OtherOperand =
Nate Begeman9008ca62009-04-27 18:41:29 +0000366 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum,
Nate Begemanb5af3342008-02-09 01:37:05 +0000367 N, NumResults);
368 if (OtherOperand->hasTypeSet()) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000369 if (!isVector(OtherOperand->getTypeNum(0)))
Nate Begemanb5af3342008-02-09 01:37:05 +0000370 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000371 MVT IVT = OtherOperand->getTypeNum(0);
372 IVT = IVT.getVectorElementType();
373 return NodeToApply->UpdateNodeType(IVT.getSimpleVT(), TP);
Nate Begemanb5af3342008-02-09 01:37:05 +0000374 }
375 return false;
376 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000377 }
378 return false;
379}
380
381//===----------------------------------------------------------------------===//
382// SDNodeInfo implementation
383//
384SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
385 EnumName = R->getValueAsString("Opcode");
386 SDClassName = R->getValueAsString("SDClass");
387 Record *TypeProfile = R->getValueAsDef("TypeProfile");
388 NumResults = TypeProfile->getValueAsInt("NumResults");
389 NumOperands = TypeProfile->getValueAsInt("NumOperands");
390
391 // Parse the properties.
392 Properties = 0;
393 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
394 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
395 if (PropList[i]->getName() == "SDNPCommutative") {
396 Properties |= 1 << SDNPCommutative;
397 } else if (PropList[i]->getName() == "SDNPAssociative") {
398 Properties |= 1 << SDNPAssociative;
399 } else if (PropList[i]->getName() == "SDNPHasChain") {
400 Properties |= 1 << SDNPHasChain;
401 } else if (PropList[i]->getName() == "SDNPOutFlag") {
Dale Johannesen4150d832009-06-01 23:27:20 +0000402 Properties |= 1 << SDNPOutFlag;
403 assert(!(Properties & (1<<SDNPOutI1)) &&
404 "Can't handle OutFlag and OutI1");
Chris Lattner6cefb772008-01-05 22:25:12 +0000405 } else if (PropList[i]->getName() == "SDNPInFlag") {
406 Properties |= 1 << SDNPInFlag;
Dale Johannesen4150d832009-06-01 23:27:20 +0000407 assert(!(Properties & (1<<SDNPInI1)) &&
408 "Can't handle InFlag and InI1");
Chris Lattner6cefb772008-01-05 22:25:12 +0000409 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
410 Properties |= 1 << SDNPOptInFlag;
Chris Lattnerc8478d82008-01-06 06:44:58 +0000411 } else if (PropList[i]->getName() == "SDNPMayStore") {
412 Properties |= 1 << SDNPMayStore;
Chris Lattner710e9952008-01-10 04:38:57 +0000413 } else if (PropList[i]->getName() == "SDNPMayLoad") {
414 Properties |= 1 << SDNPMayLoad;
Chris Lattnerbc0b9f72008-01-10 05:39:30 +0000415 } else if (PropList[i]->getName() == "SDNPSideEffect") {
416 Properties |= 1 << SDNPSideEffect;
Mon P Wang28873102008-06-25 08:15:39 +0000417 } else if (PropList[i]->getName() == "SDNPMemOperand") {
418 Properties |= 1 << SDNPMemOperand;
Dale Johannesen4150d832009-06-01 23:27:20 +0000419 } else if (PropList[i]->getName() == "SDNPInI1") {
420 Properties |= 1 << SDNPInI1;
421 assert(!(Properties & (1<<SDNPInFlag)) &&
422 "Can't handle InFlag and InI1");
423 } else if (PropList[i]->getName() == "SDNPOutI1") {
424 Properties |= 1 << SDNPOutI1;
425 assert(!(Properties & (1<<SDNPOutFlag)) &&
426 "Can't handle OutFlag and OutI1");
Chris Lattner6cefb772008-01-05 22:25:12 +0000427 } else {
428 cerr << "Unknown SD Node property '" << PropList[i]->getName()
429 << "' on node '" << R->getName() << "'!\n";
430 exit(1);
431 }
432 }
433
434
435 // Parse the type constraints.
436 std::vector<Record*> ConstraintList =
437 TypeProfile->getValueAsListOfDefs("Constraints");
438 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
439}
440
441//===----------------------------------------------------------------------===//
442// TreePatternNode implementation
443//
444
445TreePatternNode::~TreePatternNode() {
446#if 0 // FIXME: implement refcounted tree nodes!
447 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
448 delete getChild(i);
449#endif
450}
451
452/// UpdateNodeType - Set the node type of N to VT if VT contains
453/// information. If N already contains a conflicting type, then throw an
454/// exception. This returns true if any information was updated.
455///
456bool TreePatternNode::UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
457 TreePattern &TP) {
458 assert(!ExtVTs.empty() && "Cannot update node type with empty type vector!");
459
Duncan Sands83ec4b62008-06-06 12:08:01 +0000460 if (ExtVTs[0] == EMVT::isUnknown || LHSIsSubsetOfRHS(getExtTypes(), ExtVTs))
Chris Lattner6cefb772008-01-05 22:25:12 +0000461 return false;
462 if (isTypeCompletelyUnknown() || LHSIsSubsetOfRHS(ExtVTs, getExtTypes())) {
463 setTypes(ExtVTs);
464 return true;
465 }
466
Mon P Wange3b3a722008-07-30 04:36:53 +0000467 if (getExtTypeNum(0) == MVT::iPTR || getExtTypeNum(0) == MVT::iPTRAny) {
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000468 if (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny ||
469 ExtVTs[0] == EMVT::isInt)
Chris Lattner6cefb772008-01-05 22:25:12 +0000470 return false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000471 if (EMVT::isExtIntegerInVTs(ExtVTs)) {
472 std::vector<unsigned char> FVTs = FilterEVTs(ExtVTs, isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000473 if (FVTs.size()) {
474 setTypes(ExtVTs);
475 return true;
476 }
477 }
478 }
Bob Wilsone035fa52009-01-05 17:52:54 +0000479
480 if ((ExtVTs[0] == EMVT::isInt || ExtVTs[0] == MVT::iAny) &&
481 EMVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000482 assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000483 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000484 if (getExtTypes() == FVTs)
485 return false;
486 setTypes(FVTs);
487 return true;
488 }
Mon P Wange3b3a722008-07-30 04:36:53 +0000489 if ((ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny) &&
490 EMVT::isExtIntegerInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000491 //assert(hasTypeSet() && "should be handled above!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000492 std::vector<unsigned char> FVTs = FilterEVTs(getExtTypes(), isInteger);
Chris Lattner6cefb772008-01-05 22:25:12 +0000493 if (getExtTypes() == FVTs)
494 return false;
495 if (FVTs.size()) {
496 setTypes(FVTs);
497 return true;
498 }
499 }
Bob Wilsone035fa52009-01-05 17:52:54 +0000500 if ((ExtVTs[0] == EMVT::isFP || ExtVTs[0] == MVT::fAny) &&
501 EMVT::isExtFloatingPointInVTs(getExtTypes())) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000502 assert(hasTypeSet() && "should be handled above!");
503 std::vector<unsigned char> FVTs =
Duncan Sands83ec4b62008-06-06 12:08:01 +0000504 FilterEVTs(getExtTypes(), isFloatingPoint);
Chris Lattner6cefb772008-01-05 22:25:12 +0000505 if (getExtTypes() == FVTs)
506 return false;
507 setTypes(FVTs);
508 return true;
509 }
510
511 // If we know this is an int or fp type, and we are told it is a specific one,
512 // take the advice.
513 //
514 // Similarly, we should probably set the type here to the intersection of
515 // {isInt|isFP} and ExtVTs
Bob Wilsone035fa52009-01-05 17:52:54 +0000516 if (((getExtTypeNum(0) == EMVT::isInt || getExtTypeNum(0) == MVT::iAny) &&
Duncan Sands83ec4b62008-06-06 12:08:01 +0000517 EMVT::isExtIntegerInVTs(ExtVTs)) ||
Bob Wilsone035fa52009-01-05 17:52:54 +0000518 ((getExtTypeNum(0) == EMVT::isFP || getExtTypeNum(0) == MVT::fAny) &&
Duncan Sands83ec4b62008-06-06 12:08:01 +0000519 EMVT::isExtFloatingPointInVTs(ExtVTs))) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000520 setTypes(ExtVTs);
521 return true;
522 }
Mon P Wange3b3a722008-07-30 04:36:53 +0000523 if (getExtTypeNum(0) == EMVT::isInt &&
524 (ExtVTs[0] == MVT::iPTR || ExtVTs[0] == MVT::iPTRAny)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000525 setTypes(ExtVTs);
526 return true;
527 }
528
529 if (isLeaf()) {
530 dump();
531 cerr << " ";
532 TP.error("Type inference contradiction found in node!");
533 } else {
534 TP.error("Type inference contradiction found in node " +
535 getOperator()->getName() + "!");
536 }
537 return true; // unreachable
538}
539
540
541void TreePatternNode::print(std::ostream &OS) const {
542 if (isLeaf()) {
543 OS << *getLeafValue();
544 } else {
545 OS << "(" << getOperator()->getName();
546 }
547
548 // FIXME: At some point we should handle printing all the value types for
549 // nodes that are multiply typed.
550 switch (getExtTypeNum(0)) {
551 case MVT::Other: OS << ":Other"; break;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000552 case EMVT::isInt: OS << ":isInt"; break;
553 case EMVT::isFP : OS << ":isFP"; break;
554 case EMVT::isUnknown: ; /*OS << ":?";*/ break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000555 case MVT::iPTR: OS << ":iPTR"; break;
Mon P Wange3b3a722008-07-30 04:36:53 +0000556 case MVT::iPTRAny: OS << ":iPTRAny"; break;
Chris Lattner6cefb772008-01-05 22:25:12 +0000557 default: {
558 std::string VTName = llvm::getName(getTypeNum(0));
559 // Strip off MVT:: prefix if present.
560 if (VTName.substr(0,5) == "MVT::")
561 VTName = VTName.substr(5);
562 OS << ":" << VTName;
563 break;
564 }
565 }
566
567 if (!isLeaf()) {
568 if (getNumChildren() != 0) {
569 OS << " ";
570 getChild(0)->print(OS);
571 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
572 OS << ", ";
573 getChild(i)->print(OS);
574 }
575 }
576 OS << ")";
577 }
578
Dan Gohman0540e172008-10-15 06:17:21 +0000579 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
580 OS << "<<P:" << PredicateFns[i] << ">>";
Chris Lattner6cefb772008-01-05 22:25:12 +0000581 if (TransformFn)
582 OS << "<<X:" << TransformFn->getName() << ">>";
583 if (!getName().empty())
584 OS << ":$" << getName();
585
586}
587void TreePatternNode::dump() const {
588 print(*cerr.stream());
589}
590
Scott Michel327d0652008-03-05 17:49:05 +0000591/// isIsomorphicTo - Return true if this node is recursively
592/// isomorphic to the specified node. For this comparison, the node's
593/// entire state is considered. The assigned name is ignored, since
594/// nodes with differing names are considered isomorphic. However, if
595/// the assigned name is present in the dependent variable set, then
596/// the assigned name is considered significant and the node is
597/// isomorphic if the names match.
598bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
599 const MultipleUseVarSet &DepVars) const {
Chris Lattner6cefb772008-01-05 22:25:12 +0000600 if (N == this) return true;
601 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman0540e172008-10-15 06:17:21 +0000602 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000603 getTransformFn() != N->getTransformFn())
604 return false;
605
606 if (isLeaf()) {
Scott Michel327d0652008-03-05 17:49:05 +0000607 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
608 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +0000609 return ((DI->getDef() == NDI->getDef())
610 && (DepVars.find(getName()) == DepVars.end()
611 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +0000612 }
613 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000614 return getLeafValue() == N->getLeafValue();
615 }
616
617 if (N->getOperator() != getOperator() ||
618 N->getNumChildren() != getNumChildren()) return false;
619 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +0000620 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +0000621 return false;
622 return true;
623}
624
625/// clone - Make a copy of this tree and all of its children.
626///
627TreePatternNode *TreePatternNode::clone() const {
628 TreePatternNode *New;
629 if (isLeaf()) {
630 New = new TreePatternNode(getLeafValue());
631 } else {
632 std::vector<TreePatternNode*> CChildren;
633 CChildren.reserve(Children.size());
634 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
635 CChildren.push_back(getChild(i)->clone());
636 New = new TreePatternNode(getOperator(), CChildren);
637 }
638 New->setName(getName());
639 New->setTypes(getExtTypes());
Dan Gohman0540e172008-10-15 06:17:21 +0000640 New->setPredicateFns(getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +0000641 New->setTransformFn(getTransformFn());
642 return New;
643}
644
645/// SubstituteFormalArguments - Replace the formal arguments in this tree
646/// with actual values specified by ArgMap.
647void TreePatternNode::
648SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
649 if (isLeaf()) return;
650
651 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
652 TreePatternNode *Child = getChild(i);
653 if (Child->isLeaf()) {
654 Init *Val = Child->getLeafValue();
655 if (dynamic_cast<DefInit*>(Val) &&
656 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
657 // We found a use of a formal argument, replace it with its value.
Dan Gohman0540e172008-10-15 06:17:21 +0000658 TreePatternNode *NewChild = ArgMap[Child->getName()];
659 assert(NewChild && "Couldn't find formal argument!");
660 assert((Child->getPredicateFns().empty() ||
661 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
662 "Non-empty child predicate clobbered!");
663 setChild(i, NewChild);
Chris Lattner6cefb772008-01-05 22:25:12 +0000664 }
665 } else {
666 getChild(i)->SubstituteFormalArguments(ArgMap);
667 }
668 }
669}
670
671
672/// InlinePatternFragments - If this pattern refers to any pattern
673/// fragments, inline them into place, giving us a pattern without any
674/// PatFrag references.
675TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
676 if (isLeaf()) return this; // nothing to do.
677 Record *Op = getOperator();
678
679 if (!Op->isSubClassOf("PatFrag")) {
680 // Just recursively inline children nodes.
Dan Gohman0540e172008-10-15 06:17:21 +0000681 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
682 TreePatternNode *Child = getChild(i);
683 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
684
685 assert((Child->getPredicateFns().empty() ||
686 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
687 "Non-empty child predicate clobbered!");
688
689 setChild(i, NewChild);
690 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000691 return this;
692 }
693
694 // Otherwise, we found a reference to a fragment. First, look up its
695 // TreePattern record.
696 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
697
698 // Verify that we are passing the right number of operands.
699 if (Frag->getNumArgs() != Children.size())
700 TP.error("'" + Op->getName() + "' fragment requires " +
701 utostr(Frag->getNumArgs()) + " operands!");
702
703 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
704
Dan Gohman0540e172008-10-15 06:17:21 +0000705 std::string Code = Op->getValueAsCode("Predicate");
706 if (!Code.empty())
707 FragTree->addPredicateFn("Predicate_"+Op->getName());
708
Chris Lattner6cefb772008-01-05 22:25:12 +0000709 // Resolve formal arguments to their actual value.
710 if (Frag->getNumArgs()) {
711 // Compute the map of formal to actual arguments.
712 std::map<std::string, TreePatternNode*> ArgMap;
713 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
714 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
715
716 FragTree->SubstituteFormalArguments(ArgMap);
717 }
718
719 FragTree->setName(getName());
720 FragTree->UpdateNodeType(getExtTypes(), TP);
Dan Gohman0540e172008-10-15 06:17:21 +0000721
722 // Transfer in the old predicates.
723 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
724 FragTree->addPredicateFn(getPredicateFns()[i]);
725
Chris Lattner6cefb772008-01-05 22:25:12 +0000726 // Get a new copy of this fragment to stitch into here.
727 //delete this; // FIXME: implement refcounting!
Chris Lattner2ca698d2008-06-30 03:02:03 +0000728
729 // The fragment we inlined could have recursive inlining that is needed. See
730 // if there are any pattern fragments in it and inline them as needed.
731 return FragTree->InlinePatternFragments(TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000732}
733
734/// getImplicitType - Check to see if the specified record has an implicit
735/// type which should be applied to it. This infer the type of register
736/// references from the register file information, for example.
737///
738static std::vector<unsigned char> getImplicitType(Record *R, bool NotRegisters,
739 TreePattern &TP) {
740 // Some common return values
Duncan Sands83ec4b62008-06-06 12:08:01 +0000741 std::vector<unsigned char> Unknown(1, EMVT::isUnknown);
Chris Lattner6cefb772008-01-05 22:25:12 +0000742 std::vector<unsigned char> Other(1, MVT::Other);
743
744 // Check to see if this is a register or a register class...
745 if (R->isSubClassOf("RegisterClass")) {
746 if (NotRegisters)
747 return Unknown;
748 const CodeGenRegisterClass &RC =
749 TP.getDAGPatterns().getTargetInfo().getRegisterClass(R);
750 return ConvertVTs(RC.getValueTypes());
751 } else if (R->isSubClassOf("PatFrag")) {
752 // Pattern fragment types will be resolved when they are inlined.
753 return Unknown;
754 } else if (R->isSubClassOf("Register")) {
755 if (NotRegisters)
756 return Unknown;
757 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
758 return T.getRegisterVTs(R);
759 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
760 // Using a VTSDNode or CondCodeSDNode.
761 return Other;
762 } else if (R->isSubClassOf("ComplexPattern")) {
763 if (NotRegisters)
764 return Unknown;
765 std::vector<unsigned char>
766 ComplexPat(1, TP.getDAGPatterns().getComplexPattern(R).getValueType());
767 return ComplexPat;
768 } else if (R->getName() == "ptr_rc") {
769 Other[0] = MVT::iPTR;
770 return Other;
771 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
772 R->getName() == "zero_reg") {
773 // Placeholder.
774 return Unknown;
775 }
776
777 TP.error("Unknown node flavor used in pattern: " + R->getName());
778 return Other;
779}
780
Chris Lattnere67bde52008-01-06 05:36:50 +0000781
782/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
783/// CodeGenIntrinsic information for it, otherwise return a null pointer.
784const CodeGenIntrinsic *TreePatternNode::
785getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
786 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
787 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
788 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
789 return 0;
790
791 unsigned IID =
792 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
793 return &CDP.getIntrinsicInfo(IID);
794}
795
Evan Cheng6bd95672008-06-16 20:29:38 +0000796/// isCommutativeIntrinsic - Return true if the node corresponds to a
797/// commutative intrinsic.
798bool
799TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
800 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
801 return Int->isCommutative;
802 return false;
803}
804
Chris Lattnere67bde52008-01-06 05:36:50 +0000805
Bob Wilson6c01ca92009-01-05 17:23:09 +0000806/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +0000807/// this node and its children in the tree. This returns true if it makes a
808/// change, false otherwise. If a type contradiction is found, throw an
809/// exception.
810bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Chris Lattnerfe718932008-01-06 01:10:31 +0000811 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +0000812 if (isLeaf()) {
813 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
814 // If it's a regclass or something else known, include the type.
815 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
816 } else if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
817 // Int inits are always integers. :)
Duncan Sands83ec4b62008-06-06 12:08:01 +0000818 bool MadeChange = UpdateNodeType(EMVT::isInt, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000819
820 if (hasTypeSet()) {
821 // At some point, it may make sense for this tree pattern to have
822 // multiple types. Assert here that it does not, so we revisit this
823 // code when appropriate.
824 assert(getExtTypes().size() >= 1 && "TreePattern doesn't have a type!");
Duncan Sands83ec4b62008-06-06 12:08:01 +0000825 MVT::SimpleValueType VT = getTypeNum(0);
Chris Lattner6cefb772008-01-05 22:25:12 +0000826 for (unsigned i = 1, e = getExtTypes().size(); i != e; ++i)
827 assert(getTypeNum(i) == VT && "TreePattern has too many types!");
828
829 VT = getTypeNum(0);
Mon P Wange3b3a722008-07-30 04:36:53 +0000830 if (VT != MVT::iPTR && VT != MVT::iPTRAny) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000831 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattner6cefb772008-01-05 22:25:12 +0000832 // Make sure that the value is representable for this type.
833 if (Size < 32) {
834 int Val = (II->getValue() << (32-Size)) >> (32-Size);
Scott Michel0123b7d2008-02-15 23:05:48 +0000835 if (Val != II->getValue()) {
Bill Wendling27926af2008-02-26 10:45:29 +0000836 // If sign-extended doesn't fit, does it fit as unsigned?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000837 unsigned ValueMask;
838 unsigned UnsignedVal;
Duncan Sandsb0d5cdd2009-02-01 18:06:53 +0000839 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
Duncan Sands83ec4b62008-06-06 12:08:01 +0000840 UnsignedVal = unsigned(II->getValue());
Scott Michel0123b7d2008-02-15 23:05:48 +0000841
Bill Wendling27926af2008-02-26 10:45:29 +0000842 if ((ValueMask & UnsignedVal) != UnsignedVal) {
843 TP.error("Integer value '" + itostr(II->getValue())+
844 "' is out of range for type '" +
845 getEnumName(getTypeNum(0)) + "'!");
846 }
847 }
848 }
849 }
Chris Lattner6cefb772008-01-05 22:25:12 +0000850 }
851
852 return MadeChange;
853 }
854 return false;
855 }
856
857 // special handling for set, which isn't really an SDNode.
858 if (getOperator()->getName() == "set") {
859 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
860 unsigned NC = getNumChildren();
861 bool MadeChange = false;
862 for (unsigned i = 0; i < NC-1; ++i) {
863 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
864 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
865
866 // Types of operands must match.
867 MadeChange |= getChild(i)->UpdateNodeType(getChild(NC-1)->getExtTypes(),
868 TP);
869 MadeChange |= getChild(NC-1)->UpdateNodeType(getChild(i)->getExtTypes(),
870 TP);
871 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
872 }
873 return MadeChange;
874 } else if (getOperator()->getName() == "implicit" ||
875 getOperator()->getName() == "parallel") {
876 bool MadeChange = false;
877 for (unsigned i = 0; i < getNumChildren(); ++i)
878 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
879 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
880 return MadeChange;
Dan Gohman88c7af02009-04-13 21:06:25 +0000881 } else if (getOperator()->getName() == "COPY_TO_REGCLASS") {
Dan Gohmanf8c73942009-04-13 15:38:05 +0000882 bool MadeChange = false;
883 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
884 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
885 MadeChange |= UpdateNodeType(getChild(1)->getTypeNum(0), TP);
886 return MadeChange;
Chris Lattnere67bde52008-01-06 05:36:50 +0000887 } else if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000888 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000889
Chris Lattner6cefb772008-01-05 22:25:12 +0000890 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000891 unsigned NumRetVTs = Int->IS.RetVTs.size();
892 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000893
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000894 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
895 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
896
897 if (getNumChildren() != NumParamVTs + NumRetVTs)
Chris Lattnere67bde52008-01-06 05:36:50 +0000898 TP.error("Intrinsic '" + Int->Name + "' expects " +
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000899 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
900 utostr(getNumChildren() - 1) + " operands!");
Chris Lattner6cefb772008-01-05 22:25:12 +0000901
902 // Apply type info to the intrinsic ID.
903 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
904
Bill Wendlingcdcc3e62008-11-13 09:08:33 +0000905 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
906 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
Chris Lattner6cefb772008-01-05 22:25:12 +0000907 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
908 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
909 }
910 return MadeChange;
911 } else if (getOperator()->isSubClassOf("SDNode")) {
912 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
913
914 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
915 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
916 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
917 // Branch, etc. do not produce results and top-level forms in instr pattern
918 // must have void types.
919 if (NI.getNumResults() == 0)
920 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
921
Chris Lattner6cefb772008-01-05 22:25:12 +0000922 return MadeChange;
923 } else if (getOperator()->isSubClassOf("Instruction")) {
924 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
925 bool MadeChange = false;
926 unsigned NumResults = Inst.getNumResults();
927
928 assert(NumResults <= 1 &&
929 "Only supports zero or one result instrs!");
930
931 CodeGenInstruction &InstInfo =
932 CDP.getTargetInfo().getInstruction(getOperator()->getName());
933 // Apply the result type to the node
934 if (NumResults == 0 || InstInfo.NumDefs == 0) {
Christopher Lamb02f69372008-03-10 04:16:09 +0000935 MadeChange = UpdateNodeType(MVT::isVoid, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000936 } else {
937 Record *ResultNode = Inst.getResult(0);
938
939 if (ResultNode->getName() == "ptr_rc") {
940 std::vector<unsigned char> VT;
941 VT.push_back(MVT::iPTR);
942 MadeChange = UpdateNodeType(VT, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +0000943 } else if (ResultNode->getName() == "unknown") {
944 std::vector<unsigned char> VT;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000945 VT.push_back(EMVT::isUnknown);
Christopher Lamb5b415372008-03-11 09:33:47 +0000946 MadeChange = UpdateNodeType(VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000947 } else {
948 assert(ResultNode->isSubClassOf("RegisterClass") &&
949 "Operands should be register classes!");
950
951 const CodeGenRegisterClass &RC =
952 CDP.getTargetInfo().getRegisterClass(ResultNode);
953 MadeChange = UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
954 }
955 }
956
957 unsigned ChildNo = 0;
958 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
959 Record *OperandNode = Inst.getOperand(i);
960
961 // If the instruction expects a predicate or optional def operand, we
962 // codegen this by setting the operand to it's default value if it has a
963 // non-empty DefaultOps field.
964 if ((OperandNode->isSubClassOf("PredicateOperand") ||
965 OperandNode->isSubClassOf("OptionalDefOperand")) &&
966 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
967 continue;
968
969 // Verify that we didn't run out of provided operands.
970 if (ChildNo >= getNumChildren())
971 TP.error("Instruction '" + getOperator()->getName() +
972 "' expects more operands than were provided.");
973
Duncan Sands83ec4b62008-06-06 12:08:01 +0000974 MVT::SimpleValueType VT;
Chris Lattner6cefb772008-01-05 22:25:12 +0000975 TreePatternNode *Child = getChild(ChildNo++);
976 if (OperandNode->isSubClassOf("RegisterClass")) {
977 const CodeGenRegisterClass &RC =
978 CDP.getTargetInfo().getRegisterClass(OperandNode);
979 MadeChange |= Child->UpdateNodeType(ConvertVTs(RC.getValueTypes()), TP);
980 } else if (OperandNode->isSubClassOf("Operand")) {
981 VT = getValueType(OperandNode->getValueAsDef("Type"));
982 MadeChange |= Child->UpdateNodeType(VT, TP);
983 } else if (OperandNode->getName() == "ptr_rc") {
984 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
Christopher Lamb5b415372008-03-11 09:33:47 +0000985 } else if (OperandNode->getName() == "unknown") {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000986 MadeChange |= Child->UpdateNodeType(EMVT::isUnknown, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +0000987 } else {
988 assert(0 && "Unknown operand type!");
989 abort();
990 }
991 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
992 }
Christopher Lamb5b415372008-03-11 09:33:47 +0000993
Christopher Lamb02f69372008-03-10 04:16:09 +0000994 if (ChildNo != getNumChildren())
Chris Lattner6cefb772008-01-05 22:25:12 +0000995 TP.error("Instruction '" + getOperator()->getName() +
996 "' was provided too many operands!");
997
998 return MadeChange;
999 } else {
1000 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1001
1002 // Node transforms always take one operand.
1003 if (getNumChildren() != 1)
1004 TP.error("Node transform '" + getOperator()->getName() +
1005 "' requires one operand!");
1006
1007 // If either the output or input of the xform does not have exact
1008 // type info. We assume they must be the same. Otherwise, it is perfectly
1009 // legal to transform from one type to a completely different type.
1010 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1011 bool MadeChange = UpdateNodeType(getChild(0)->getExtTypes(), TP);
1012 MadeChange |= getChild(0)->UpdateNodeType(getExtTypes(), TP);
1013 return MadeChange;
1014 }
1015 return false;
1016 }
1017}
1018
1019/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1020/// RHS of a commutative operation, not the on LHS.
1021static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1022 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1023 return true;
1024 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1025 return true;
1026 return false;
1027}
1028
1029
1030/// canPatternMatch - If it is impossible for this pattern to match on this
1031/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00001032/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00001033/// that can never possibly work), and to prevent the pattern permuter from
1034/// generating stuff that is useless.
1035bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00001036 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001037 if (isLeaf()) return true;
1038
1039 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1040 if (!getChild(i)->canPatternMatch(Reason, CDP))
1041 return false;
1042
1043 // If this is an intrinsic, handle cases that would make it not match. For
1044 // example, if an operand is required to be an immediate.
1045 if (getOperator()->isSubClassOf("Intrinsic")) {
1046 // TODO:
1047 return true;
1048 }
1049
1050 // If this node is a commutative operator, check that the LHS isn't an
1051 // immediate.
1052 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00001053 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1054 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001055 // Scan all of the operands of the node and make sure that only the last one
1056 // is a constant node, unless the RHS also is.
1057 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng6bd95672008-06-16 20:29:38 +00001058 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1059 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00001060 if (OnlyOnRHSOfCommutative(getChild(i))) {
1061 Reason="Immediate value must be on the RHS of commutative operators!";
1062 return false;
1063 }
1064 }
1065 }
1066
1067 return true;
1068}
1069
1070//===----------------------------------------------------------------------===//
1071// TreePattern implementation
1072//
1073
1074TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001075 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001076 isInputPattern = isInput;
1077 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1078 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1079}
1080
1081TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001082 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001083 isInputPattern = isInput;
1084 Trees.push_back(ParseTreePattern(Pat));
1085}
1086
1087TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Chris Lattnerfe718932008-01-06 01:10:31 +00001088 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
Chris Lattner6cefb772008-01-05 22:25:12 +00001089 isInputPattern = isInput;
1090 Trees.push_back(Pat);
1091}
1092
1093
1094
1095void TreePattern::error(const std::string &Msg) const {
1096 dump();
Chris Lattnera14b1de2009-03-13 16:25:21 +00001097 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
Chris Lattner6cefb772008-01-05 22:25:12 +00001098}
1099
1100TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1101 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1102 if (!OpDef) error("Pattern has unexpected operator type!");
1103 Record *Operator = OpDef->getDef();
1104
1105 if (Operator->isSubClassOf("ValueType")) {
1106 // If the operator is a ValueType, then this must be "type cast" of a leaf
1107 // node.
1108 if (Dag->getNumArgs() != 1)
1109 error("Type cast only takes one operand!");
1110
1111 Init *Arg = Dag->getArg(0);
1112 TreePatternNode *New;
1113 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1114 Record *R = DI->getDef();
1115 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001116 Dag->setArg(0, new DagInit(DI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001117 std::vector<std::pair<Init*, std::string> >()));
1118 return ParseTreePattern(Dag);
1119 }
1120 New = new TreePatternNode(DI);
1121 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1122 New = ParseTreePattern(DI);
1123 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1124 New = new TreePatternNode(II);
1125 if (!Dag->getArgName(0).empty())
1126 error("Constant int argument should not have a name!");
1127 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1128 // Turn this into an IntInit.
1129 Init *II = BI->convertInitializerTo(new IntRecTy());
1130 if (II == 0 || !dynamic_cast<IntInit*>(II))
1131 error("Bits value must be constants!");
1132
1133 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1134 if (!Dag->getArgName(0).empty())
1135 error("Constant int argument should not have a name!");
1136 } else {
1137 Arg->dump();
1138 error("Unknown leaf value for tree pattern!");
1139 return 0;
1140 }
1141
1142 // Apply the type cast.
1143 New->UpdateNodeType(getValueType(Operator), *this);
Nate Begeman7cee8172009-03-19 05:21:56 +00001144 if (New->getNumChildren() == 0)
1145 New->setName(Dag->getArgName(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00001146 return New;
1147 }
1148
1149 // Verify that this is something that makes sense for an operator.
Nate Begeman7cee8172009-03-19 05:21:56 +00001150 if (!Operator->isSubClassOf("PatFrag") &&
1151 !Operator->isSubClassOf("SDNode") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00001152 !Operator->isSubClassOf("Instruction") &&
1153 !Operator->isSubClassOf("SDNodeXForm") &&
1154 !Operator->isSubClassOf("Intrinsic") &&
1155 Operator->getName() != "set" &&
1156 Operator->getName() != "implicit" &&
1157 Operator->getName() != "parallel")
1158 error("Unrecognized node '" + Operator->getName() + "'!");
1159
1160 // Check to see if this is something that is illegal in an input pattern.
1161 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1162 Operator->isSubClassOf("SDNodeXForm")))
1163 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1164
1165 std::vector<TreePatternNode*> Children;
1166
1167 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1168 Init *Arg = Dag->getArg(i);
1169 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1170 Children.push_back(ParseTreePattern(DI));
1171 if (Children.back()->getName().empty())
1172 Children.back()->setName(Dag->getArgName(i));
1173 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1174 Record *R = DefI->getDef();
1175 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1176 // TreePatternNode if its own.
1177 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
Nate Begeman7cee8172009-03-19 05:21:56 +00001178 Dag->setArg(i, new DagInit(DefI, "",
Chris Lattner6cefb772008-01-05 22:25:12 +00001179 std::vector<std::pair<Init*, std::string> >()));
1180 --i; // Revisit this node...
1181 } else {
1182 TreePatternNode *Node = new TreePatternNode(DefI);
1183 Node->setName(Dag->getArgName(i));
1184 Children.push_back(Node);
1185
1186 // Input argument?
1187 if (R->getName() == "node") {
1188 if (Dag->getArgName(i).empty())
1189 error("'node' argument requires a name to match with operand list");
1190 Args.push_back(Dag->getArgName(i));
1191 }
1192 }
1193 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1194 TreePatternNode *Node = new TreePatternNode(II);
1195 if (!Dag->getArgName(i).empty())
1196 error("Constant int argument should not have a name!");
1197 Children.push_back(Node);
1198 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1199 // Turn this into an IntInit.
1200 Init *II = BI->convertInitializerTo(new IntRecTy());
1201 if (II == 0 || !dynamic_cast<IntInit*>(II))
1202 error("Bits value must be constants!");
1203
1204 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1205 if (!Dag->getArgName(i).empty())
1206 error("Constant int argument should not have a name!");
1207 Children.push_back(Node);
1208 } else {
1209 cerr << '"';
1210 Arg->dump();
1211 cerr << "\": ";
1212 error("Unknown leaf value for tree pattern!");
1213 }
1214 }
1215
1216 // If the operator is an intrinsic, then this is just syntactic sugar for for
1217 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1218 // convert the intrinsic name to a number.
1219 if (Operator->isSubClassOf("Intrinsic")) {
1220 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1221 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1222
1223 // If this intrinsic returns void, it must have side-effects and thus a
1224 // chain.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00001225 if (Int.IS.RetVTs[0] == MVT::isVoid) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001226 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1227 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1228 // Has side-effects, requires chain.
1229 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1230 } else {
1231 // Otherwise, no chain.
1232 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1233 }
1234
1235 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1236 Children.insert(Children.begin(), IIDNode);
1237 }
1238
Nate Begeman7cee8172009-03-19 05:21:56 +00001239 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1240 Result->setName(Dag->getName());
1241 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00001242}
1243
1244/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00001245/// patterns as possible. Return true if all types are inferred, false
Chris Lattner6cefb772008-01-05 22:25:12 +00001246/// otherwise. Throw an exception if a type contradiction is found.
1247bool TreePattern::InferAllTypes() {
1248 bool MadeChange = true;
1249 while (MadeChange) {
1250 MadeChange = false;
1251 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1252 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1253 }
1254
1255 bool HasUnresolvedTypes = false;
1256 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1257 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1258 return !HasUnresolvedTypes;
1259}
1260
1261void TreePattern::print(std::ostream &OS) const {
1262 OS << getRecord()->getName();
1263 if (!Args.empty()) {
1264 OS << "(" << Args[0];
1265 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1266 OS << ", " << Args[i];
1267 OS << ")";
1268 }
1269 OS << ": ";
1270
1271 if (Trees.size() > 1)
1272 OS << "[\n";
1273 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1274 OS << "\t";
1275 Trees[i]->print(OS);
1276 OS << "\n";
1277 }
1278
1279 if (Trees.size() > 1)
1280 OS << "]\n";
1281}
1282
1283void TreePattern::dump() const { print(*cerr.stream()); }
1284
1285//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00001286// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00001287//
1288
1289// FIXME: REMOVE OSTREAM ARGUMENT
Chris Lattnerfe718932008-01-06 01:10:31 +00001290CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
Dale Johannesen49de9822009-02-05 01:49:45 +00001291 Intrinsics = LoadIntrinsics(Records, false);
1292 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00001293 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00001294 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00001295 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001296 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00001297 ParseDefaultOperands();
1298 ParseInstructions();
1299 ParsePatterns();
1300
1301 // Generate variants. For example, commutative patterns can match
1302 // multiple ways. Add them to PatternsToMatch as well.
1303 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00001304
1305 // Infer instruction flags. For example, we can detect loads,
1306 // stores, and side effects in many cases by examining an
1307 // instruction's pattern.
1308 InferInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00001309}
1310
Chris Lattnerfe718932008-01-06 01:10:31 +00001311CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001312 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1313 E = PatternFragments.end(); I != E; ++I)
1314 delete I->second;
1315}
1316
1317
Chris Lattnerfe718932008-01-06 01:10:31 +00001318Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00001319 Record *N = Records.getDef(Name);
1320 if (!N || !N->isSubClassOf("SDNode")) {
1321 cerr << "Error getting SDNode '" << Name << "'!\n";
1322 exit(1);
1323 }
1324 return N;
1325}
1326
1327// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00001328void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001329 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1330 while (!Nodes.empty()) {
1331 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1332 Nodes.pop_back();
1333 }
1334
Jim Grosbachda4231f2009-03-26 16:17:51 +00001335 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00001336 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1337 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1338 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1339}
1340
1341/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1342/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001343void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001344 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1345 while (!Xforms.empty()) {
1346 Record *XFormNode = Xforms.back();
1347 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1348 std::string Code = XFormNode->getValueAsCode("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00001349 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00001350
1351 Xforms.pop_back();
1352 }
1353}
1354
Chris Lattnerfe718932008-01-06 01:10:31 +00001355void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001356 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1357 while (!AMs.empty()) {
1358 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1359 AMs.pop_back();
1360 }
1361}
1362
1363
1364/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1365/// file, building up the PatternFragments map. After we've collected them all,
1366/// inline fragments together as necessary, so that there are no references left
1367/// inside a pattern fragment to a pattern fragment.
1368///
Chris Lattnerfe718932008-01-06 01:10:31 +00001369void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001370 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1371
Chris Lattnerdc32f982008-01-05 22:43:57 +00001372 // First step, parse all of the fragments.
Chris Lattner6cefb772008-01-05 22:25:12 +00001373 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1374 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1375 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1376 PatternFragments[Fragments[i]] = P;
1377
Chris Lattnerdc32f982008-01-05 22:43:57 +00001378 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00001379 std::vector<std::string> &Args = P->getArgList();
Chris Lattnerdc32f982008-01-05 22:43:57 +00001380 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Chris Lattner6cefb772008-01-05 22:25:12 +00001381
Chris Lattnerdc32f982008-01-05 22:43:57 +00001382 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00001383 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1384
1385 // Parse the operands list.
1386 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1387 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1388 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00001389 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00001390 if (!OpsOp ||
1391 (OpsOp->getDef()->getName() != "ops" &&
1392 OpsOp->getDef()->getName() != "outs" &&
1393 OpsOp->getDef()->getName() != "ins"))
1394 P->error("Operands list should start with '(ops ... '!");
1395
1396 // Copy over the arguments.
1397 Args.clear();
1398 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1399 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1400 static_cast<DefInit*>(OpsList->getArg(j))->
1401 getDef()->getName() != "node")
1402 P->error("Operands list should all be 'node' values.");
1403 if (OpsList->getArgName(j).empty())
1404 P->error("Operands list should have names for each operand!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001405 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner6cefb772008-01-05 22:25:12 +00001406 P->error("'" + OpsList->getArgName(j) +
1407 "' does not occur in pattern or was multiply specified!");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001408 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner6cefb772008-01-05 22:25:12 +00001409 Args.push_back(OpsList->getArgName(j));
1410 }
1411
Chris Lattnerdc32f982008-01-05 22:43:57 +00001412 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00001413 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00001414 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001415
Chris Lattnerdc32f982008-01-05 22:43:57 +00001416 // If there is a code init for this fragment, keep track of the fact that
1417 // this fragment uses it.
Chris Lattner6cefb772008-01-05 22:25:12 +00001418 std::string Code = Fragments[i]->getValueAsCode("Predicate");
Chris Lattnerdc32f982008-01-05 22:43:57 +00001419 if (!Code.empty())
Dan Gohman0540e172008-10-15 06:17:21 +00001420 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +00001421
1422 // If there is a node transformation corresponding to this, keep track of
1423 // it.
1424 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1425 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1426 P->getOnlyTree()->setTransformFn(Transform);
1427 }
1428
Chris Lattner6cefb772008-01-05 22:25:12 +00001429 // Now that we've parsed all of the tree fragments, do a closure on them so
1430 // that there are not references to PatFrags left inside of them.
Chris Lattner2ca698d2008-06-30 03:02:03 +00001431 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1432 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner6cefb772008-01-05 22:25:12 +00001433 ThePat->InlinePatternFragments();
1434
1435 // Infer as many types as possible. Don't worry about it if we don't infer
1436 // all of them, some may depend on the inputs of the pattern.
1437 try {
1438 ThePat->InferAllTypes();
1439 } catch (...) {
1440 // If this pattern fragment is not supported by this target (no types can
1441 // satisfy its constraints), just ignore it. If the bogus pattern is
1442 // actually used by instructions, the type consistency error will be
1443 // reported there.
1444 }
1445
1446 // If debugging, print out the pattern fragment result.
1447 DEBUG(ThePat->dump());
1448 }
1449}
1450
Chris Lattnerfe718932008-01-06 01:10:31 +00001451void CodeGenDAGPatterns::ParseDefaultOperands() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001452 std::vector<Record*> DefaultOps[2];
1453 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1454 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1455
1456 // Find some SDNode.
1457 assert(!SDNodes.empty() && "No SDNodes parsed?");
1458 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1459
1460 for (unsigned iter = 0; iter != 2; ++iter) {
1461 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1462 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1463
1464 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1465 // SomeSDnode so that we can parse this.
1466 std::vector<std::pair<Init*, std::string> > Ops;
1467 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1468 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1469 DefaultInfo->getArgName(op)));
Nate Begeman7cee8172009-03-19 05:21:56 +00001470 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
Chris Lattner6cefb772008-01-05 22:25:12 +00001471
1472 // Create a TreePattern to parse this.
1473 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1474 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1475
1476 // Copy the operands over into a DAGDefaultOperand.
1477 DAGDefaultOperand DefaultOpInfo;
1478
1479 TreePatternNode *T = P.getTree(0);
1480 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1481 TreePatternNode *TPN = T->getChild(op);
1482 while (TPN->ApplyTypeConstraints(P, false))
1483 /* Resolve all types */;
1484
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001485 if (TPN->ContainsUnresolvedType()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001486 if (iter == 0)
1487 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1488 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
1489 else
1490 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1491 DefaultOps[iter][i]->getName() + "' doesn't have a concrete type!";
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00001492 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001493 DefaultOpInfo.DefaultOps.push_back(TPN);
1494 }
1495
1496 // Insert it into the DefaultOperands map so we can find it later.
1497 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1498 }
1499 }
1500}
1501
1502/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1503/// instruction input. Return true if this is a real use.
1504static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1505 std::map<std::string, TreePatternNode*> &InstInputs,
1506 std::vector<Record*> &InstImpInputs) {
1507 // No name -> not interesting.
1508 if (Pat->getName().empty()) {
1509 if (Pat->isLeaf()) {
1510 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1511 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1512 I->error("Input " + DI->getDef()->getName() + " must be named!");
1513 else if (DI && DI->getDef()->isSubClassOf("Register"))
1514 InstImpInputs.push_back(DI->getDef());
Chris Lattner6cefb772008-01-05 22:25:12 +00001515 }
1516 return false;
1517 }
1518
1519 Record *Rec;
1520 if (Pat->isLeaf()) {
1521 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1522 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1523 Rec = DI->getDef();
1524 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00001525 Rec = Pat->getOperator();
1526 }
1527
1528 // SRCVALUE nodes are ignored.
1529 if (Rec->getName() == "srcvalue")
1530 return false;
1531
1532 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1533 if (!Slot) {
1534 Slot = Pat;
1535 } else {
1536 Record *SlotRec;
1537 if (Slot->isLeaf()) {
1538 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1539 } else {
1540 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1541 SlotRec = Slot->getOperator();
1542 }
1543
1544 // Ensure that the inputs agree if we've already seen this input.
1545 if (Rec != SlotRec)
1546 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1547 if (Slot->getExtTypes() != Pat->getExtTypes())
1548 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1549 }
1550 return true;
1551}
1552
1553/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1554/// part of "I", the instruction), computing the set of inputs and outputs of
1555/// the pattern. Report errors if we see anything naughty.
Chris Lattnerfe718932008-01-06 01:10:31 +00001556void CodeGenDAGPatterns::
Chris Lattner6cefb772008-01-05 22:25:12 +00001557FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1558 std::map<std::string, TreePatternNode*> &InstInputs,
1559 std::map<std::string, TreePatternNode*>&InstResults,
1560 std::vector<Record*> &InstImpInputs,
1561 std::vector<Record*> &InstImpResults) {
1562 if (Pat->isLeaf()) {
1563 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1564 if (!isUse && Pat->getTransformFn())
1565 I->error("Cannot specify a transform function for a non-input value!");
1566 return;
1567 } else if (Pat->getOperator()->getName() == "implicit") {
1568 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1569 TreePatternNode *Dest = Pat->getChild(i);
1570 if (!Dest->isLeaf())
1571 I->error("implicitly defined value should be a register!");
1572
1573 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1574 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1575 I->error("implicitly defined value should be a register!");
1576 InstImpResults.push_back(Val->getDef());
1577 }
1578 return;
1579 } else if (Pat->getOperator()->getName() != "set") {
1580 // If this is not a set, verify that the children nodes are not void typed,
1581 // and recurse.
1582 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1583 if (Pat->getChild(i)->getExtTypeNum(0) == MVT::isVoid)
1584 I->error("Cannot have void nodes inside of patterns!");
1585 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1586 InstImpInputs, InstImpResults);
1587 }
1588
1589 // If this is a non-leaf node with no children, treat it basically as if
1590 // it were a leaf. This handles nodes like (imm).
Nate Begeman7cee8172009-03-19 05:21:56 +00001591 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00001592
1593 if (!isUse && Pat->getTransformFn())
1594 I->error("Cannot specify a transform function for a non-input value!");
1595 return;
1596 }
1597
1598 // Otherwise, this is a set, validate and collect instruction results.
1599 if (Pat->getNumChildren() == 0)
1600 I->error("set requires operands!");
1601
1602 if (Pat->getTransformFn())
1603 I->error("Cannot specify a transform function on a set node!");
1604
1605 // Check the set destinations.
1606 unsigned NumDests = Pat->getNumChildren()-1;
1607 for (unsigned i = 0; i != NumDests; ++i) {
1608 TreePatternNode *Dest = Pat->getChild(i);
1609 if (!Dest->isLeaf())
1610 I->error("set destination should be a register!");
1611
1612 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1613 if (!Val)
1614 I->error("set destination should be a register!");
1615
1616 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1617 Val->getDef()->getName() == "ptr_rc") {
1618 if (Dest->getName().empty())
1619 I->error("set destination must have a name!");
1620 if (InstResults.count(Dest->getName()))
1621 I->error("cannot set '" + Dest->getName() +"' multiple times");
1622 InstResults[Dest->getName()] = Dest;
1623 } else if (Val->getDef()->isSubClassOf("Register")) {
1624 InstImpResults.push_back(Val->getDef());
1625 } else {
1626 I->error("set destination should be a register!");
1627 }
1628 }
1629
1630 // Verify and collect info from the computation.
1631 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1632 InstInputs, InstResults,
1633 InstImpInputs, InstImpResults);
1634}
1635
Dan Gohmanee4fa192008-04-03 00:02:49 +00001636//===----------------------------------------------------------------------===//
1637// Instruction Analysis
1638//===----------------------------------------------------------------------===//
1639
1640class InstAnalyzer {
1641 const CodeGenDAGPatterns &CDP;
1642 bool &mayStore;
1643 bool &mayLoad;
1644 bool &HasSideEffects;
1645public:
1646 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1647 bool &maystore, bool &mayload, bool &hse)
1648 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse){
1649 }
1650
1651 /// Analyze - Analyze the specified instruction, returning true if the
1652 /// instruction had a pattern.
1653 bool Analyze(Record *InstRecord) {
1654 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1655 if (Pattern == 0) {
1656 HasSideEffects = 1;
1657 return false; // No pattern.
1658 }
1659
1660 // FIXME: Assume only the first tree is the pattern. The others are clobber
1661 // nodes.
1662 AnalyzeNode(Pattern->getTree(0));
1663 return true;
1664 }
1665
1666private:
1667 void AnalyzeNode(const TreePatternNode *N) {
1668 if (N->isLeaf()) {
1669 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1670 Record *LeafRec = DI->getDef();
1671 // Handle ComplexPattern leaves.
1672 if (LeafRec->isSubClassOf("ComplexPattern")) {
1673 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
1674 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
1675 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
1676 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1677 }
1678 }
1679 return;
1680 }
1681
1682 // Analyze children.
1683 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1684 AnalyzeNode(N->getChild(i));
1685
1686 // Ignore set nodes, which are not SDNodes.
1687 if (N->getOperator()->getName() == "set")
1688 return;
1689
1690 // Get information about the SDNode for the operator.
1691 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
1692
1693 // Notice properties of the node.
1694 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
1695 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
1696 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
1697
1698 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
1699 // If this is an intrinsic, analyze it.
1700 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
1701 mayLoad = true;// These may load memory.
1702
1703 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
1704 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
1705
1706 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
1707 // WriteMem intrinsics can have other strange effects.
1708 HasSideEffects = true;
1709 }
1710 }
1711
1712};
1713
1714static void InferFromPattern(const CodeGenInstruction &Inst,
1715 bool &MayStore, bool &MayLoad,
1716 bool &HasSideEffects,
1717 const CodeGenDAGPatterns &CDP) {
1718 MayStore = MayLoad = HasSideEffects = false;
1719
1720 bool HadPattern =
1721 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects).Analyze(Inst.TheDef);
1722
1723 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
1724 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
1725 // If we decided that this is a store from the pattern, then the .td file
1726 // entry is redundant.
1727 if (MayStore)
1728 fprintf(stderr,
1729 "Warning: mayStore flag explicitly set on instruction '%s'"
1730 " but flag already inferred from pattern.\n",
1731 Inst.TheDef->getName().c_str());
1732 MayStore = true;
1733 }
1734
1735 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
1736 // If we decided that this is a load from the pattern, then the .td file
1737 // entry is redundant.
1738 if (MayLoad)
1739 fprintf(stderr,
1740 "Warning: mayLoad flag explicitly set on instruction '%s'"
1741 " but flag already inferred from pattern.\n",
1742 Inst.TheDef->getName().c_str());
1743 MayLoad = true;
1744 }
1745
1746 if (Inst.neverHasSideEffects) {
1747 if (HadPattern)
1748 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
1749 "which already has a pattern\n", Inst.TheDef->getName().c_str());
1750 HasSideEffects = false;
1751 }
1752
1753 if (Inst.hasSideEffects) {
1754 if (HasSideEffects)
1755 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
1756 "which already inferred this.\n", Inst.TheDef->getName().c_str());
1757 HasSideEffects = true;
1758 }
1759}
1760
Chris Lattner6cefb772008-01-05 22:25:12 +00001761/// ParseInstructions - Parse all of the instructions, inlining and resolving
1762/// any fragments involved. This populates the Instructions list with fully
1763/// resolved instructions.
Chris Lattnerfe718932008-01-06 01:10:31 +00001764void CodeGenDAGPatterns::ParseInstructions() {
Chris Lattner6cefb772008-01-05 22:25:12 +00001765 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
1766
1767 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
1768 ListInit *LI = 0;
1769
1770 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
1771 LI = Instrs[i]->getValueAsListInit("Pattern");
1772
1773 // If there is no pattern, only collect minimal information about the
1774 // instruction for its operand list. We have to assume that there is one
1775 // result, as we have no detailed info.
1776 if (!LI || LI->getSize() == 0) {
1777 std::vector<Record*> Results;
1778 std::vector<Record*> Operands;
1779
1780 CodeGenInstruction &InstInfo =Target.getInstruction(Instrs[i]->getName());
1781
1782 if (InstInfo.OperandList.size() != 0) {
1783 if (InstInfo.NumDefs == 0) {
1784 // These produce no results
1785 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
1786 Operands.push_back(InstInfo.OperandList[j].Rec);
1787 } else {
1788 // Assume the first operand is the result.
1789 Results.push_back(InstInfo.OperandList[0].Rec);
1790
1791 // The rest are inputs.
1792 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
1793 Operands.push_back(InstInfo.OperandList[j].Rec);
1794 }
1795 }
1796
1797 // Create and insert the instruction.
1798 std::vector<Record*> ImpResults;
1799 std::vector<Record*> ImpOperands;
1800 Instructions.insert(std::make_pair(Instrs[i],
1801 DAGInstruction(0, Results, Operands, ImpResults,
1802 ImpOperands)));
1803 continue; // no pattern.
1804 }
1805
1806 // Parse the instruction.
1807 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
1808 // Inline pattern fragments into it.
1809 I->InlinePatternFragments();
1810
1811 // Infer as many types as possible. If we cannot infer all of them, we can
1812 // never do anything with this instruction pattern: report it to the user.
1813 if (!I->InferAllTypes())
1814 I->error("Could not infer all types in pattern!");
1815
1816 // InstInputs - Keep track of all of the inputs of the instruction, along
1817 // with the record they are declared as.
1818 std::map<std::string, TreePatternNode*> InstInputs;
1819
1820 // InstResults - Keep track of all the virtual registers that are 'set'
1821 // in the instruction, including what reg class they are.
1822 std::map<std::string, TreePatternNode*> InstResults;
1823
1824 std::vector<Record*> InstImpInputs;
1825 std::vector<Record*> InstImpResults;
1826
1827 // Verify that the top-level forms in the instruction are of void type, and
1828 // fill in the InstResults map.
1829 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
1830 TreePatternNode *Pat = I->getTree(j);
1831 if (Pat->getExtTypeNum(0) != MVT::isVoid)
1832 I->error("Top-level forms in instruction pattern should have"
1833 " void types");
1834
1835 // Find inputs and outputs, and verify the structure of the uses/defs.
1836 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
1837 InstImpInputs, InstImpResults);
1838 }
1839
1840 // Now that we have inputs and outputs of the pattern, inspect the operands
1841 // list for the instruction. This determines the order that operands are
1842 // added to the machine instruction the node corresponds to.
1843 unsigned NumResults = InstResults.size();
1844
1845 // Parse the operands list from the (ops) list, validating it.
1846 assert(I->getArgList().empty() && "Args list should still be empty here!");
1847 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
1848
1849 // Check that all of the results occur first in the list.
1850 std::vector<Record*> Results;
1851 TreePatternNode *Res0Node = NULL;
1852 for (unsigned i = 0; i != NumResults; ++i) {
1853 if (i == CGI.OperandList.size())
1854 I->error("'" + InstResults.begin()->first +
1855 "' set but does not appear in operand list!");
1856 const std::string &OpName = CGI.OperandList[i].Name;
1857
1858 // Check that it exists in InstResults.
1859 TreePatternNode *RNode = InstResults[OpName];
1860 if (RNode == 0)
1861 I->error("Operand $" + OpName + " does not exist in operand list!");
1862
1863 if (i == 0)
1864 Res0Node = RNode;
1865 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
1866 if (R == 0)
1867 I->error("Operand $" + OpName + " should be a set destination: all "
1868 "outputs must occur before inputs in operand list!");
1869
1870 if (CGI.OperandList[i].Rec != R)
1871 I->error("Operand $" + OpName + " class mismatch!");
1872
1873 // Remember the return type.
1874 Results.push_back(CGI.OperandList[i].Rec);
1875
1876 // Okay, this one checks out.
1877 InstResults.erase(OpName);
1878 }
1879
1880 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
1881 // the copy while we're checking the inputs.
1882 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
1883
1884 std::vector<TreePatternNode*> ResultNodeOperands;
1885 std::vector<Record*> Operands;
1886 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
1887 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
1888 const std::string &OpName = Op.Name;
1889 if (OpName.empty())
1890 I->error("Operand #" + utostr(i) + " in operands list has no name!");
1891
1892 if (!InstInputsCheck.count(OpName)) {
1893 // If this is an predicate operand or optional def operand with an
1894 // DefaultOps set filled in, we can ignore this. When we codegen it,
1895 // we will do so as always executed.
1896 if (Op.Rec->isSubClassOf("PredicateOperand") ||
1897 Op.Rec->isSubClassOf("OptionalDefOperand")) {
1898 // Does it have a non-empty DefaultOps field? If so, ignore this
1899 // operand.
1900 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
1901 continue;
1902 }
1903 I->error("Operand $" + OpName +
1904 " does not appear in the instruction pattern");
1905 }
1906 TreePatternNode *InVal = InstInputsCheck[OpName];
1907 InstInputsCheck.erase(OpName); // It occurred, remove from map.
1908
1909 if (InVal->isLeaf() &&
1910 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
1911 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
1912 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
1913 I->error("Operand $" + OpName + "'s register class disagrees"
1914 " between the operand and pattern");
1915 }
1916 Operands.push_back(Op.Rec);
1917
1918 // Construct the result for the dest-pattern operand list.
1919 TreePatternNode *OpNode = InVal->clone();
1920
1921 // No predicate is useful on the result.
Dan Gohman0540e172008-10-15 06:17:21 +00001922 OpNode->clearPredicateFns();
Chris Lattner6cefb772008-01-05 22:25:12 +00001923
1924 // Promote the xform function to be an explicit node if set.
1925 if (Record *Xform = OpNode->getTransformFn()) {
1926 OpNode->setTransformFn(0);
1927 std::vector<TreePatternNode*> Children;
1928 Children.push_back(OpNode);
1929 OpNode = new TreePatternNode(Xform, Children);
1930 }
1931
1932 ResultNodeOperands.push_back(OpNode);
1933 }
1934
1935 if (!InstInputsCheck.empty())
1936 I->error("Input operand $" + InstInputsCheck.begin()->first +
1937 " occurs in pattern but not in operands list!");
1938
1939 TreePatternNode *ResultPattern =
1940 new TreePatternNode(I->getRecord(), ResultNodeOperands);
1941 // Copy fully inferred output node type to instruction result pattern.
1942 if (NumResults > 0)
1943 ResultPattern->setTypes(Res0Node->getExtTypes());
1944
1945 // Create and insert the instruction.
1946 // FIXME: InstImpResults and InstImpInputs should not be part of
1947 // DAGInstruction.
1948 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
1949 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
1950
1951 // Use a temporary tree pattern to infer all types and make sure that the
1952 // constructed result is correct. This depends on the instruction already
1953 // being inserted into the Instructions map.
1954 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
1955 Temp.InferAllTypes();
1956
1957 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
1958 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
1959
1960 DEBUG(I->dump());
1961 }
1962
1963 // If we can, convert the instructions to be patterns that are matched!
1964 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
1965 E = Instructions.end(); II != E; ++II) {
1966 DAGInstruction &TheInst = II->second;
Chris Lattnerf1ab4f12008-01-06 01:52:22 +00001967 const TreePattern *I = TheInst.getPattern();
Chris Lattner6cefb772008-01-05 22:25:12 +00001968 if (I == 0) continue; // No pattern.
1969
1970 // FIXME: Assume only the first tree is the pattern. The others are clobber
1971 // nodes.
1972 TreePatternNode *Pattern = I->getTree(0);
1973 TreePatternNode *SrcPattern;
1974 if (Pattern->getOperator()->getName() == "set") {
1975 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
1976 } else{
1977 // Not a set (store or something?)
1978 SrcPattern = Pattern;
1979 }
1980
1981 std::string Reason;
1982 if (!SrcPattern->canPatternMatch(Reason, *this))
1983 I->error("Instruction can never match: " + Reason);
1984
1985 Record *Instr = II->first;
1986 TreePatternNode *DstPattern = TheInst.getResultPattern();
1987 PatternsToMatch.
1988 push_back(PatternToMatch(Instr->getValueAsListInit("Predicates"),
1989 SrcPattern, DstPattern, TheInst.getImpResults(),
1990 Instr->getValueAsInt("AddedComplexity")));
1991 }
1992}
1993
Dan Gohmanee4fa192008-04-03 00:02:49 +00001994
1995void CodeGenDAGPatterns::InferInstructionFlags() {
1996 std::map<std::string, CodeGenInstruction> &InstrDescs =
1997 Target.getInstructions();
1998 for (std::map<std::string, CodeGenInstruction>::iterator
1999 II = InstrDescs.begin(), E = InstrDescs.end(); II != E; ++II) {
2000 CodeGenInstruction &InstInfo = II->second;
2001 // Determine properties of the instruction from its pattern.
2002 bool MayStore, MayLoad, HasSideEffects;
2003 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, *this);
2004 InstInfo.mayStore = MayStore;
2005 InstInfo.mayLoad = MayLoad;
2006 InstInfo.hasSideEffects = HasSideEffects;
2007 }
2008}
2009
Chris Lattnerfe718932008-01-06 01:10:31 +00002010void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002011 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2012
2013 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2014 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2015 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2016 Record *Operator = OpDef->getDef();
2017 TreePattern *Pattern;
2018 if (Operator->getName() != "parallel")
2019 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2020 else {
2021 std::vector<Init*> Values;
2022 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j)
2023 Values.push_back(Tree->getArg(j));
2024 ListInit *LI = new ListInit(Values);
2025 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2026 }
2027
2028 // Inline pattern fragments into it.
2029 Pattern->InlinePatternFragments();
2030
2031 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2032 if (LI->getSize() == 0) continue; // no pattern.
2033
2034 // Parse the instruction.
2035 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2036
2037 // Inline pattern fragments into it.
2038 Result->InlinePatternFragments();
2039
2040 if (Result->getNumTrees() != 1)
2041 Result->error("Cannot handle instructions producing instructions "
2042 "with temporaries yet!");
2043
2044 bool IterateInference;
2045 bool InferredAllPatternTypes, InferredAllResultTypes;
2046 do {
2047 // Infer as many types as possible. If we cannot infer all of them, we
2048 // can never do anything with this pattern: report it to the user.
2049 InferredAllPatternTypes = Pattern->InferAllTypes();
2050
2051 // Infer as many types as possible. If we cannot infer all of them, we
2052 // can never do anything with this pattern: report it to the user.
2053 InferredAllResultTypes = Result->InferAllTypes();
2054
2055 // Apply the type of the result to the source pattern. This helps us
2056 // resolve cases where the input type is known to be a pointer type (which
2057 // is considered resolved), but the result knows it needs to be 32- or
2058 // 64-bits. Infer the other way for good measure.
2059 IterateInference = Pattern->getTree(0)->
2060 UpdateNodeType(Result->getTree(0)->getExtTypes(), *Result);
2061 IterateInference |= Result->getTree(0)->
2062 UpdateNodeType(Pattern->getTree(0)->getExtTypes(), *Result);
2063 } while (IterateInference);
Nate Begeman9008ca62009-04-27 18:41:29 +00002064
Chris Lattner6cefb772008-01-05 22:25:12 +00002065 // Verify that we inferred enough types that we can do something with the
2066 // pattern and result. If these fire the user has to add type casts.
2067 if (!InferredAllPatternTypes)
2068 Pattern->error("Could not infer all types in pattern!");
2069 if (!InferredAllResultTypes)
2070 Result->error("Could not infer all types in pattern result!");
2071
2072 // Validate that the input pattern is correct.
2073 std::map<std::string, TreePatternNode*> InstInputs;
2074 std::map<std::string, TreePatternNode*> InstResults;
2075 std::vector<Record*> InstImpInputs;
2076 std::vector<Record*> InstImpResults;
2077 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2078 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2079 InstInputs, InstResults,
2080 InstImpInputs, InstImpResults);
2081
2082 // Promote the xform function to be an explicit node if set.
2083 TreePatternNode *DstPattern = Result->getOnlyTree();
2084 std::vector<TreePatternNode*> ResultNodeOperands;
2085 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2086 TreePatternNode *OpNode = DstPattern->getChild(ii);
2087 if (Record *Xform = OpNode->getTransformFn()) {
2088 OpNode->setTransformFn(0);
2089 std::vector<TreePatternNode*> Children;
2090 Children.push_back(OpNode);
2091 OpNode = new TreePatternNode(Xform, Children);
2092 }
2093 ResultNodeOperands.push_back(OpNode);
2094 }
2095 DstPattern = Result->getOnlyTree();
2096 if (!DstPattern->isLeaf())
2097 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2098 ResultNodeOperands);
2099 DstPattern->setTypes(Result->getOnlyTree()->getExtTypes());
2100 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2101 Temp.InferAllTypes();
2102
2103 std::string Reason;
2104 if (!Pattern->getTree(0)->canPatternMatch(Reason, *this))
2105 Pattern->error("Pattern can never match: " + Reason);
2106
2107 PatternsToMatch.
2108 push_back(PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2109 Pattern->getTree(0),
2110 Temp.getOnlyTree(), InstImpResults,
2111 Patterns[i]->getValueAsInt("AddedComplexity")));
2112 }
2113}
2114
2115/// CombineChildVariants - Given a bunch of permutations of each child of the
2116/// 'operator' node, put them together in all possible ways.
2117static void CombineChildVariants(TreePatternNode *Orig,
2118 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2119 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002120 CodeGenDAGPatterns &CDP,
2121 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002122 // Make sure that each operand has at least one variant to choose from.
2123 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2124 if (ChildVariants[i].empty())
2125 return;
2126
2127 // The end result is an all-pairs construction of the resultant pattern.
2128 std::vector<unsigned> Idxs;
2129 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00002130 bool NotDone;
2131 do {
2132#ifndef NDEBUG
2133 if (DebugFlag && !Idxs.empty()) {
2134 cerr << Orig->getOperator()->getName() << ": Idxs = [ ";
2135 for (unsigned i = 0; i < Idxs.size(); ++i) {
2136 cerr << Idxs[i] << " ";
2137 }
2138 cerr << "]\n";
2139 }
2140#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00002141 // Create the variant and add it to the output list.
2142 std::vector<TreePatternNode*> NewChildren;
2143 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2144 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2145 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2146
2147 // Copy over properties.
2148 R->setName(Orig->getName());
Dan Gohman0540e172008-10-15 06:17:21 +00002149 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner6cefb772008-01-05 22:25:12 +00002150 R->setTransformFn(Orig->getTransformFn());
2151 R->setTypes(Orig->getExtTypes());
2152
Scott Michel327d0652008-03-05 17:49:05 +00002153 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00002154 std::string ErrString;
2155 if (!R->canPatternMatch(ErrString, CDP)) {
2156 delete R;
2157 } else {
2158 bool AlreadyExists = false;
2159
2160 // Scan to see if this pattern has already been emitted. We can get
2161 // duplication due to things like commuting:
2162 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2163 // which are the same pattern. Ignore the dups.
2164 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002165 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002166 AlreadyExists = true;
2167 break;
2168 }
2169
2170 if (AlreadyExists)
2171 delete R;
2172 else
2173 OutVariants.push_back(R);
2174 }
2175
Scott Michel327d0652008-03-05 17:49:05 +00002176 // Increment indices to the next permutation by incrementing the
2177 // indicies from last index backward, e.g., generate the sequence
2178 // [0, 0], [0, 1], [1, 0], [1, 1].
2179 int IdxsIdx;
2180 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2181 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2182 Idxs[IdxsIdx] = 0;
2183 else
Chris Lattner6cefb772008-01-05 22:25:12 +00002184 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00002185 }
Scott Michel327d0652008-03-05 17:49:05 +00002186 NotDone = (IdxsIdx >= 0);
2187 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00002188}
2189
2190/// CombineChildVariants - A helper function for binary operators.
2191///
2192static void CombineChildVariants(TreePatternNode *Orig,
2193 const std::vector<TreePatternNode*> &LHS,
2194 const std::vector<TreePatternNode*> &RHS,
2195 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002196 CodeGenDAGPatterns &CDP,
2197 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002198 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2199 ChildVariants.push_back(LHS);
2200 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00002201 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002202}
2203
2204
2205static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2206 std::vector<TreePatternNode *> &Children) {
2207 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2208 Record *Operator = N->getOperator();
2209
2210 // Only permit raw nodes.
Dan Gohman0540e172008-10-15 06:17:21 +00002211 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00002212 N->getTransformFn()) {
2213 Children.push_back(N);
2214 return;
2215 }
2216
2217 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2218 Children.push_back(N->getChild(0));
2219 else
2220 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2221
2222 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2223 Children.push_back(N->getChild(1));
2224 else
2225 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2226}
2227
2228/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2229/// the (potentially recursive) pattern by using algebraic laws.
2230///
2231static void GenerateVariantsOf(TreePatternNode *N,
2232 std::vector<TreePatternNode*> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00002233 CodeGenDAGPatterns &CDP,
2234 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002235 // We cannot permute leaves.
2236 if (N->isLeaf()) {
2237 OutVariants.push_back(N);
2238 return;
2239 }
2240
2241 // Look up interesting info about the node.
2242 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2243
Jim Grosbachda4231f2009-03-26 16:17:51 +00002244 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00002245 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00002246 // Re-associate by pulling together all of the linked operators
Chris Lattner6cefb772008-01-05 22:25:12 +00002247 std::vector<TreePatternNode*> MaximalChildren;
2248 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2249
2250 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2251 // permutations.
2252 if (MaximalChildren.size() == 3) {
2253 // Find the variants of all of our maximal children.
2254 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002255 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2256 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2257 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002258
2259 // There are only two ways we can permute the tree:
2260 // (A op B) op C and A op (B op C)
2261 // Within these forms, we can also permute A/B/C.
2262
2263 // Generate legal pair permutations of A/B/C.
2264 std::vector<TreePatternNode*> ABVariants;
2265 std::vector<TreePatternNode*> BAVariants;
2266 std::vector<TreePatternNode*> ACVariants;
2267 std::vector<TreePatternNode*> CAVariants;
2268 std::vector<TreePatternNode*> BCVariants;
2269 std::vector<TreePatternNode*> CBVariants;
Scott Michel327d0652008-03-05 17:49:05 +00002270 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2271 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2272 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2273 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2274 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2275 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002276
2277 // Combine those into the result: (x op x) op x
Scott Michel327d0652008-03-05 17:49:05 +00002278 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2279 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2280 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2281 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2282 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2283 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002284
2285 // Combine those into the result: x op (x op x)
Scott Michel327d0652008-03-05 17:49:05 +00002286 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2287 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2288 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2289 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2290 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2291 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002292 return;
2293 }
2294 }
2295
2296 // Compute permutations of all children.
2297 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2298 ChildVariants.resize(N->getNumChildren());
2299 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel327d0652008-03-05 17:49:05 +00002300 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002301
2302 // Build all permutations based on how the children were formed.
Scott Michel327d0652008-03-05 17:49:05 +00002303 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002304
2305 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002306 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2307 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2308 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2309 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002310 // Don't count children which are actually register references.
2311 unsigned NC = 0;
2312 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2313 TreePatternNode *Child = N->getChild(i);
2314 if (Child->isLeaf())
2315 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2316 Record *RR = DI->getDef();
2317 if (RR->isSubClassOf("Register"))
2318 continue;
2319 }
2320 NC++;
2321 }
2322 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00002323 if (isCommIntrinsic) {
2324 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2325 // operands are the commutative operands, and there might be more operands
2326 // after those.
2327 assert(NC >= 3 &&
2328 "Commutative intrinsic should have at least 3 childrean!");
2329 std::vector<std::vector<TreePatternNode*> > Variants;
2330 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2331 Variants.push_back(ChildVariants[2]);
2332 Variants.push_back(ChildVariants[1]);
2333 for (unsigned i = 3; i != NC; ++i)
2334 Variants.push_back(ChildVariants[i]);
2335 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2336 } else if (NC == 2)
Chris Lattner6cefb772008-01-05 22:25:12 +00002337 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel327d0652008-03-05 17:49:05 +00002338 OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002339 }
2340}
2341
2342
2343// GenerateVariants - Generate variants. For example, commutative patterns can
2344// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00002345void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002346 DOUT << "Generating instruction variants.\n";
2347
2348 // Loop over all of the patterns we've collected, checking to see if we can
2349 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00002350 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00002351 // the .td file having to contain tons of variants of instructions.
2352 //
2353 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2354 // intentionally do not reconsider these. Any variants of added patterns have
2355 // already been added.
2356 //
2357 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel327d0652008-03-05 17:49:05 +00002358 MultipleUseVarSet DepVars;
Chris Lattner6cefb772008-01-05 22:25:12 +00002359 std::vector<TreePatternNode*> Variants;
Scott Michel327d0652008-03-05 17:49:05 +00002360 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2361 DOUT << "Dependent/multiply used variables: ";
2362 DEBUG(DumpDepVars(DepVars));
2363 DOUT << "\n";
2364 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00002365
2366 assert(!Variants.empty() && "Must create at least original variant!");
2367 Variants.erase(Variants.begin()); // Remove the original pattern.
2368
2369 if (Variants.empty()) // No variants for this pattern.
2370 continue;
2371
2372 DOUT << "FOUND VARIANTS OF: ";
2373 DEBUG(PatternsToMatch[i].getSrcPattern()->dump());
2374 DOUT << "\n";
2375
2376 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2377 TreePatternNode *Variant = Variants[v];
2378
2379 DOUT << " VAR#" << v << ": ";
2380 DEBUG(Variant->dump());
2381 DOUT << "\n";
2382
2383 // Scan to see if an instruction or explicit pattern already matches this.
2384 bool AlreadyExists = false;
2385 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2386 // Check to see if this variant already exists.
Scott Michel327d0652008-03-05 17:49:05 +00002387 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002388 DOUT << " *** ALREADY EXISTS, ignoring variant.\n";
2389 AlreadyExists = true;
2390 break;
2391 }
2392 }
2393 // If we already have it, ignore the variant.
2394 if (AlreadyExists) continue;
2395
2396 // Otherwise, add it to the list of patterns we have.
2397 PatternsToMatch.
2398 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2399 Variant, PatternsToMatch[i].getDstPattern(),
2400 PatternsToMatch[i].getDstRegs(),
2401 PatternsToMatch[i].getAddedComplexity()));
2402 }
2403
2404 DOUT << "\n";
2405 }
2406}
2407