blob: ae38830a9d173c4c7d4e14a437f0fa694fe48c76 [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
17#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000018#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000019#include <set>
20using namespace llvm;
21
Chris Lattnerca559d02005-09-08 21:03:01 +000022//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000023// SDTypeConstraint implementation
24//
25
26SDTypeConstraint::SDTypeConstraint(Record *R) {
27 OperandNo = R->getValueAsInt("OperandNum");
28
29 if (R->isSubClassOf("SDTCisVT")) {
30 ConstraintType = SDTCisVT;
31 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
32 } else if (R->isSubClassOf("SDTCisInt")) {
33 ConstraintType = SDTCisInt;
34 } else if (R->isSubClassOf("SDTCisFP")) {
35 ConstraintType = SDTCisFP;
36 } else if (R->isSubClassOf("SDTCisSameAs")) {
37 ConstraintType = SDTCisSameAs;
38 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
39 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
40 ConstraintType = SDTCisVTSmallerThanOp;
41 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
42 R->getValueAsInt("OtherOperandNum");
43 } else {
44 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
45 exit(1);
46 }
47}
48
Chris Lattner32707602005-09-08 23:22:48 +000049/// getOperandNum - Return the node corresponding to operand #OpNo in tree
50/// N, which has NumResults results.
51TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
52 TreePatternNode *N,
53 unsigned NumResults) const {
54 assert(NumResults == 1 && "We only work with single result nodes so far!");
55
56 if (OpNo < NumResults)
57 return N; // FIXME: need value #
58 else
59 return N->getChild(OpNo-NumResults);
60}
61
62/// ApplyTypeConstraint - Given a node in a pattern, apply this type
63/// constraint to the nodes operands. This returns true if it makes a
64/// change, false otherwise. If a type contradiction is found, throw an
65/// exception.
66bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
67 const SDNodeInfo &NodeInfo,
68 TreePattern &TP) const {
69 unsigned NumResults = NodeInfo.getNumResults();
70 assert(NumResults == 1 && "We only work with single result nodes so far!");
71
72 // Check that the number of operands is sane.
73 if (NodeInfo.getNumOperands() >= 0) {
74 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
75 TP.error(N->getOperator()->getName() + " node requires exactly " +
76 itostr(NodeInfo.getNumOperands()) + " operands!");
77 }
78
79 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
80
81 switch (ConstraintType) {
82 default: assert(0 && "Unknown constraint type!");
83 case SDTCisVT:
84 // Operand must be a particular type.
85 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
86 case SDTCisInt:
87 if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
88 NodeToApply->UpdateNodeType(MVT::i1, TP); // throw an error.
89
90 // FIXME: can tell from the target if there is only one Int type supported.
91 return false;
92 case SDTCisFP:
93 if (NodeToApply->hasTypeSet() &&
94 !MVT::isFloatingPoint(NodeToApply->getType()))
95 NodeToApply->UpdateNodeType(MVT::f32, TP); // throw an error.
96 // FIXME: can tell from the target if there is only one FP type supported.
97 return false;
98 case SDTCisSameAs: {
99 TreePatternNode *OtherNode =
100 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
101 return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
102 OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
103 }
104 case SDTCisVTSmallerThanOp: {
105 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
106 // have an integer type that is smaller than the VT.
107 if (!NodeToApply->isLeaf() ||
108 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
109 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
110 ->isSubClassOf("ValueType"))
111 TP.error(N->getOperator()->getName() + " expects a VT operand!");
112 MVT::ValueType VT =
113 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
114 if (!MVT::isInteger(VT))
115 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
116
117 TreePatternNode *OtherNode =
118 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
119 if (OtherNode->hasTypeSet() &&
120 (!MVT::isInteger(OtherNode->getType()) ||
121 OtherNode->getType() <= VT))
122 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
123 return false;
124 }
125 }
126 return false;
127}
128
129
Chris Lattner33c92e92005-09-08 21:27:15 +0000130//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000131// SDNodeInfo implementation
132//
133SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
134 EnumName = R->getValueAsString("Opcode");
135 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000136 Record *TypeProfile = R->getValueAsDef("TypeProfile");
137 NumResults = TypeProfile->getValueAsInt("NumResults");
138 NumOperands = TypeProfile->getValueAsInt("NumOperands");
139
140 // Parse the type constraints.
141 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
142 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
143 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
144 "Constraints list should contain constraint definitions!");
145 Record *Constraint =
146 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
147 TypeConstraints.push_back(Constraint);
148 }
Chris Lattnerca559d02005-09-08 21:03:01 +0000149}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000150
151//===----------------------------------------------------------------------===//
152// TreePatternNode implementation
153//
154
155TreePatternNode::~TreePatternNode() {
156#if 0 // FIXME: implement refcounted tree nodes!
157 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
158 delete getChild(i);
159#endif
160}
161
Chris Lattner32707602005-09-08 23:22:48 +0000162/// UpdateNodeType - Set the node type of N to VT if VT contains
163/// information. If N already contains a conflicting type, then throw an
164/// exception. This returns true if any information was updated.
165///
166bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
167 if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
168 if (getType() == MVT::LAST_VALUETYPE) {
169 setType(VT);
170 return true;
171 }
172
173 TP.error("Type inference contradiction found in node " +
174 getOperator()->getName() + "!");
175 return true; // unreachable
176}
177
178
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000179void TreePatternNode::print(std::ostream &OS) const {
180 if (isLeaf()) {
181 OS << *getLeafValue();
182 } else {
183 OS << "(" << getOperator()->getName();
184 }
185
186 if (getType() == MVT::Other)
187 OS << ":Other";
188 else if (getType() == MVT::LAST_VALUETYPE)
189 ;//OS << ":?";
190 else
191 OS << ":" << getType();
192
193 if (!isLeaf()) {
194 if (getNumChildren() != 0) {
195 OS << " ";
196 getChild(0)->print(OS);
197 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
198 OS << ", ";
199 getChild(i)->print(OS);
200 }
201 }
202 OS << ")";
203 }
204
205 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000206 OS << "<<P:" << PredicateFn << ">>";
Chris Lattnerb0276202005-09-14 22:55:26 +0000207 if (TransformFn)
208 OS << "<<X:" << TransformFn->getName() << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000209 if (!getName().empty())
210 OS << ":$" << getName();
211
212}
213void TreePatternNode::dump() const {
214 print(std::cerr);
215}
216
217/// clone - Make a copy of this tree and all of its children.
218///
219TreePatternNode *TreePatternNode::clone() const {
220 TreePatternNode *New;
221 if (isLeaf()) {
222 New = new TreePatternNode(getLeafValue());
223 } else {
224 std::vector<TreePatternNode*> CChildren;
225 CChildren.reserve(Children.size());
226 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
227 CChildren.push_back(getChild(i)->clone());
228 New = new TreePatternNode(getOperator(), CChildren);
229 }
230 New->setName(getName());
231 New->setType(getType());
232 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000233 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000234 return New;
235}
236
Chris Lattner32707602005-09-08 23:22:48 +0000237/// SubstituteFormalArguments - Replace the formal arguments in this tree
238/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000239void TreePatternNode::
240SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
241 if (isLeaf()) return;
242
243 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
244 TreePatternNode *Child = getChild(i);
245 if (Child->isLeaf()) {
246 Init *Val = Child->getLeafValue();
247 if (dynamic_cast<DefInit*>(Val) &&
248 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
249 // We found a use of a formal argument, replace it with its value.
250 Child = ArgMap[Child->getName()];
251 assert(Child && "Couldn't find formal argument!");
252 setChild(i, Child);
253 }
254 } else {
255 getChild(i)->SubstituteFormalArguments(ArgMap);
256 }
257 }
258}
259
260
261/// InlinePatternFragments - If this pattern refers to any pattern
262/// fragments, inline them into place, giving us a pattern without any
263/// PatFrag references.
264TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
265 if (isLeaf()) return this; // nothing to do.
266 Record *Op = getOperator();
267
268 if (!Op->isSubClassOf("PatFrag")) {
269 // Just recursively inline children nodes.
270 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
271 setChild(i, getChild(i)->InlinePatternFragments(TP));
272 return this;
273 }
274
275 // Otherwise, we found a reference to a fragment. First, look up its
276 // TreePattern record.
277 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
278
279 // Verify that we are passing the right number of operands.
280 if (Frag->getNumArgs() != Children.size())
281 TP.error("'" + Op->getName() + "' fragment requires " +
282 utostr(Frag->getNumArgs()) + " operands!");
283
Chris Lattner37937092005-09-09 01:15:01 +0000284 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000285
286 // Resolve formal arguments to their actual value.
287 if (Frag->getNumArgs()) {
288 // Compute the map of formal to actual arguments.
289 std::map<std::string, TreePatternNode*> ArgMap;
290 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
291 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
292
293 FragTree->SubstituteFormalArguments(ArgMap);
294 }
295
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000296 FragTree->setName(getName());
297
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000298 // Get a new copy of this fragment to stitch into here.
299 //delete this; // FIXME: implement refcounting!
300 return FragTree;
301}
302
Chris Lattner32707602005-09-08 23:22:48 +0000303/// ApplyTypeConstraints - Apply all of the type constraints relevent to
304/// this node and its children in the tree. This returns true if it makes a
305/// change, false otherwise. If a type contradiction is found, throw an
306/// exception.
307bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
308 if (isLeaf()) return false;
309
310 // special handling for set, which isn't really an SDNode.
311 if (getOperator()->getName() == "set") {
312 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
313 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
314 MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
315
316 // Types of operands must match.
317 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
318 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
319 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
320 return MadeChange;
Chris Lattnerabbb6052005-09-15 21:42:00 +0000321 } else if (getOperator()->isSubClassOf("SDNode")) {
322 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
323
324 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
325 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
326 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
327 return MadeChange;
Chris Lattnera28aec12005-09-15 22:23:50 +0000328 } else if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattnerae5b3502005-09-15 21:57:35 +0000329 const DAGInstruction &Inst =
330 TP.getDAGISelEmitter().getInstruction(getOperator());
331
Chris Lattnera28aec12005-09-15 22:23:50 +0000332 assert(Inst.getNumResults() == 1 && "Only supports one result instrs!");
333 // Apply the result type to the node
334 bool MadeChange = UpdateNodeType(Inst.getResultType(0), TP);
335
336 if (getNumChildren() != Inst.getNumOperands())
337 TP.error("Instruction '" + getOperator()->getName() + " expects " +
338 utostr(Inst.getNumOperands()) + " operands, not " +
339 utostr(getNumChildren()) + " operands!");
340 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
341 MadeChange |= getChild(i)->UpdateNodeType(Inst.getOperandType(i), TP);
342 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
343 }
344 return MadeChange;
345 } else {
346 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
347
348 // Node transforms always take one operand, and take and return the same
349 // type.
350 if (getNumChildren() != 1)
351 TP.error("Node transform '" + getOperator()->getName() +
352 "' requires one operand!");
353 bool MadeChange = UpdateNodeType(getChild(0)->getType(), TP);
354 MadeChange |= getChild(0)->UpdateNodeType(getType(), TP);
355 return MadeChange;
Chris Lattner32707602005-09-08 23:22:48 +0000356 }
Chris Lattner32707602005-09-08 23:22:48 +0000357}
358
359
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000360//===----------------------------------------------------------------------===//
361// TreePattern implementation
362//
363
Chris Lattnera28aec12005-09-15 22:23:50 +0000364TreePattern::TreePattern(Record *TheRec, ListInit *RawPat,
Chris Lattneree9f0c32005-09-13 21:20:49 +0000365 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000366 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
367 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000368}
369
Chris Lattnera28aec12005-09-15 22:23:50 +0000370TreePattern::TreePattern(Record *TheRec, DagInit *Pat,
371 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
372 Trees.push_back(ParseTreePattern(Pat));
373}
374
375TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat,
376 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
377 Trees.push_back(Pat);
378}
379
380
381
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000382void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000383 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000384 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000385}
386
387/// getIntrinsicType - Check to see if the specified record has an intrinsic
388/// type which should be applied to it. This infer the type of register
389/// references from the register file information, for example.
390///
391MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
392 // Check to see if this is a register or a register class...
393 if (R->isSubClassOf("RegisterClass"))
394 return getValueType(R->getValueAsDef("RegType"));
395 else if (R->isSubClassOf("PatFrag")) {
Chris Lattner37937092005-09-09 01:15:01 +0000396 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000397 return MVT::LAST_VALUETYPE;
398 } else if (R->isSubClassOf("Register")) {
399 assert(0 && "Explicit registers not handled here yet!\n");
400 return MVT::LAST_VALUETYPE;
401 } else if (R->isSubClassOf("ValueType")) {
402 // Using a VTSDNode.
403 return MVT::Other;
404 } else if (R->getName() == "node") {
405 // Placeholder.
406 return MVT::LAST_VALUETYPE;
407 }
408
Chris Lattner72fe91c2005-09-24 00:40:24 +0000409 error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000410 return MVT::Other;
411}
412
413TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
414 Record *Operator = Dag->getNodeType();
415
416 if (Operator->isSubClassOf("ValueType")) {
417 // If the operator is a ValueType, then this must be "type cast" of a leaf
418 // node.
419 if (Dag->getNumArgs() != 1)
420 error("Type cast only valid for a leaf node!");
421
422 Init *Arg = Dag->getArg(0);
423 TreePatternNode *New;
424 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
Chris Lattner72fe91c2005-09-24 00:40:24 +0000425 Record *R = DI->getDef();
426 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
427 Dag->setArg(0, new DagInit(R,
428 std::vector<std::pair<Init*, std::string> >()));
429 TreePatternNode *TPN = ParseTreePattern(Dag);
430 TPN->setName(Dag->getArgName(0));
431 return TPN;
432 }
433
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000434 New = new TreePatternNode(DI);
435 // If it's a regclass or something else known, set the type.
436 New->setType(getIntrinsicType(DI->getDef()));
437 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
438 New = ParseTreePattern(DI);
439 } else {
440 Arg->dump();
441 error("Unknown leaf value for tree pattern!");
442 return 0;
443 }
444
Chris Lattner32707602005-09-08 23:22:48 +0000445 // Apply the type cast.
446 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000447 return New;
448 }
449
450 // Verify that this is something that makes sense for an operator.
451 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
Chris Lattnerabbb6052005-09-15 21:42:00 +0000452 !Operator->isSubClassOf("Instruction") &&
453 !Operator->isSubClassOf("SDNodeXForm") &&
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000454 Operator->getName() != "set")
455 error("Unrecognized node '" + Operator->getName() + "'!");
456
457 std::vector<TreePatternNode*> Children;
458
459 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
460 Init *Arg = Dag->getArg(i);
461 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
462 Children.push_back(ParseTreePattern(DI));
463 Children.back()->setName(Dag->getArgName(i));
464 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
465 Record *R = DefI->getDef();
466 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
467 // TreePatternNode if its own.
468 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
469 Dag->setArg(i, new DagInit(R,
470 std::vector<std::pair<Init*, std::string> >()));
471 --i; // Revisit this node...
472 } else {
473 TreePatternNode *Node = new TreePatternNode(DefI);
474 Node->setName(Dag->getArgName(i));
475 Children.push_back(Node);
476
477 // If it's a regclass or something else known, set the type.
478 Node->setType(getIntrinsicType(R));
479
480 // Input argument?
481 if (R->getName() == "node") {
482 if (Dag->getArgName(i).empty())
483 error("'node' argument requires a name to match with operand list");
484 Args.push_back(Dag->getArgName(i));
485 }
486 }
487 } else {
488 Arg->dump();
489 error("Unknown leaf value for tree pattern!");
490 }
491 }
492
493 return new TreePatternNode(Operator, Children);
494}
495
Chris Lattner32707602005-09-08 23:22:48 +0000496/// InferAllTypes - Infer/propagate as many types throughout the expression
497/// patterns as possible. Return true if all types are infered, false
498/// otherwise. Throw an exception if a type contradiction is found.
499bool TreePattern::InferAllTypes() {
500 bool MadeChange = true;
501 while (MadeChange) {
502 MadeChange = false;
503 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
504 MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
505 }
506
507 bool HasUnresolvedTypes = false;
508 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
509 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
510 return !HasUnresolvedTypes;
511}
512
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000513void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000514 OS << getRecord()->getName();
515 if (!Args.empty()) {
516 OS << "(" << Args[0];
517 for (unsigned i = 1, e = Args.size(); i != e; ++i)
518 OS << ", " << Args[i];
519 OS << ")";
520 }
521 OS << ": ";
522
523 if (Trees.size() > 1)
524 OS << "[\n";
525 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
526 OS << "\t";
527 Trees[i]->print(OS);
528 OS << "\n";
529 }
530
531 if (Trees.size() > 1)
532 OS << "]\n";
533}
534
535void TreePattern::dump() const { print(std::cerr); }
536
537
538
539//===----------------------------------------------------------------------===//
540// DAGISelEmitter implementation
541//
542
Chris Lattnerca559d02005-09-08 21:03:01 +0000543// Parse all of the SDNode definitions for the target, populating SDNodes.
544void DAGISelEmitter::ParseNodeInfo() {
545 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
546 while (!Nodes.empty()) {
547 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
548 Nodes.pop_back();
549 }
550}
551
Chris Lattner24eeeb82005-09-13 21:51:00 +0000552/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
553/// map, and emit them to the file as functions.
554void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
555 OS << "\n// Node transformations.\n";
556 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
557 while (!Xforms.empty()) {
558 Record *XFormNode = Xforms.back();
559 Record *SDNode = XFormNode->getValueAsDef("Opcode");
560 std::string Code = XFormNode->getValueAsCode("XFormFunction");
561 SDNodeXForms.insert(std::make_pair(XFormNode,
562 std::make_pair(SDNode, Code)));
563
Chris Lattner1048b7a2005-09-13 22:03:37 +0000564 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000565 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
566 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
567
Chris Lattner1048b7a2005-09-13 22:03:37 +0000568 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000569 << "(SDNode *" << C2 << ") {\n";
570 if (ClassName != "SDNode")
571 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
572 OS << Code << "\n}\n";
573 }
574
575 Xforms.pop_back();
576 }
577}
578
579
580
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000581/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
582/// file, building up the PatternFragments map. After we've collected them all,
583/// inline fragments together as necessary, so that there are no references left
584/// inside a pattern fragment to a pattern fragment.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000585///
586/// This also emits all of the predicate functions to the output file.
587///
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000588void DAGISelEmitter::ParsePatternFragments(std::ostream &OS) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000589 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
590
591 // First step, parse all of the fragments and emit predicate functions.
592 OS << "\n// Predicate functions.\n";
593 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000594 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
595 TreePattern *P = new TreePattern(Fragments[i], Tree, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000596 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000597
598 // Validate the argument list, converting it to map, to discard duplicates.
599 std::vector<std::string> &Args = P->getArgList();
600 std::set<std::string> OperandsMap(Args.begin(), Args.end());
601
602 if (OperandsMap.count(""))
603 P->error("Cannot have unnamed 'node' values in pattern fragment!");
604
605 // Parse the operands list.
606 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
607 if (OpsList->getNodeType()->getName() != "ops")
608 P->error("Operands list should start with '(ops ... '!");
609
610 // Copy over the arguments.
611 Args.clear();
612 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
613 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
614 static_cast<DefInit*>(OpsList->getArg(j))->
615 getDef()->getName() != "node")
616 P->error("Operands list should all be 'node' values.");
617 if (OpsList->getArgName(j).empty())
618 P->error("Operands list should have names for each operand!");
619 if (!OperandsMap.count(OpsList->getArgName(j)))
620 P->error("'" + OpsList->getArgName(j) +
621 "' does not occur in pattern or was multiply specified!");
622 OperandsMap.erase(OpsList->getArgName(j));
623 Args.push_back(OpsList->getArgName(j));
624 }
625
626 if (!OperandsMap.empty())
627 P->error("Operands list does not contain an entry for operand '" +
628 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000629
630 // If there is a code init for this fragment, emit the predicate code and
631 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000632 std::string Code = Fragments[i]->getValueAsCode("Predicate");
633 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000634 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000635 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000636 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000637 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
638
Chris Lattner1048b7a2005-09-13 22:03:37 +0000639 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000640 << "(SDNode *" << C2 << ") {\n";
641 if (ClassName != "SDNode")
642 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000643 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000644 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000645 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000646
647 // If there is a node transformation corresponding to this, keep track of
648 // it.
649 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
650 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Chris Lattnerb0276202005-09-14 22:55:26 +0000651 P->getOnlyTree()->setTransformFn(Transform);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000652 }
653
654 OS << "\n\n";
655
656 // Now that we've parsed all of the tree fragments, do a closure on them so
657 // that there are not references to PatFrags left inside of them.
658 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
659 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000660 TreePattern *ThePat = I->second;
661 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000662
Chris Lattner32707602005-09-08 23:22:48 +0000663 // Infer as many types as possible. Don't worry about it if we don't infer
664 // all of them, some may depend on the inputs of the pattern.
665 try {
666 ThePat->InferAllTypes();
667 } catch (...) {
668 // If this pattern fragment is not supported by this target (no types can
669 // satisfy its constraints), just ignore it. If the bogus pattern is
670 // actually used by instructions, the type consistency error will be
671 // reported there.
672 }
673
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000674 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000675 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000676 }
677}
678
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000679/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
Chris Lattnerf1311842005-09-14 23:05:13 +0000680/// instruction input. Return true if this is a real use.
681static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000682 std::map<std::string, TreePatternNode*> &InstInputs) {
683 // No name -> not interesting.
Chris Lattner7da852f2005-09-14 22:06:36 +0000684 if (Pat->getName().empty()) {
685 if (Pat->isLeaf()) {
686 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
687 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
688 I->error("Input " + DI->getDef()->getName() + " must be named!");
689
690 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000691 return false;
Chris Lattner7da852f2005-09-14 22:06:36 +0000692 }
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000693
694 Record *Rec;
695 if (Pat->isLeaf()) {
696 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
697 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
698 Rec = DI->getDef();
699 } else {
700 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
701 Rec = Pat->getOperator();
702 }
703
704 TreePatternNode *&Slot = InstInputs[Pat->getName()];
705 if (!Slot) {
706 Slot = Pat;
707 } else {
708 Record *SlotRec;
709 if (Slot->isLeaf()) {
Chris Lattnerb9f01eb2005-09-16 00:29:46 +0000710 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000711 } else {
712 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
713 SlotRec = Slot->getOperator();
714 }
715
716 // Ensure that the inputs agree if we've already seen this input.
717 if (Rec != SlotRec)
718 I->error("All $" + Pat->getName() + " inputs must agree with each other");
719 if (Slot->getType() != Pat->getType())
720 I->error("All $" + Pat->getName() + " inputs must agree with each other");
721 }
Chris Lattnerf1311842005-09-14 23:05:13 +0000722 return true;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000723}
724
725/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
726/// part of "I", the instruction), computing the set of inputs and outputs of
727/// the pattern. Report errors if we see anything naughty.
728void DAGISelEmitter::
729FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
730 std::map<std::string, TreePatternNode*> &InstInputs,
731 std::map<std::string, Record*> &InstResults) {
732 if (Pat->isLeaf()) {
Chris Lattnerf1311842005-09-14 23:05:13 +0000733 bool isUse = HandleUse(I, Pat, InstInputs);
734 if (!isUse && Pat->getTransformFn())
735 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000736 return;
737 } else if (Pat->getOperator()->getName() != "set") {
738 // If this is not a set, verify that the children nodes are not void typed,
739 // and recurse.
740 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
741 if (Pat->getChild(i)->getType() == MVT::isVoid)
742 I->error("Cannot have void nodes inside of patterns!");
743 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
744 }
745
746 // If this is a non-leaf node with no children, treat it basically as if
747 // it were a leaf. This handles nodes like (imm).
Chris Lattnerf1311842005-09-14 23:05:13 +0000748 bool isUse = false;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000749 if (Pat->getNumChildren() == 0)
Chris Lattnerf1311842005-09-14 23:05:13 +0000750 isUse = HandleUse(I, Pat, InstInputs);
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000751
Chris Lattnerf1311842005-09-14 23:05:13 +0000752 if (!isUse && Pat->getTransformFn())
753 I->error("Cannot specify a transform function for a non-input value!");
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000754 return;
755 }
756
757 // Otherwise, this is a set, validate and collect instruction results.
758 if (Pat->getNumChildren() == 0)
759 I->error("set requires operands!");
760 else if (Pat->getNumChildren() & 1)
761 I->error("set requires an even number of operands");
762
Chris Lattnerf1311842005-09-14 23:05:13 +0000763 if (Pat->getTransformFn())
764 I->error("Cannot specify a transform function on a set node!");
765
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000766 // Check the set destinations.
767 unsigned NumValues = Pat->getNumChildren()/2;
768 for (unsigned i = 0; i != NumValues; ++i) {
769 TreePatternNode *Dest = Pat->getChild(i);
770 if (!Dest->isLeaf())
771 I->error("set destination should be a virtual register!");
772
773 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
774 if (!Val)
775 I->error("set destination should be a virtual register!");
776
777 if (!Val->getDef()->isSubClassOf("RegisterClass"))
778 I->error("set destination should be a virtual register!");
779 if (Dest->getName().empty())
780 I->error("set destination must have a name!");
781 if (InstResults.count(Dest->getName()))
782 I->error("cannot set '" + Dest->getName() +"' multiple times");
783 InstResults[Dest->getName()] = Val->getDef();
784
785 // Verify and collect info from the computation.
786 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
787 InstInputs, InstResults);
788 }
789}
790
791
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000792/// ParseInstructions - Parse all of the instructions, inlining and resolving
793/// any fragments involved. This populates the Instructions list with fully
794/// resolved instructions.
795void DAGISelEmitter::ParseInstructions() {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000796 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
797
798 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
799 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
800 continue; // no pattern yet, ignore it.
801
802 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
803 if (LI->getSize() == 0) continue; // no pattern.
804
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000805 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000806 TreePattern *I = new TreePattern(Instrs[i], LI, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000807 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +0000808 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000809
Chris Lattner95f6b762005-09-08 23:26:30 +0000810 // Infer as many types as possible. If we cannot infer all of them, we can
811 // never do anything with this instruction pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000812 if (!I->InferAllTypes())
Chris Lattner32707602005-09-08 23:22:48 +0000813 I->error("Could not infer all types in pattern!");
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000814
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000815 // InstInputs - Keep track of all of the inputs of the instruction, along
816 // with the record they are declared as.
817 std::map<std::string, TreePatternNode*> InstInputs;
818
819 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000820 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000821 std::map<std::string, Record*> InstResults;
822
Chris Lattner1f39e292005-09-14 00:09:24 +0000823 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000824 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +0000825 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
826 TreePatternNode *Pat = I->getTree(j);
827 if (Pat->getType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000828 I->dump();
829 I->error("Top-level forms in instruction pattern should have"
830 " void types");
831 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000832
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000833 // Find inputs and outputs, and verify the structure of the uses/defs.
834 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +0000835 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000836
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000837 // Now that we have inputs and outputs of the pattern, inspect the operands
838 // list for the instruction. This determines the order that operands are
839 // added to the machine instruction the node corresponds to.
840 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +0000841
842 // Parse the operands list from the (ops) list, validating it.
843 std::vector<std::string> &Args = I->getArgList();
844 assert(Args.empty() && "Args list should still be empty here!");
845 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
846
847 // Check that all of the results occur first in the list.
Chris Lattnerae6d8282005-09-15 21:51:12 +0000848 std::vector<MVT::ValueType> ResultTypes;
Chris Lattner39e8af92005-09-14 18:19:25 +0000849 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +0000850 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000851 I->error("'" + InstResults.begin()->first +
852 "' set but does not appear in operand list!");
Chris Lattner39e8af92005-09-14 18:19:25 +0000853 const std::string &OpName = CGI.OperandList[i].Name;
Chris Lattner39e8af92005-09-14 18:19:25 +0000854
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000855 // Check that it exists in InstResults.
856 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +0000857 if (R == 0)
858 I->error("Operand $" + OpName + " should be a set destination: all "
859 "outputs must occur before inputs in operand list!");
860
861 if (CGI.OperandList[i].Rec != R)
862 I->error("Operand $" + OpName + " class mismatch!");
863
Chris Lattnerae6d8282005-09-15 21:51:12 +0000864 // Remember the return type.
865 ResultTypes.push_back(CGI.OperandList[i].Ty);
866
Chris Lattner39e8af92005-09-14 18:19:25 +0000867 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000868 InstResults.erase(OpName);
869 }
870
Chris Lattner0b592252005-09-14 21:59:34 +0000871 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
872 // the copy while we're checking the inputs.
873 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
Chris Lattnerb0276202005-09-14 22:55:26 +0000874
875 std::vector<TreePatternNode*> ResultNodeOperands;
Chris Lattnerae6d8282005-09-15 21:51:12 +0000876 std::vector<MVT::ValueType> OperandTypes;
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000877 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
878 const std::string &OpName = CGI.OperandList[i].Name;
879 if (OpName.empty())
880 I->error("Operand #" + utostr(i) + " in operands list has no name!");
881
Chris Lattner0b592252005-09-14 21:59:34 +0000882 if (!InstInputsCheck.count(OpName))
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000883 I->error("Operand $" + OpName +
884 " does not appear in the instruction pattern");
Chris Lattner0b592252005-09-14 21:59:34 +0000885 TreePatternNode *InVal = InstInputsCheck[OpName];
Chris Lattnerb0276202005-09-14 22:55:26 +0000886 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000887 if (CGI.OperandList[i].Ty != InVal->getType())
888 I->error("Operand $" + OpName +
889 "'s type disagrees between the operand and pattern");
Chris Lattnerae6d8282005-09-15 21:51:12 +0000890 OperandTypes.push_back(InVal->getType());
Chris Lattnerb0276202005-09-14 22:55:26 +0000891
Chris Lattner2175c182005-09-14 23:01:59 +0000892 // Construct the result for the dest-pattern operand list.
893 TreePatternNode *OpNode = InVal->clone();
894
895 // No predicate is useful on the result.
896 OpNode->setPredicateFn("");
897
898 // Promote the xform function to be an explicit node if set.
899 if (Record *Xform = OpNode->getTransformFn()) {
900 OpNode->setTransformFn(0);
901 std::vector<TreePatternNode*> Children;
902 Children.push_back(OpNode);
903 OpNode = new TreePatternNode(Xform, Children);
904 }
905
906 ResultNodeOperands.push_back(OpNode);
Chris Lattner39e8af92005-09-14 18:19:25 +0000907 }
908
Chris Lattner0b592252005-09-14 21:59:34 +0000909 if (!InstInputsCheck.empty())
910 I->error("Input operand $" + InstInputsCheck.begin()->first +
911 " occurs in pattern but not in operands list!");
Chris Lattnerb0276202005-09-14 22:55:26 +0000912
913 TreePatternNode *ResultPattern =
914 new TreePatternNode(I->getRecord(), ResultNodeOperands);
Chris Lattnera28aec12005-09-15 22:23:50 +0000915
916 // Create and insert the instruction.
917 DAGInstruction TheInst(I, ResultTypes, OperandTypes);
918 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
919
920 // Use a temporary tree pattern to infer all types and make sure that the
921 // constructed result is correct. This depends on the instruction already
922 // being inserted into the Instructions map.
923 TreePattern Temp(I->getRecord(), ResultPattern, *this);
924 Temp.InferAllTypes();
925
926 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
927 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Chris Lattnerb0276202005-09-14 22:55:26 +0000928
Chris Lattner32707602005-09-08 23:22:48 +0000929 DEBUG(I->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000930 }
Chris Lattner1f39e292005-09-14 00:09:24 +0000931
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000932 // If we can, convert the instructions to be patterns that are matched!
Chris Lattnerae5b3502005-09-15 21:57:35 +0000933 for (std::map<Record*, DAGInstruction>::iterator II = Instructions.begin(),
934 E = Instructions.end(); II != E; ++II) {
935 TreePattern *I = II->second.getPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +0000936
937 if (I->getNumTrees() != 1) {
938 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
939 continue;
940 }
941 TreePatternNode *Pattern = I->getTree(0);
942 if (Pattern->getOperator()->getName() != "set")
943 continue; // Not a set (store or something?)
944
945 if (Pattern->getNumChildren() != 2)
946 continue; // Not a set of a single value (not handled so far)
947
948 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
Chris Lattnerae5b3502005-09-15 21:57:35 +0000949 TreePatternNode *DstPattern = II->second.getResultPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +0000950 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
Chris Lattner1f39e292005-09-14 00:09:24 +0000951 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000952}
953
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000954void DAGISelEmitter::ParsePatterns() {
Chris Lattnerabbb6052005-09-15 21:42:00 +0000955 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000956
Chris Lattnerabbb6052005-09-15 21:42:00 +0000957 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnera28aec12005-09-15 22:23:50 +0000958 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
959 TreePattern *Pattern = new TreePattern(Patterns[i], Tree, *this);
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000960
Chris Lattnerabbb6052005-09-15 21:42:00 +0000961 // Inline pattern fragments into it.
962 Pattern->InlinePatternFragments();
963
964 // Infer as many types as possible. If we cannot infer all of them, we can
965 // never do anything with this pattern: report it to the user.
966 if (!Pattern->InferAllTypes())
967 Pattern->error("Could not infer all types in pattern!");
968
969 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
970 if (LI->getSize() == 0) continue; // no pattern.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000971
972 // Parse the instruction.
Chris Lattnera28aec12005-09-15 22:23:50 +0000973 TreePattern *Result = new TreePattern(Patterns[i], LI, *this);
Chris Lattnerabbb6052005-09-15 21:42:00 +0000974
975 // Inline pattern fragments into it.
976 Result->InlinePatternFragments();
977
978 // Infer as many types as possible. If we cannot infer all of them, we can
979 // never do anything with this pattern: report it to the user.
Chris Lattnerabbb6052005-09-15 21:42:00 +0000980 if (!Result->InferAllTypes())
Chris Lattnerae5b3502005-09-15 21:57:35 +0000981 Result->error("Could not infer all types in pattern result!");
Chris Lattnerabbb6052005-09-15 21:42:00 +0000982
983 if (Result->getNumTrees() != 1)
984 Result->error("Cannot handle instructions producing instructions "
985 "with temporaries yet!");
986 PatternsToMatch.push_back(std::make_pair(Pattern->getOnlyTree(),
987 Result->getOnlyTree()));
988 }
Chris Lattnerb39e4be2005-09-15 02:38:02 +0000989
990 DEBUG(std::cerr << "\n\nPARSED PATTERNS TO MATCH:\n\n";
991 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
992 std::cerr << "PATTERN: "; PatternsToMatch[i].first->dump();
993 std::cerr << "\nRESULT: ";PatternsToMatch[i].second->dump();
994 std::cerr << "\n";
995 });
996}
997
Chris Lattnerd1ff35a2005-09-23 21:33:23 +0000998/// EmitMatchForPattern - Emit a matcher for N, going to the label for PatternNo
999/// if the match fails. At this point, we already know that the opcode for N
1000/// matches, and the SDNode for the result has the RootName specified name.
1001void DAGISelEmitter::EmitMatchForPattern(TreePatternNode *N,
Chris Lattner8fc35682005-09-23 23:16:51 +00001002 const std::string &RootName,
1003 std::map<std::string,std::string> &VarMap,
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001004 unsigned PatternNo, std::ostream &OS) {
1005 assert(!N->isLeaf() && "Cannot match against a leaf!");
Chris Lattner72fe91c2005-09-24 00:40:24 +00001006
1007 // If this node has a name associated with it, capture it in VarMap. If
1008 // we already saw this in the pattern, emit code to verify dagness.
1009 if (!N->getName().empty()) {
1010 std::string &VarMapEntry = VarMap[N->getName()];
1011 if (VarMapEntry.empty()) {
1012 VarMapEntry = RootName;
1013 } else {
1014 // If we get here, this is a second reference to a specific name. Since
1015 // we already have checked that the first reference is valid, we don't
1016 // have to recursively match it, just check that it's the same as the
1017 // previously named thing.
1018 OS << " if (" << VarMapEntry << " != " << RootName
1019 << ") goto P" << PatternNo << "Fail;\n";
1020 return;
1021 }
1022 }
1023
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001024 // Emit code to load the child nodes and match their contents recursively.
1025 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Chris Lattner547394c2005-09-23 21:53:45 +00001026 OS << " SDOperand " << RootName << i <<" = " << RootName
1027 << ".getOperand(" << i << ");\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001028 TreePatternNode *Child = N->getChild(i);
Chris Lattner8fc35682005-09-23 23:16:51 +00001029
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001030 if (!Child->isLeaf()) {
1031 // If it's not a leaf, recursively match.
1032 const SDNodeInfo &CInfo = getSDNodeInfo(Child->getOperator());
Chris Lattner547394c2005-09-23 21:53:45 +00001033 OS << " if (" << RootName << i << ".getOpcode() != "
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001034 << CInfo.getEnumName() << ") goto P" << PatternNo << "Fail;\n";
Chris Lattner8fc35682005-09-23 23:16:51 +00001035 EmitMatchForPattern(Child, RootName + utostr(i), VarMap, PatternNo, OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001036 } else {
Chris Lattner72fe91c2005-09-24 00:40:24 +00001037 // If this child has a name associated with it, capture it in VarMap. If
1038 // we already saw this in the pattern, emit code to verify dagness.
1039 if (!Child->getName().empty()) {
1040 std::string &VarMapEntry = VarMap[Child->getName()];
1041 if (VarMapEntry.empty()) {
1042 VarMapEntry = RootName + utostr(i);
1043 } else {
1044 // If we get here, this is a second reference to a specific name. Since
1045 // we already have checked that the first reference is valid, we don't
1046 // have to recursively match it, just check that it's the same as the
1047 // previously named thing.
1048 OS << " if (" << VarMapEntry << " != " << RootName << i
1049 << ") goto P" << PatternNo << "Fail;\n";
1050 continue;
1051 }
1052 }
1053
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001054 // Handle leaves of various types.
1055 Init *LeafVal = Child->getLeafValue();
1056 Record *LeafRec = dynamic_cast<DefInit*>(LeafVal)->getDef();
1057 if (LeafRec->isSubClassOf("RegisterClass")) {
1058 // Handle register references. Nothing to do here.
1059 } else if (LeafRec->isSubClassOf("ValueType")) {
1060 // Make sure this is the specified value type.
1061 OS << " if (cast<VTSDNode>(" << RootName << i << ")->getVT() != "
1062 << "MVT::" << LeafRec->getName() << ") goto P" << PatternNo
1063 << "Fail;\n";
1064 } else {
1065 Child->dump();
1066 assert(0 && "Unknown leaf type!");
1067 }
1068 }
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001069 }
1070
1071 // If there is a node predicate for this, emit the call.
1072 if (!N->getPredicateFn().empty())
1073 OS << " if (!" << N->getPredicateFn() << "(" << RootName
Chris Lattner547394c2005-09-23 21:53:45 +00001074 << ".Val)) goto P" << PatternNo << "Fail;\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001075}
1076
Chris Lattner72fe91c2005-09-24 00:40:24 +00001077
1078unsigned DAGISelEmitter::
1079CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
1080 std::map<std::string,std::string> &VariableMap,
1081 std::ostream &OS){
1082 // This is something selected from the pattern we matched.
1083 if (!N->getName().empty()) {
1084 const std::string &Val = VariableMap[N->getName()];
1085 assert(!Val.empty() &&
1086 "Variable referenced but not defined and not caught earlier!");
1087 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
1088 // Already selected this operand, just return the tmpval.
1089 // FIXME: DO THIS.
1090 } else {
1091 unsigned ResNo = Ctr++;
1092 OS << " SDOperand Tmp" << ResNo << " = Select(" << Val << ");\n";
1093 // FIXME: Add Tmp<ResNo> to VariableMap.
1094 return ResNo;
1095 }
1096 }
1097
1098 if (N->isLeaf()) {
1099 N->dump();
1100 assert(0 && "Unknown leaf type!");
1101 return ~0U;
1102 }
1103
1104 Record *Op = N->getOperator();
1105 if (Op->isSubClassOf("Instruction")) {
1106 // Emit all of the operands.
1107 std::vector<unsigned> Ops;
1108 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1109 Ops.push_back(CodeGenPatternResult(N->getChild(i), Ctr, VariableMap, OS));
1110
1111 CodeGenInstruction &II = Target.getInstruction(Op->getName());
1112 unsigned ResNo = Ctr++;
1113
1114 OS << " SDOperand Tmp" << ResNo << " = CurDAG->getTargetNode("
1115 << II.Namespace << "::" << II.TheDef->getName() << ", MVT::"
1116 << getEnumName(N->getType());
1117 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1118 OS << ", Tmp" << Ops[i];
1119 OS << ");\n";
1120 return ResNo;
1121 } else if (Op->isSubClassOf("SDNodeXForm")) {
1122 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1123 unsigned OpVal = CodeGenPatternResult(N->getChild(0), Ctr, VariableMap, OS);
1124
1125 unsigned ResNo = Ctr++;
1126 OS << " SDOperand Tmp" << ResNo << " = Transform_" << Op->getName()
1127 << "(Tmp" << OpVal << ".Val);\n";
1128 return ResNo;
1129 } else {
1130 N->dump();
1131 assert(0 && "Unknown node in result pattern!");
Jeff Cohena48283b2005-09-25 19:04:43 +00001132 return ~0U;
Chris Lattner72fe91c2005-09-24 00:40:24 +00001133 }
1134}
1135
1136
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001137/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1138/// stream to match the pattern, and generate the code for the match if it
1139/// succeeds.
Chris Lattner3f7e9142005-09-23 20:52:47 +00001140void DAGISelEmitter::EmitCodeForPattern(PatternToMatch &Pattern,
1141 std::ostream &OS) {
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001142 static unsigned PatternCount = 0;
1143 unsigned PatternNo = PatternCount++;
1144 OS << " { // Pattern #" << PatternNo << ": ";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001145 Pattern.first->print(OS);
1146 OS << "\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001147
Chris Lattner8fc35682005-09-23 23:16:51 +00001148 // Emit the matcher, capturing named arguments in VariableMap.
1149 std::map<std::string,std::string> VariableMap;
1150 EmitMatchForPattern(Pattern.first, "N", VariableMap, PatternNo, OS);
Chris Lattner3f7e9142005-09-23 20:52:47 +00001151
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001152 OS << " // Emit: ";
1153 Pattern.second->print(OS);
1154 OS << "\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001155
Chris Lattner72fe91c2005-09-24 00:40:24 +00001156 unsigned TmpNo = 0;
1157 unsigned Res = CodeGenPatternResult(Pattern.second, TmpNo, VariableMap, OS);
Chris Lattner296dfe32005-09-24 00:50:51 +00001158
1159 // Add the result to the map if it has multiple uses.
1160 OS << " if (!N.Val->hasOneUse()) CodeGenMap[N] = Tmp" << Res << ";\n";
Chris Lattner72fe91c2005-09-24 00:40:24 +00001161 OS << " return Tmp" << Res << ";\n";
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001162 OS << " }\n P" << PatternNo << "Fail:\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001163}
1164
1165/// getPatternSize - Return the 'size' of this pattern. We want to match large
1166/// patterns before small ones. This is used to determine the size of a
1167/// pattern.
1168static unsigned getPatternSize(TreePatternNode *P) {
1169 assert(MVT::isInteger(P->getType()) || MVT::isFloatingPoint(P->getType()) &&
1170 "Not a valid pattern node to size!");
1171 unsigned Size = 1; // The node itself.
1172
1173 // Count children in the count if they are also nodes.
1174 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1175 TreePatternNode *Child = P->getChild(i);
1176 if (!Child->isLeaf() && Child->getType() != MVT::Other)
1177 Size += getPatternSize(Child);
1178 }
1179
1180 return Size;
1181}
1182
1183// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
1184// In particular, we want to match maximal patterns first and lowest cost within
1185// a particular complexity first.
1186struct PatternSortingPredicate {
1187 bool operator()(DAGISelEmitter::PatternToMatch *LHS,
1188 DAGISelEmitter::PatternToMatch *RHS) {
1189 unsigned LHSSize = getPatternSize(LHS->first);
1190 unsigned RHSSize = getPatternSize(RHS->first);
1191 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
1192 if (LHSSize < RHSSize) return false;
1193
1194 // If they are equal, compare cost.
1195 // FIXME: Compute cost!
1196 return false;
1197 }
1198};
1199
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001200void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1201 // Emit boilerplate.
1202 OS << "// The main instruction selector code.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001203 << "SDOperand SelectCode(SDOperand N) {\n"
1204 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1205 << " N.getOpcode() < PPCISD::FIRST_NUMBER)\n"
1206 << " return N; // Already selected.\n\n"
Chris Lattner296dfe32005-09-24 00:50:51 +00001207 << " if (!N.Val->hasOneUse()) {\n"
1208 << " std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(N);\n"
1209 << " if (CGMI != CodeGenMap.end()) return CGMI->second;\n"
1210 << " }\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001211 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001212 << " default: break;\n"
1213 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001214 << " return N;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001215 << " case ISD::AssertSext:\n"
1216 << " case ISD::AssertZext:\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001217 << " return Select(N.getOperand(0));\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001218
Chris Lattner81303322005-09-23 19:36:15 +00001219 // Group the patterns by their top-level opcodes.
1220 std::map<Record*, std::vector<PatternToMatch*> > PatternsByOpcode;
1221 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i)
1222 PatternsByOpcode[PatternsToMatch[i].first->getOperator()]
1223 .push_back(&PatternsToMatch[i]);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001224
Chris Lattner3f7e9142005-09-23 20:52:47 +00001225 // Loop over all of the case statements.
Chris Lattner81303322005-09-23 19:36:15 +00001226 for (std::map<Record*, std::vector<PatternToMatch*> >::iterator
1227 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end(); PBOI != E;
1228 ++PBOI) {
1229 const SDNodeInfo &OpcodeInfo = getSDNodeInfo(PBOI->first);
1230 std::vector<PatternToMatch*> &Patterns = PBOI->second;
1231
1232 OS << " case " << OpcodeInfo.getEnumName() << ":\n";
Chris Lattner3f7e9142005-09-23 20:52:47 +00001233
1234 // We want to emit all of the matching code now. However, we want to emit
1235 // the matches in order of minimal cost. Sort the patterns so the least
1236 // cost one is at the start.
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001237 std::stable_sort(Patterns.begin(), Patterns.end(),
1238 PatternSortingPredicate());
Chris Lattner81303322005-09-23 19:36:15 +00001239
Chris Lattner3f7e9142005-09-23 20:52:47 +00001240 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1241 EmitCodeForPattern(*Patterns[i], OS);
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001242 OS << " break;\n\n";
Chris Lattner81303322005-09-23 19:36:15 +00001243 }
1244
1245
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001246 OS << " } // end of big switch.\n\n"
1247 << " std::cerr << \"Cannot yet select: \";\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001248 << " N.Val->dump();\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001249 << " std::cerr << '\\n';\n"
1250 << " abort();\n"
1251 << "}\n";
1252}
1253
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001254void DAGISelEmitter::run(std::ostream &OS) {
1255 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1256 " target", OS);
1257
Chris Lattner1f39e292005-09-14 00:09:24 +00001258 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1259 << "// *** instruction selector class. These functions are really "
1260 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001261
Chris Lattner296dfe32005-09-24 00:50:51 +00001262 OS << "// Instance var to keep track of multiply used nodes that have \n"
1263 << "// already been selected.\n"
1264 << "std::map<SDOperand, SDOperand> CodeGenMap;\n";
1265
Chris Lattnerca559d02005-09-08 21:03:01 +00001266 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +00001267 ParseNodeTransforms(OS);
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001268 ParsePatternFragments(OS);
1269 ParseInstructions();
1270 ParsePatterns();
Chris Lattner3f7e9142005-09-23 20:52:47 +00001271
1272 // FIXME: Generate variants. For example, commutative patterns can match
1273 // multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerb39e4be2005-09-15 02:38:02 +00001274
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001275 // At this point, we have full information about the 'Patterns' we need to
1276 // parse, both implicitly from instructions as well as from explicit pattern
1277 // definitions.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001278
1279 EmitInstructionSelector(OS);
1280
1281 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
1282 E = PatternFragments.end(); I != E; ++I)
1283 delete I->second;
1284 PatternFragments.clear();
1285
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001286 Instructions.clear();
1287}