blob: 0093e50f82184cf46fa8c5953fdb30ff34dc7717 [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"
18#include <set>
19using namespace llvm;
20
Chris Lattnerca559d02005-09-08 21:03:01 +000021//===----------------------------------------------------------------------===//
Chris Lattner33c92e92005-09-08 21:27:15 +000022// SDTypeConstraint implementation
23//
24
25SDTypeConstraint::SDTypeConstraint(Record *R) {
26 OperandNo = R->getValueAsInt("OperandNum");
27
28 if (R->isSubClassOf("SDTCisVT")) {
29 ConstraintType = SDTCisVT;
30 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
31 } else if (R->isSubClassOf("SDTCisInt")) {
32 ConstraintType = SDTCisInt;
33 } else if (R->isSubClassOf("SDTCisFP")) {
34 ConstraintType = SDTCisFP;
35 } else if (R->isSubClassOf("SDTCisSameAs")) {
36 ConstraintType = SDTCisSameAs;
37 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
38 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
39 ConstraintType = SDTCisVTSmallerThanOp;
40 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
41 R->getValueAsInt("OtherOperandNum");
42 } else {
43 std::cerr << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
44 exit(1);
45 }
46}
47
Chris Lattner32707602005-09-08 23:22:48 +000048/// getOperandNum - Return the node corresponding to operand #OpNo in tree
49/// N, which has NumResults results.
50TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
51 TreePatternNode *N,
52 unsigned NumResults) const {
53 assert(NumResults == 1 && "We only work with single result nodes so far!");
54
55 if (OpNo < NumResults)
56 return N; // FIXME: need value #
57 else
58 return N->getChild(OpNo-NumResults);
59}
60
61/// ApplyTypeConstraint - Given a node in a pattern, apply this type
62/// constraint to the nodes operands. This returns true if it makes a
63/// change, false otherwise. If a type contradiction is found, throw an
64/// exception.
65bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
66 const SDNodeInfo &NodeInfo,
67 TreePattern &TP) const {
68 unsigned NumResults = NodeInfo.getNumResults();
69 assert(NumResults == 1 && "We only work with single result nodes so far!");
70
71 // Check that the number of operands is sane.
72 if (NodeInfo.getNumOperands() >= 0) {
73 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
74 TP.error(N->getOperator()->getName() + " node requires exactly " +
75 itostr(NodeInfo.getNumOperands()) + " operands!");
76 }
77
78 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
79
80 switch (ConstraintType) {
81 default: assert(0 && "Unknown constraint type!");
82 case SDTCisVT:
83 // Operand must be a particular type.
84 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
85 case SDTCisInt:
86 if (NodeToApply->hasTypeSet() && !MVT::isInteger(NodeToApply->getType()))
87 NodeToApply->UpdateNodeType(MVT::i1, TP); // throw an error.
88
89 // FIXME: can tell from the target if there is only one Int type supported.
90 return false;
91 case SDTCisFP:
92 if (NodeToApply->hasTypeSet() &&
93 !MVT::isFloatingPoint(NodeToApply->getType()))
94 NodeToApply->UpdateNodeType(MVT::f32, TP); // throw an error.
95 // FIXME: can tell from the target if there is only one FP type supported.
96 return false;
97 case SDTCisSameAs: {
98 TreePatternNode *OtherNode =
99 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
100 return NodeToApply->UpdateNodeType(OtherNode->getType(), TP) |
101 OtherNode->UpdateNodeType(NodeToApply->getType(), TP);
102 }
103 case SDTCisVTSmallerThanOp: {
104 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
105 // have an integer type that is smaller than the VT.
106 if (!NodeToApply->isLeaf() ||
107 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
108 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
109 ->isSubClassOf("ValueType"))
110 TP.error(N->getOperator()->getName() + " expects a VT operand!");
111 MVT::ValueType VT =
112 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
113 if (!MVT::isInteger(VT))
114 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
115
116 TreePatternNode *OtherNode =
117 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
118 if (OtherNode->hasTypeSet() &&
119 (!MVT::isInteger(OtherNode->getType()) ||
120 OtherNode->getType() <= VT))
121 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
122 return false;
123 }
124 }
125 return false;
126}
127
128
Chris Lattner33c92e92005-09-08 21:27:15 +0000129//===----------------------------------------------------------------------===//
Chris Lattnerca559d02005-09-08 21:03:01 +0000130// SDNodeInfo implementation
131//
132SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
133 EnumName = R->getValueAsString("Opcode");
134 SDClassName = R->getValueAsString("SDClass");
Chris Lattner33c92e92005-09-08 21:27:15 +0000135 Record *TypeProfile = R->getValueAsDef("TypeProfile");
136 NumResults = TypeProfile->getValueAsInt("NumResults");
137 NumOperands = TypeProfile->getValueAsInt("NumOperands");
138
139 // Parse the type constraints.
140 ListInit *Constraints = TypeProfile->getValueAsListInit("Constraints");
141 for (unsigned i = 0, e = Constraints->getSize(); i != e; ++i) {
142 assert(dynamic_cast<DefInit*>(Constraints->getElement(i)) &&
143 "Constraints list should contain constraint definitions!");
144 Record *Constraint =
145 static_cast<DefInit*>(Constraints->getElement(i))->getDef();
146 TypeConstraints.push_back(Constraint);
147 }
Chris Lattnerca559d02005-09-08 21:03:01 +0000148}
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000149
150//===----------------------------------------------------------------------===//
151// TreePatternNode implementation
152//
153
154TreePatternNode::~TreePatternNode() {
155#if 0 // FIXME: implement refcounted tree nodes!
156 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
157 delete getChild(i);
158#endif
159}
160
Chris Lattner32707602005-09-08 23:22:48 +0000161/// UpdateNodeType - Set the node type of N to VT if VT contains
162/// information. If N already contains a conflicting type, then throw an
163/// exception. This returns true if any information was updated.
164///
165bool TreePatternNode::UpdateNodeType(MVT::ValueType VT, TreePattern &TP) {
166 if (VT == MVT::LAST_VALUETYPE || getType() == VT) return false;
167 if (getType() == MVT::LAST_VALUETYPE) {
168 setType(VT);
169 return true;
170 }
171
172 TP.error("Type inference contradiction found in node " +
173 getOperator()->getName() + "!");
174 return true; // unreachable
175}
176
177
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000178void TreePatternNode::print(std::ostream &OS) const {
179 if (isLeaf()) {
180 OS << *getLeafValue();
181 } else {
182 OS << "(" << getOperator()->getName();
183 }
184
185 if (getType() == MVT::Other)
186 OS << ":Other";
187 else if (getType() == MVT::LAST_VALUETYPE)
188 ;//OS << ":?";
189 else
190 OS << ":" << getType();
191
192 if (!isLeaf()) {
193 if (getNumChildren() != 0) {
194 OS << " ";
195 getChild(0)->print(OS);
196 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
197 OS << ", ";
198 getChild(i)->print(OS);
199 }
200 }
201 OS << ")";
202 }
203
204 if (!PredicateFn.empty())
Chris Lattner24eeeb82005-09-13 21:51:00 +0000205 OS << "<<P:" << PredicateFn << ">>";
206 if (!TransformFn.empty())
207 OS << "<<X:" << TransformFn << ">>";
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000208 if (!getName().empty())
209 OS << ":$" << getName();
210
211}
212void TreePatternNode::dump() const {
213 print(std::cerr);
214}
215
216/// clone - Make a copy of this tree and all of its children.
217///
218TreePatternNode *TreePatternNode::clone() const {
219 TreePatternNode *New;
220 if (isLeaf()) {
221 New = new TreePatternNode(getLeafValue());
222 } else {
223 std::vector<TreePatternNode*> CChildren;
224 CChildren.reserve(Children.size());
225 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
226 CChildren.push_back(getChild(i)->clone());
227 New = new TreePatternNode(getOperator(), CChildren);
228 }
229 New->setName(getName());
230 New->setType(getType());
231 New->setPredicateFn(getPredicateFn());
Chris Lattner24eeeb82005-09-13 21:51:00 +0000232 New->setTransformFn(getTransformFn());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000233 return New;
234}
235
Chris Lattner32707602005-09-08 23:22:48 +0000236/// SubstituteFormalArguments - Replace the formal arguments in this tree
237/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000238void TreePatternNode::
239SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
240 if (isLeaf()) return;
241
242 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
243 TreePatternNode *Child = getChild(i);
244 if (Child->isLeaf()) {
245 Init *Val = Child->getLeafValue();
246 if (dynamic_cast<DefInit*>(Val) &&
247 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
248 // We found a use of a formal argument, replace it with its value.
249 Child = ArgMap[Child->getName()];
250 assert(Child && "Couldn't find formal argument!");
251 setChild(i, Child);
252 }
253 } else {
254 getChild(i)->SubstituteFormalArguments(ArgMap);
255 }
256 }
257}
258
259
260/// InlinePatternFragments - If this pattern refers to any pattern
261/// fragments, inline them into place, giving us a pattern without any
262/// PatFrag references.
263TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
264 if (isLeaf()) return this; // nothing to do.
265 Record *Op = getOperator();
266
267 if (!Op->isSubClassOf("PatFrag")) {
268 // Just recursively inline children nodes.
269 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
270 setChild(i, getChild(i)->InlinePatternFragments(TP));
271 return this;
272 }
273
274 // Otherwise, we found a reference to a fragment. First, look up its
275 // TreePattern record.
276 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
277
278 // Verify that we are passing the right number of operands.
279 if (Frag->getNumArgs() != Children.size())
280 TP.error("'" + Op->getName() + "' fragment requires " +
281 utostr(Frag->getNumArgs()) + " operands!");
282
Chris Lattner37937092005-09-09 01:15:01 +0000283 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000284
285 // Resolve formal arguments to their actual value.
286 if (Frag->getNumArgs()) {
287 // Compute the map of formal to actual arguments.
288 std::map<std::string, TreePatternNode*> ArgMap;
289 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
290 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
291
292 FragTree->SubstituteFormalArguments(ArgMap);
293 }
294
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000295 FragTree->setName(getName());
296
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000297 // Get a new copy of this fragment to stitch into here.
298 //delete this; // FIXME: implement refcounting!
299 return FragTree;
300}
301
Chris Lattner32707602005-09-08 23:22:48 +0000302/// ApplyTypeConstraints - Apply all of the type constraints relevent to
303/// this node and its children in the tree. This returns true if it makes a
304/// change, false otherwise. If a type contradiction is found, throw an
305/// exception.
306bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
307 if (isLeaf()) return false;
308
309 // special handling for set, which isn't really an SDNode.
310 if (getOperator()->getName() == "set") {
311 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
312 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
313 MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
314
315 // Types of operands must match.
316 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
317 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
318 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
319 return MadeChange;
320 }
321
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;
328}
329
330
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000331//===----------------------------------------------------------------------===//
332// TreePattern implementation
333//
334
Chris Lattneree9f0c32005-09-13 21:20:49 +0000335TreePattern::TreePattern(Record *TheRec, const std::vector<DagInit *> &RawPat,
336 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000337
338 for (unsigned i = 0, e = RawPat.size(); i != e; ++i)
339 Trees.push_back(ParseTreePattern(RawPat[i]));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000340}
341
342void TreePattern::error(const std::string &Msg) const {
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000343 dump();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000344 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000345}
346
347/// getIntrinsicType - Check to see if the specified record has an intrinsic
348/// type which should be applied to it. This infer the type of register
349/// references from the register file information, for example.
350///
351MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
352 // Check to see if this is a register or a register class...
353 if (R->isSubClassOf("RegisterClass"))
354 return getValueType(R->getValueAsDef("RegType"));
355 else if (R->isSubClassOf("PatFrag")) {
Chris Lattner37937092005-09-09 01:15:01 +0000356 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000357 return MVT::LAST_VALUETYPE;
358 } else if (R->isSubClassOf("Register")) {
359 assert(0 && "Explicit registers not handled here yet!\n");
360 return MVT::LAST_VALUETYPE;
361 } else if (R->isSubClassOf("ValueType")) {
362 // Using a VTSDNode.
363 return MVT::Other;
364 } else if (R->getName() == "node") {
365 // Placeholder.
366 return MVT::LAST_VALUETYPE;
367 }
368
369 error("Unknown value used: " + R->getName());
370 return MVT::Other;
371}
372
373TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
374 Record *Operator = Dag->getNodeType();
375
376 if (Operator->isSubClassOf("ValueType")) {
377 // If the operator is a ValueType, then this must be "type cast" of a leaf
378 // node.
379 if (Dag->getNumArgs() != 1)
380 error("Type cast only valid for a leaf node!");
381
382 Init *Arg = Dag->getArg(0);
383 TreePatternNode *New;
384 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
385 New = new TreePatternNode(DI);
386 // If it's a regclass or something else known, set the type.
387 New->setType(getIntrinsicType(DI->getDef()));
388 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
389 New = ParseTreePattern(DI);
390 } else {
391 Arg->dump();
392 error("Unknown leaf value for tree pattern!");
393 return 0;
394 }
395
Chris Lattner32707602005-09-08 23:22:48 +0000396 // Apply the type cast.
397 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000398 return New;
399 }
400
401 // Verify that this is something that makes sense for an operator.
402 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
403 Operator->getName() != "set")
404 error("Unrecognized node '" + Operator->getName() + "'!");
405
406 std::vector<TreePatternNode*> Children;
407
408 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
409 Init *Arg = Dag->getArg(i);
410 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
411 Children.push_back(ParseTreePattern(DI));
412 Children.back()->setName(Dag->getArgName(i));
413 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
414 Record *R = DefI->getDef();
415 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
416 // TreePatternNode if its own.
417 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
418 Dag->setArg(i, new DagInit(R,
419 std::vector<std::pair<Init*, std::string> >()));
420 --i; // Revisit this node...
421 } else {
422 TreePatternNode *Node = new TreePatternNode(DefI);
423 Node->setName(Dag->getArgName(i));
424 Children.push_back(Node);
425
426 // If it's a regclass or something else known, set the type.
427 Node->setType(getIntrinsicType(R));
428
429 // Input argument?
430 if (R->getName() == "node") {
431 if (Dag->getArgName(i).empty())
432 error("'node' argument requires a name to match with operand list");
433 Args.push_back(Dag->getArgName(i));
434 }
435 }
436 } else {
437 Arg->dump();
438 error("Unknown leaf value for tree pattern!");
439 }
440 }
441
442 return new TreePatternNode(Operator, Children);
443}
444
Chris Lattner32707602005-09-08 23:22:48 +0000445/// InferAllTypes - Infer/propagate as many types throughout the expression
446/// patterns as possible. Return true if all types are infered, false
447/// otherwise. Throw an exception if a type contradiction is found.
448bool TreePattern::InferAllTypes() {
449 bool MadeChange = true;
450 while (MadeChange) {
451 MadeChange = false;
452 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
453 MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
454 }
455
456 bool HasUnresolvedTypes = false;
457 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
458 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
459 return !HasUnresolvedTypes;
460}
461
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000462void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000463 OS << getRecord()->getName();
464 if (!Args.empty()) {
465 OS << "(" << Args[0];
466 for (unsigned i = 1, e = Args.size(); i != e; ++i)
467 OS << ", " << Args[i];
468 OS << ")";
469 }
470 OS << ": ";
471
472 if (Trees.size() > 1)
473 OS << "[\n";
474 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
475 OS << "\t";
476 Trees[i]->print(OS);
477 OS << "\n";
478 }
479
480 if (Trees.size() > 1)
481 OS << "]\n";
482}
483
484void TreePattern::dump() const { print(std::cerr); }
485
486
487
488//===----------------------------------------------------------------------===//
489// DAGISelEmitter implementation
490//
491
Chris Lattnerca559d02005-09-08 21:03:01 +0000492// Parse all of the SDNode definitions for the target, populating SDNodes.
493void DAGISelEmitter::ParseNodeInfo() {
494 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
495 while (!Nodes.empty()) {
496 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
497 Nodes.pop_back();
498 }
499}
500
Chris Lattner24eeeb82005-09-13 21:51:00 +0000501/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
502/// map, and emit them to the file as functions.
503void DAGISelEmitter::ParseNodeTransforms(std::ostream &OS) {
504 OS << "\n// Node transformations.\n";
505 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
506 while (!Xforms.empty()) {
507 Record *XFormNode = Xforms.back();
508 Record *SDNode = XFormNode->getValueAsDef("Opcode");
509 std::string Code = XFormNode->getValueAsCode("XFormFunction");
510 SDNodeXForms.insert(std::make_pair(XFormNode,
511 std::make_pair(SDNode, Code)));
512
Chris Lattner1048b7a2005-09-13 22:03:37 +0000513 if (!Code.empty()) {
Chris Lattner24eeeb82005-09-13 21:51:00 +0000514 std::string ClassName = getSDNodeInfo(SDNode).getSDClassName();
515 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
516
Chris Lattner1048b7a2005-09-13 22:03:37 +0000517 OS << "inline SDOperand Transform_" << XFormNode->getName()
Chris Lattner24eeeb82005-09-13 21:51:00 +0000518 << "(SDNode *" << C2 << ") {\n";
519 if (ClassName != "SDNode")
520 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
521 OS << Code << "\n}\n";
522 }
523
524 Xforms.pop_back();
525 }
526}
527
528
529
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000530/// ParseAndResolvePatternFragments - Parse all of the PatFrag definitions in
531/// the .td file, building up the PatternFragments map. After we've collected
532/// them all, inline fragments together as necessary, so that there are no
533/// references left inside a pattern fragment to a pattern fragment.
534///
535/// This also emits all of the predicate functions to the output file.
536///
537void DAGISelEmitter::ParseAndResolvePatternFragments(std::ostream &OS) {
538 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
539
540 // First step, parse all of the fragments and emit predicate functions.
541 OS << "\n// Predicate functions.\n";
542 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
543 std::vector<DagInit*> Trees;
544 Trees.push_back(Fragments[i]->getValueAsDag("Fragment"));
Chris Lattneree9f0c32005-09-13 21:20:49 +0000545 TreePattern *P = new TreePattern(Fragments[i], Trees, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000546 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000547
548 // Validate the argument list, converting it to map, to discard duplicates.
549 std::vector<std::string> &Args = P->getArgList();
550 std::set<std::string> OperandsMap(Args.begin(), Args.end());
551
552 if (OperandsMap.count(""))
553 P->error("Cannot have unnamed 'node' values in pattern fragment!");
554
555 // Parse the operands list.
556 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
557 if (OpsList->getNodeType()->getName() != "ops")
558 P->error("Operands list should start with '(ops ... '!");
559
560 // Copy over the arguments.
561 Args.clear();
562 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
563 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
564 static_cast<DefInit*>(OpsList->getArg(j))->
565 getDef()->getName() != "node")
566 P->error("Operands list should all be 'node' values.");
567 if (OpsList->getArgName(j).empty())
568 P->error("Operands list should have names for each operand!");
569 if (!OperandsMap.count(OpsList->getArgName(j)))
570 P->error("'" + OpsList->getArgName(j) +
571 "' does not occur in pattern or was multiply specified!");
572 OperandsMap.erase(OpsList->getArgName(j));
573 Args.push_back(OpsList->getArgName(j));
574 }
575
576 if (!OperandsMap.empty())
577 P->error("Operands list does not contain an entry for operand '" +
578 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000579
580 // If there is a code init for this fragment, emit the predicate code and
581 // keep track of the fact that this fragment uses it.
Chris Lattner24eeeb82005-09-13 21:51:00 +0000582 std::string Code = Fragments[i]->getValueAsCode("Predicate");
583 if (!Code.empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000584 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000585 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000586 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000587 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
588
Chris Lattner1048b7a2005-09-13 22:03:37 +0000589 OS << "inline bool Predicate_" << Fragments[i]->getName()
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000590 << "(SDNode *" << C2 << ") {\n";
591 if (ClassName != "SDNode")
592 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
Chris Lattner24eeeb82005-09-13 21:51:00 +0000593 OS << Code << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000594 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000595 }
Chris Lattner6de8b532005-09-13 21:59:15 +0000596
597 // If there is a node transformation corresponding to this, keep track of
598 // it.
599 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
600 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
601 P->getOnlyTree()->setTransformFn("Transform_"+Transform->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000602 }
603
604 OS << "\n\n";
605
606 // Now that we've parsed all of the tree fragments, do a closure on them so
607 // that there are not references to PatFrags left inside of them.
608 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
609 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000610 TreePattern *ThePat = I->second;
611 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000612
Chris Lattner32707602005-09-08 23:22:48 +0000613 // Infer as many types as possible. Don't worry about it if we don't infer
614 // all of them, some may depend on the inputs of the pattern.
615 try {
616 ThePat->InferAllTypes();
617 } catch (...) {
618 // If this pattern fragment is not supported by this target (no types can
619 // satisfy its constraints), just ignore it. If the bogus pattern is
620 // actually used by instructions, the type consistency error will be
621 // reported there.
622 }
623
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000624 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000625 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000626 }
627}
628
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000629/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
630/// instruction input.
631static void HandleUse(TreePattern *I, TreePatternNode *Pat,
632 std::map<std::string, TreePatternNode*> &InstInputs) {
633 // No name -> not interesting.
634 if (Pat->getName().empty()) return;
635
636 Record *Rec;
637 if (Pat->isLeaf()) {
638 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
639 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
640 Rec = DI->getDef();
641 } else {
642 assert(Pat->getNumChildren() == 0 && "can't be a use with children!");
643 Rec = Pat->getOperator();
644 }
645
646 TreePatternNode *&Slot = InstInputs[Pat->getName()];
647 if (!Slot) {
648 Slot = Pat;
649 } else {
650 Record *SlotRec;
651 if (Slot->isLeaf()) {
652 Rec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
653 } else {
654 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
655 SlotRec = Slot->getOperator();
656 }
657
658 // Ensure that the inputs agree if we've already seen this input.
659 if (Rec != SlotRec)
660 I->error("All $" + Pat->getName() + " inputs must agree with each other");
661 if (Slot->getType() != Pat->getType())
662 I->error("All $" + Pat->getName() + " inputs must agree with each other");
663 }
664}
665
666/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
667/// part of "I", the instruction), computing the set of inputs and outputs of
668/// the pattern. Report errors if we see anything naughty.
669void DAGISelEmitter::
670FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
671 std::map<std::string, TreePatternNode*> &InstInputs,
672 std::map<std::string, Record*> &InstResults) {
673 if (Pat->isLeaf()) {
674 HandleUse(I, Pat, InstInputs);
675 return;
676 } else if (Pat->getOperator()->getName() != "set") {
677 // If this is not a set, verify that the children nodes are not void typed,
678 // and recurse.
679 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
680 if (Pat->getChild(i)->getType() == MVT::isVoid)
681 I->error("Cannot have void nodes inside of patterns!");
682 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults);
683 }
684
685 // If this is a non-leaf node with no children, treat it basically as if
686 // it were a leaf. This handles nodes like (imm).
687 if (Pat->getNumChildren() == 0)
688 HandleUse(I, Pat, InstInputs);
689
690 return;
691 }
692
693 // Otherwise, this is a set, validate and collect instruction results.
694 if (Pat->getNumChildren() == 0)
695 I->error("set requires operands!");
696 else if (Pat->getNumChildren() & 1)
697 I->error("set requires an even number of operands");
698
699 // Check the set destinations.
700 unsigned NumValues = Pat->getNumChildren()/2;
701 for (unsigned i = 0; i != NumValues; ++i) {
702 TreePatternNode *Dest = Pat->getChild(i);
703 if (!Dest->isLeaf())
704 I->error("set destination should be a virtual register!");
705
706 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
707 if (!Val)
708 I->error("set destination should be a virtual register!");
709
710 if (!Val->getDef()->isSubClassOf("RegisterClass"))
711 I->error("set destination should be a virtual register!");
712 if (Dest->getName().empty())
713 I->error("set destination must have a name!");
714 if (InstResults.count(Dest->getName()))
715 I->error("cannot set '" + Dest->getName() +"' multiple times");
716 InstResults[Dest->getName()] = Val->getDef();
717
718 // Verify and collect info from the computation.
719 FindPatternInputsAndOutputs(I, Pat->getChild(i+NumValues),
720 InstInputs, InstResults);
721 }
722}
723
724
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000725/// ParseAndResolveInstructions - Parse all of the instructions, inlining and
726/// resolving any fragments involved. This populates the Instructions list with
727/// fully resolved instructions.
728void DAGISelEmitter::ParseAndResolveInstructions() {
729 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
730
731 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
732 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
733 continue; // no pattern yet, ignore it.
734
735 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
736 if (LI->getSize() == 0) continue; // no pattern.
737
738 std::vector<DagInit*> Trees;
739 for (unsigned j = 0, e = LI->getSize(); j != e; ++j)
740 Trees.push_back((DagInit*)LI->getElement(j));
741
742 // Parse the instruction.
Chris Lattneree9f0c32005-09-13 21:20:49 +0000743 TreePattern *I = new TreePattern(Instrs[i], Trees, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000744 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +0000745 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000746
Chris Lattner95f6b762005-09-08 23:26:30 +0000747 // Infer as many types as possible. If we cannot infer all of them, we can
748 // never do anything with this instruction pattern: report it to the user.
Chris Lattner32707602005-09-08 23:22:48 +0000749 if (!I->InferAllTypes()) {
750 I->dump();
751 I->error("Could not infer all types in pattern!");
752 }
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000753
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000754 // InstInputs - Keep track of all of the inputs of the instruction, along
755 // with the record they are declared as.
756 std::map<std::string, TreePatternNode*> InstInputs;
757
758 // InstResults - Keep track of all the virtual registers that are 'set'
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000759 // in the instruction, including what reg class they are.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000760 std::map<std::string, Record*> InstResults;
761
Chris Lattner1f39e292005-09-14 00:09:24 +0000762 // Verify that the top-level forms in the instruction are of void type, and
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000763 // fill in the InstResults map.
Chris Lattner1f39e292005-09-14 00:09:24 +0000764 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
765 TreePatternNode *Pat = I->getTree(j);
766 if (Pat->getType() != MVT::isVoid) {
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000767 I->dump();
768 I->error("Top-level forms in instruction pattern should have"
769 " void types");
770 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000771
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000772 // Find inputs and outputs, and verify the structure of the uses/defs.
773 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults);
Chris Lattner1f39e292005-09-14 00:09:24 +0000774 }
Chris Lattner5f8cb2a2005-09-14 02:11:12 +0000775
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000776 // Now that we have inputs and outputs of the pattern, inspect the operands
777 // list for the instruction. This determines the order that operands are
778 // added to the machine instruction the node corresponds to.
779 unsigned NumResults = InstResults.size();
Chris Lattner39e8af92005-09-14 18:19:25 +0000780
781 // Parse the operands list from the (ops) list, validating it.
782 std::vector<std::string> &Args = I->getArgList();
783 assert(Args.empty() && "Args list should still be empty here!");
784 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]->getName());
785
786 // Check that all of the results occur first in the list.
787 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattner3a7319d2005-09-14 21:04:12 +0000788 if (i == CGI.OperandList.size())
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000789 I->error("'" + InstResults.begin()->first +
790 "' set but does not appear in operand list!");
791
Chris Lattner39e8af92005-09-14 18:19:25 +0000792 const std::string &OpName = CGI.OperandList[i].Name;
793 if (OpName.empty())
794 I->error("Operand #" + utostr(i) + " in operands list has no name!");
795
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000796 // Check that it exists in InstResults.
797 Record *R = InstResults[OpName];
Chris Lattner39e8af92005-09-14 18:19:25 +0000798 if (R == 0)
799 I->error("Operand $" + OpName + " should be a set destination: all "
800 "outputs must occur before inputs in operand list!");
801
802 if (CGI.OperandList[i].Rec != R)
803 I->error("Operand $" + OpName + " class mismatch!");
804
805 // Okay, this one checks out.
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000806 InstResults.erase(OpName);
807 }
808
809 // Loop over the inputs next.
810 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
811 const std::string &OpName = CGI.OperandList[i].Name;
812 if (OpName.empty())
813 I->error("Operand #" + utostr(i) + " in operands list has no name!");
814
815 if (!InstInputs.count(OpName))
816 I->error("Operand $" + OpName +
817 " does not appear in the instruction pattern");
818 TreePatternNode *InVal = InstInputs[OpName];
819 if (CGI.OperandList[i].Ty != InVal->getType())
820 I->error("Operand $" + OpName +
821 "'s type disagrees between the operand and pattern");
Chris Lattner39e8af92005-09-14 18:19:25 +0000822 }
823
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000824 unsigned NumOperands = CGI.OperandList.size()-NumResults;
825
Chris Lattner32707602005-09-08 23:22:48 +0000826 DEBUG(I->dump());
Chris Lattnerec676432005-09-14 04:03:16 +0000827 Instructions.push_back(DAGInstruction(I, NumResults, NumOperands));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000828 }
Chris Lattner1f39e292005-09-14 00:09:24 +0000829
Chris Lattnerd8a3bde2005-09-14 20:53:42 +0000830 // If we can, convert the instructions to be patterns that are matched!
Chris Lattner1f39e292005-09-14 00:09:24 +0000831 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
Chris Lattnerec676432005-09-14 04:03:16 +0000832 TreePattern *I = Instructions[i].getPattern();
Chris Lattner1f39e292005-09-14 00:09:24 +0000833
834 if (I->getNumTrees() != 1) {
835 std::cerr << "CANNOT HANDLE: " << I->getRecord()->getName() << " yet!";
836 continue;
837 }
838 TreePatternNode *Pattern = I->getTree(0);
839 if (Pattern->getOperator()->getName() != "set")
840 continue; // Not a set (store or something?)
841
842 if (Pattern->getNumChildren() != 2)
843 continue; // Not a set of a single value (not handled so far)
844
845 TreePatternNode *SrcPattern = Pattern->getChild(1)->clone();
846 TreePatternNode *DstPattern = SrcPattern->clone(); // FIXME: WRONG
847 PatternsToMatch.push_back(std::make_pair(SrcPattern, DstPattern));
848 DEBUG(std::cerr << "PATTERN TO MATCH: "; SrcPattern->dump();
849 std::cerr << "\nRESULT DAG : ";
850 DstPattern->dump(); std::cerr << "\n");
851 }
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000852}
853
854void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
855 // Emit boilerplate.
856 OS << "// The main instruction selector code.\n"
Chris Lattnerf4f33ba2005-09-13 22:05:02 +0000857 << "SDOperand SelectCode(SDOperand Op) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000858 << " SDNode *N = Op.Val;\n"
859 << " if (N->getOpcode() >= ISD::BUILTIN_OP_END &&\n"
860 << " N->getOpcode() < PPCISD::FIRST_NUMBER)\n"
861 << " return Op; // Already selected.\n\n"
862 << " switch (N->getOpcode()) {\n"
863 << " default: break;\n"
864 << " case ISD::EntryToken: // These leaves remain the same.\n"
865 << " return Op;\n"
866 << " case ISD::AssertSext:\n"
867 << " case ISD::AssertZext:\n"
868 << " return Select(N->getOperand(0));\n";
869
870
871
872 OS << " } // end of big switch.\n\n"
873 << " std::cerr << \"Cannot yet select: \";\n"
874 << " N->dump();\n"
875 << " std::cerr << '\\n';\n"
876 << " abort();\n"
877 << "}\n";
878}
879
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000880void DAGISelEmitter::run(std::ostream &OS) {
881 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
882 " target", OS);
883
Chris Lattner1f39e292005-09-14 00:09:24 +0000884 OS << "// *** NOTE: This file is #included into the middle of the target\n"
885 << "// *** instruction selector class. These functions are really "
886 << "methods.\n\n";
Chris Lattnerca559d02005-09-08 21:03:01 +0000887 ParseNodeInfo();
Chris Lattner24eeeb82005-09-13 21:51:00 +0000888 ParseNodeTransforms(OS);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000889 ParseAndResolvePatternFragments(OS);
890 ParseAndResolveInstructions();
891
892 // TODO: convert some instructions to expanders if needed or something.
893
894 EmitInstructionSelector(OS);
895
896 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
897 E = PatternFragments.end(); I != E; ++I)
898 delete I->second;
899 PatternFragments.clear();
900
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000901 Instructions.clear();
902}