blob: 4d32af93ff0c1fcbdc7bc3e32dd568e2092d84fe [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())
205 OS << "<<" << PredicateFn << ">>";
206 if (!getName().empty())
207 OS << ":$" << getName();
208
209}
210void TreePatternNode::dump() const {
211 print(std::cerr);
212}
213
214/// clone - Make a copy of this tree and all of its children.
215///
216TreePatternNode *TreePatternNode::clone() const {
217 TreePatternNode *New;
218 if (isLeaf()) {
219 New = new TreePatternNode(getLeafValue());
220 } else {
221 std::vector<TreePatternNode*> CChildren;
222 CChildren.reserve(Children.size());
223 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
224 CChildren.push_back(getChild(i)->clone());
225 New = new TreePatternNode(getOperator(), CChildren);
226 }
227 New->setName(getName());
228 New->setType(getType());
229 New->setPredicateFn(getPredicateFn());
230 return New;
231}
232
Chris Lattner32707602005-09-08 23:22:48 +0000233/// SubstituteFormalArguments - Replace the formal arguments in this tree
234/// with actual values specified by ArgMap.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000235void TreePatternNode::
236SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
237 if (isLeaf()) return;
238
239 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
240 TreePatternNode *Child = getChild(i);
241 if (Child->isLeaf()) {
242 Init *Val = Child->getLeafValue();
243 if (dynamic_cast<DefInit*>(Val) &&
244 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
245 // We found a use of a formal argument, replace it with its value.
246 Child = ArgMap[Child->getName()];
247 assert(Child && "Couldn't find formal argument!");
248 setChild(i, Child);
249 }
250 } else {
251 getChild(i)->SubstituteFormalArguments(ArgMap);
252 }
253 }
254}
255
256
257/// InlinePatternFragments - If this pattern refers to any pattern
258/// fragments, inline them into place, giving us a pattern without any
259/// PatFrag references.
260TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
261 if (isLeaf()) return this; // nothing to do.
262 Record *Op = getOperator();
263
264 if (!Op->isSubClassOf("PatFrag")) {
265 // Just recursively inline children nodes.
266 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
267 setChild(i, getChild(i)->InlinePatternFragments(TP));
268 return this;
269 }
270
271 // Otherwise, we found a reference to a fragment. First, look up its
272 // TreePattern record.
273 TreePattern *Frag = TP.getDAGISelEmitter().getPatternFragment(Op);
274
275 // Verify that we are passing the right number of operands.
276 if (Frag->getNumArgs() != Children.size())
277 TP.error("'" + Op->getName() + "' fragment requires " +
278 utostr(Frag->getNumArgs()) + " operands!");
279
Chris Lattner37937092005-09-09 01:15:01 +0000280 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000281
282 // Resolve formal arguments to their actual value.
283 if (Frag->getNumArgs()) {
284 // Compute the map of formal to actual arguments.
285 std::map<std::string, TreePatternNode*> ArgMap;
286 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
287 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
288
289 FragTree->SubstituteFormalArguments(ArgMap);
290 }
291
Chris Lattnerfbf8e572005-09-08 17:45:12 +0000292 FragTree->setName(getName());
293
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000294 // Get a new copy of this fragment to stitch into here.
295 //delete this; // FIXME: implement refcounting!
296 return FragTree;
297}
298
Chris Lattner32707602005-09-08 23:22:48 +0000299/// ApplyTypeConstraints - Apply all of the type constraints relevent to
300/// this node and its children in the tree. This returns true if it makes a
301/// change, false otherwise. If a type contradiction is found, throw an
302/// exception.
303bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP) {
304 if (isLeaf()) return false;
305
306 // special handling for set, which isn't really an SDNode.
307 if (getOperator()->getName() == "set") {
308 assert (getNumChildren() == 2 && "Only handle 2 operand set's for now!");
309 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP);
310 MadeChange |= getChild(1)->ApplyTypeConstraints(TP);
311
312 // Types of operands must match.
313 MadeChange |= getChild(0)->UpdateNodeType(getChild(1)->getType(), TP);
314 MadeChange |= getChild(1)->UpdateNodeType(getChild(0)->getType(), TP);
315 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
316 return MadeChange;
317 }
318
319 const SDNodeInfo &NI = TP.getDAGISelEmitter().getSDNodeInfo(getOperator());
320
321 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
322 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
323 MadeChange |= getChild(i)->ApplyTypeConstraints(TP);
324 return MadeChange;
325}
326
327
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000328//===----------------------------------------------------------------------===//
329// TreePattern implementation
330//
331
Chris Lattneree9f0c32005-09-13 21:20:49 +0000332TreePattern::TreePattern(Record *TheRec, const std::vector<DagInit *> &RawPat,
333 DAGISelEmitter &ise) : TheRecord(TheRec), ISE(ise) {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000334
335 for (unsigned i = 0, e = RawPat.size(); i != e; ++i)
336 Trees.push_back(ParseTreePattern(RawPat[i]));
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000337}
338
339void TreePattern::error(const std::string &Msg) const {
Chris Lattneree9f0c32005-09-13 21:20:49 +0000340 throw "In " + TheRecord->getName() + ": " + Msg;
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000341}
342
343/// getIntrinsicType - Check to see if the specified record has an intrinsic
344/// type which should be applied to it. This infer the type of register
345/// references from the register file information, for example.
346///
347MVT::ValueType TreePattern::getIntrinsicType(Record *R) const {
348 // Check to see if this is a register or a register class...
349 if (R->isSubClassOf("RegisterClass"))
350 return getValueType(R->getValueAsDef("RegType"));
351 else if (R->isSubClassOf("PatFrag")) {
Chris Lattner37937092005-09-09 01:15:01 +0000352 // Pattern fragment types will be resolved when they are inlined.
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000353 return MVT::LAST_VALUETYPE;
354 } else if (R->isSubClassOf("Register")) {
355 assert(0 && "Explicit registers not handled here yet!\n");
356 return MVT::LAST_VALUETYPE;
357 } else if (R->isSubClassOf("ValueType")) {
358 // Using a VTSDNode.
359 return MVT::Other;
360 } else if (R->getName() == "node") {
361 // Placeholder.
362 return MVT::LAST_VALUETYPE;
363 }
364
365 error("Unknown value used: " + R->getName());
366 return MVT::Other;
367}
368
369TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
370 Record *Operator = Dag->getNodeType();
371
372 if (Operator->isSubClassOf("ValueType")) {
373 // If the operator is a ValueType, then this must be "type cast" of a leaf
374 // node.
375 if (Dag->getNumArgs() != 1)
376 error("Type cast only valid for a leaf node!");
377
378 Init *Arg = Dag->getArg(0);
379 TreePatternNode *New;
380 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
381 New = new TreePatternNode(DI);
382 // If it's a regclass or something else known, set the type.
383 New->setType(getIntrinsicType(DI->getDef()));
384 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
385 New = ParseTreePattern(DI);
386 } else {
387 Arg->dump();
388 error("Unknown leaf value for tree pattern!");
389 return 0;
390 }
391
Chris Lattner32707602005-09-08 23:22:48 +0000392 // Apply the type cast.
393 New->UpdateNodeType(getValueType(Operator), *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000394 return New;
395 }
396
397 // Verify that this is something that makes sense for an operator.
398 if (!Operator->isSubClassOf("PatFrag") && !Operator->isSubClassOf("SDNode") &&
399 Operator->getName() != "set")
400 error("Unrecognized node '" + Operator->getName() + "'!");
401
402 std::vector<TreePatternNode*> Children;
403
404 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
405 Init *Arg = Dag->getArg(i);
406 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
407 Children.push_back(ParseTreePattern(DI));
408 Children.back()->setName(Dag->getArgName(i));
409 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
410 Record *R = DefI->getDef();
411 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
412 // TreePatternNode if its own.
413 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
414 Dag->setArg(i, new DagInit(R,
415 std::vector<std::pair<Init*, std::string> >()));
416 --i; // Revisit this node...
417 } else {
418 TreePatternNode *Node = new TreePatternNode(DefI);
419 Node->setName(Dag->getArgName(i));
420 Children.push_back(Node);
421
422 // If it's a regclass or something else known, set the type.
423 Node->setType(getIntrinsicType(R));
424
425 // Input argument?
426 if (R->getName() == "node") {
427 if (Dag->getArgName(i).empty())
428 error("'node' argument requires a name to match with operand list");
429 Args.push_back(Dag->getArgName(i));
430 }
431 }
432 } else {
433 Arg->dump();
434 error("Unknown leaf value for tree pattern!");
435 }
436 }
437
438 return new TreePatternNode(Operator, Children);
439}
440
Chris Lattner32707602005-09-08 23:22:48 +0000441/// InferAllTypes - Infer/propagate as many types throughout the expression
442/// patterns as possible. Return true if all types are infered, false
443/// otherwise. Throw an exception if a type contradiction is found.
444bool TreePattern::InferAllTypes() {
445 bool MadeChange = true;
446 while (MadeChange) {
447 MadeChange = false;
448 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
449 MadeChange |= Trees[i]->ApplyTypeConstraints(*this);
450 }
451
452 bool HasUnresolvedTypes = false;
453 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
454 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
455 return !HasUnresolvedTypes;
456}
457
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000458void TreePattern::print(std::ostream &OS) const {
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000459 OS << getRecord()->getName();
460 if (!Args.empty()) {
461 OS << "(" << Args[0];
462 for (unsigned i = 1, e = Args.size(); i != e; ++i)
463 OS << ", " << Args[i];
464 OS << ")";
465 }
466 OS << ": ";
467
468 if (Trees.size() > 1)
469 OS << "[\n";
470 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
471 OS << "\t";
472 Trees[i]->print(OS);
473 OS << "\n";
474 }
475
476 if (Trees.size() > 1)
477 OS << "]\n";
478}
479
480void TreePattern::dump() const { print(std::cerr); }
481
482
483
484//===----------------------------------------------------------------------===//
485// DAGISelEmitter implementation
486//
487
Chris Lattnerca559d02005-09-08 21:03:01 +0000488// Parse all of the SDNode definitions for the target, populating SDNodes.
489void DAGISelEmitter::ParseNodeInfo() {
490 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
491 while (!Nodes.empty()) {
492 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
493 Nodes.pop_back();
494 }
495}
496
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000497/// ParseAndResolvePatternFragments - Parse all of the PatFrag definitions in
498/// the .td file, building up the PatternFragments map. After we've collected
499/// them all, inline fragments together as necessary, so that there are no
500/// references left inside a pattern fragment to a pattern fragment.
501///
502/// This also emits all of the predicate functions to the output file.
503///
504void DAGISelEmitter::ParseAndResolvePatternFragments(std::ostream &OS) {
505 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
506
507 // First step, parse all of the fragments and emit predicate functions.
508 OS << "\n// Predicate functions.\n";
509 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
510 std::vector<DagInit*> Trees;
511 Trees.push_back(Fragments[i]->getValueAsDag("Fragment"));
Chris Lattneree9f0c32005-09-13 21:20:49 +0000512 TreePattern *P = new TreePattern(Fragments[i], Trees, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000513 PatternFragments[Fragments[i]] = P;
Chris Lattneree9f0c32005-09-13 21:20:49 +0000514
515 // Validate the argument list, converting it to map, to discard duplicates.
516 std::vector<std::string> &Args = P->getArgList();
517 std::set<std::string> OperandsMap(Args.begin(), Args.end());
518
519 if (OperandsMap.count(""))
520 P->error("Cannot have unnamed 'node' values in pattern fragment!");
521
522 // Parse the operands list.
523 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
524 if (OpsList->getNodeType()->getName() != "ops")
525 P->error("Operands list should start with '(ops ... '!");
526
527 // Copy over the arguments.
528 Args.clear();
529 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
530 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
531 static_cast<DefInit*>(OpsList->getArg(j))->
532 getDef()->getName() != "node")
533 P->error("Operands list should all be 'node' values.");
534 if (OpsList->getArgName(j).empty())
535 P->error("Operands list should have names for each operand!");
536 if (!OperandsMap.count(OpsList->getArgName(j)))
537 P->error("'" + OpsList->getArgName(j) +
538 "' does not occur in pattern or was multiply specified!");
539 OperandsMap.erase(OpsList->getArgName(j));
540 Args.push_back(OpsList->getArgName(j));
541 }
542
543 if (!OperandsMap.empty())
544 P->error("Operands list does not contain an entry for operand '" +
545 *OperandsMap.begin() + "'!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000546
547 // If there is a code init for this fragment, emit the predicate code and
548 // keep track of the fact that this fragment uses it.
549 CodeInit *CI =
550 dynamic_cast<CodeInit*>(Fragments[i]->getValueInit("Predicate"));
551 if (!CI->getValue().empty()) {
Chris Lattner37937092005-09-09 01:15:01 +0000552 assert(!P->getOnlyTree()->isLeaf() && "Can't be a leaf!");
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000553 std::string ClassName =
Chris Lattner37937092005-09-09 01:15:01 +0000554 getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000555 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
556
557 OS << "static inline bool Predicate_" << Fragments[i]->getName()
558 << "(SDNode *" << C2 << ") {\n";
559 if (ClassName != "SDNode")
560 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
561 OS << CI->getValue() << "\n}\n";
Chris Lattner37937092005-09-09 01:15:01 +0000562 P->getOnlyTree()->setPredicateFn("Predicate_"+Fragments[i]->getName());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000563 }
564 }
565
566 OS << "\n\n";
567
568 // Now that we've parsed all of the tree fragments, do a closure on them so
569 // that there are not references to PatFrags left inside of them.
570 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
571 E = PatternFragments.end(); I != E; ++I) {
Chris Lattner32707602005-09-08 23:22:48 +0000572 TreePattern *ThePat = I->second;
573 ThePat->InlinePatternFragments();
Chris Lattneree9f0c32005-09-13 21:20:49 +0000574
Chris Lattner32707602005-09-08 23:22:48 +0000575 // Infer as many types as possible. Don't worry about it if we don't infer
576 // all of them, some may depend on the inputs of the pattern.
577 try {
578 ThePat->InferAllTypes();
579 } catch (...) {
580 // If this pattern fragment is not supported by this target (no types can
581 // satisfy its constraints), just ignore it. If the bogus pattern is
582 // actually used by instructions, the type consistency error will be
583 // reported there.
584 }
585
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000586 // If debugging, print out the pattern fragment result.
Chris Lattner32707602005-09-08 23:22:48 +0000587 DEBUG(ThePat->dump());
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000588 }
589}
590
591/// ParseAndResolveInstructions - Parse all of the instructions, inlining and
592/// resolving any fragments involved. This populates the Instructions list with
593/// fully resolved instructions.
594void DAGISelEmitter::ParseAndResolveInstructions() {
595 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
596
597 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
598 if (!dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
599 continue; // no pattern yet, ignore it.
600
601 ListInit *LI = Instrs[i]->getValueAsListInit("Pattern");
602 if (LI->getSize() == 0) continue; // no pattern.
603
604 std::vector<DagInit*> Trees;
605 for (unsigned j = 0, e = LI->getSize(); j != e; ++j)
606 Trees.push_back((DagInit*)LI->getElement(j));
607
608 // Parse the instruction.
Chris Lattneree9f0c32005-09-13 21:20:49 +0000609 TreePattern *I = new TreePattern(Instrs[i], Trees, *this);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000610 // Inline pattern fragments into it.
Chris Lattner32707602005-09-08 23:22:48 +0000611 I->InlinePatternFragments();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000612
Chris Lattner95f6b762005-09-08 23:26:30 +0000613 // Infer as many types as possible. If we cannot infer all of them, we can
614 // never do anything with this instruction pattern: report it to the user.
Chris Lattner32707602005-09-08 23:22:48 +0000615 if (!I->InferAllTypes()) {
616 I->dump();
617 I->error("Could not infer all types in pattern!");
618 }
Chris Lattnerf2a17a72005-09-09 01:11:44 +0000619
620 // Verify that the top-level forms in the instruction are of void type.
621 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j)
622 if (I->getTree(j)->getType() != MVT::isVoid) {
623 I->dump();
624 I->error("Top-level forms in instruction pattern should have"
625 " void types");
626 }
Chris Lattner32707602005-09-08 23:22:48 +0000627
628 DEBUG(I->dump());
Chris Lattner32707602005-09-08 23:22:48 +0000629 Instructions.push_back(I);
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000630 }
631}
632
633void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
634 // Emit boilerplate.
635 OS << "// The main instruction selector code.\n"
636 << "SDOperand " << Target.getName()
637 << "DAGToDAGISel::SelectCode(SDOperand Op) {\n"
638 << " SDNode *N = Op.Val;\n"
639 << " if (N->getOpcode() >= ISD::BUILTIN_OP_END &&\n"
640 << " N->getOpcode() < PPCISD::FIRST_NUMBER)\n"
641 << " return Op; // Already selected.\n\n"
642 << " switch (N->getOpcode()) {\n"
643 << " default: break;\n"
644 << " case ISD::EntryToken: // These leaves remain the same.\n"
645 << " return Op;\n"
646 << " case ISD::AssertSext:\n"
647 << " case ISD::AssertZext:\n"
648 << " return Select(N->getOperand(0));\n";
649
650
651
652 OS << " } // end of big switch.\n\n"
653 << " std::cerr << \"Cannot yet select: \";\n"
654 << " N->dump();\n"
655 << " std::cerr << '\\n';\n"
656 << " abort();\n"
657 << "}\n";
658}
659
660
661void DAGISelEmitter::run(std::ostream &OS) {
662 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
663 " target", OS);
664
Chris Lattnerca559d02005-09-08 21:03:01 +0000665 ParseNodeInfo();
Chris Lattner54cb8fd2005-09-07 23:44:43 +0000666 ParseAndResolvePatternFragments(OS);
667 ParseAndResolveInstructions();
668
669 // TODO: convert some instructions to expanders if needed or something.
670
671 EmitInstructionSelector(OS);
672
673 for (std::map<Record*, TreePattern*>::iterator I = PatternFragments.begin(),
674 E = PatternFragments.end(); I != E; ++I)
675 delete I->second;
676 PatternFragments.clear();
677
678 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
679 delete Instructions[i];
680 Instructions.clear();
681}