blob: e9c63441aeae06c323f193ac5121fcf494b8e53f [file] [log] [blame]
Chris Lattnerf5bd1b72003-10-05 19:27:59 +00001//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
John Criswelld3032032003-10-20 20:20:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerf5bd1b72003-10-05 19:27:59 +00009//
10// This tablegen backend is responsible for emitting a description of the target
11// instruction set for the code generator.
12//
13//===----------------------------------------------------------------------===//
14
15#include "InstrSelectorEmitter.h"
Chris Lattnerf5bd1b72003-10-05 19:27:59 +000016#include "Record.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000017#include "llvm/Support/Debug.h"
18#include "llvm/ADT/StringExtras.h"
Chris Lattnerf5bd1b72003-10-05 19:27:59 +000019#include <set>
Chris Lattner68478662004-08-01 03:55:39 +000020using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000021
Chris Lattnerf5bd1b72003-10-05 19:27:59 +000022NodeType::ArgResultTypes NodeType::Translate(Record *R) {
23 const std::string &Name = R->getName();
24 if (Name == "DNVT_any") return Any;
25 if (Name == "DNVT_void") return Void;
26 if (Name == "DNVT_val" ) return Val;
27 if (Name == "DNVT_arg0") return Arg0;
28 if (Name == "DNVT_arg1") return Arg1;
29 if (Name == "DNVT_ptr" ) return Ptr;
30 if (Name == "DNVT_i8" ) return I8;
31 throw "Unknown DagNodeValType '" + Name + "'!";
32}
33
34
35//===----------------------------------------------------------------------===//
36// TreePatternNode implementation
37//
38
39/// getValueRecord - Returns the value of this tree node as a record. For now
40/// we only allow DefInit's as our leaf values, so this is used.
41Record *TreePatternNode::getValueRecord() const {
42 DefInit *DI = dynamic_cast<DefInit*>(getValue());
43 assert(DI && "Instruction Selector does not yet support non-def leaves!");
44 return DI->getDef();
45}
46
47
48// updateNodeType - Set the node type of N to VT if VT contains information. If
49// N already contains a conflicting type, then throw an exception
50//
51bool TreePatternNode::updateNodeType(MVT::ValueType VT,
52 const std::string &RecName) {
53 if (VT == MVT::Other || getType() == VT) return false;
54 if (getType() == MVT::Other) {
55 setType(VT);
56 return true;
57 }
58
Chris Lattner95c13c92003-12-11 00:58:34 +000059 throw "Type inference contradiction found for pattern " + RecName;
Chris Lattnerf5bd1b72003-10-05 19:27:59 +000060}
61
62/// InstantiateNonterminals - If this pattern refers to any nonterminals which
63/// are not themselves completely resolved, clone the nonterminal and resolve it
64/// with the using context we provide.
65///
66void TreePatternNode::InstantiateNonterminals(InstrSelectorEmitter &ISE) {
67 if (!isLeaf()) {
68 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
69 getChild(i)->InstantiateNonterminals(ISE);
70 return;
71 }
72
73 // If this is a leaf, it might be a reference to a nonterminal! Check now.
74 Record *R = getValueRecord();
75 if (R->isSubClassOf("Nonterminal")) {
76 Pattern *NT = ISE.getPattern(R);
77 if (!NT->isResolved()) {
78 // We found an unresolved nonterminal reference. Ask the ISE to clone
79 // it for us, then update our reference to the fresh, new, resolved,
80 // nonterminal.
81
82 Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
83 }
84 }
85}
86
87
88/// clone - Make a copy of this tree and all of its children.
89///
90TreePatternNode *TreePatternNode::clone() const {
91 TreePatternNode *New;
92 if (isLeaf()) {
93 New = new TreePatternNode(Value);
94 } else {
95 std::vector<std::pair<TreePatternNode*, std::string> > CChildren;
96 CChildren.reserve(Children.size());
97 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
98 CChildren.push_back(std::make_pair(getChild(i)->clone(),getChildName(i)));
99 New = new TreePatternNode(Operator, CChildren);
100 }
101 New->setType(Type);
102 return New;
103}
104
Chris Lattner68478662004-08-01 03:55:39 +0000105std::ostream &llvm::operator<<(std::ostream &OS, const TreePatternNode &N) {
Chris Lattnerf5bd1b72003-10-05 19:27:59 +0000106 if (N.isLeaf())
107 return OS << N.getType() << ":" << *N.getValue();
108 OS << "(" << N.getType() << ":";
109 OS << N.getOperator()->getName();
110
111 if (N.getNumChildren() != 0) {
112 OS << " " << *N.getChild(0);
113 for (unsigned i = 1, e = N.getNumChildren(); i != e; ++i)
114 OS << ", " << *N.getChild(i);
115 }
116 return OS << ")";
117}
118
119void TreePatternNode::dump() const { std::cerr << *this; }
120
121//===----------------------------------------------------------------------===//
122// Pattern implementation
123//
124
125// Parse the specified DagInit into a TreePattern which we can use.
126//
127Pattern::Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
128 InstrSelectorEmitter &ise)
129 : PTy(pty), ResultNode(0), TheRecord(TheRec), ISE(ise) {
130
131 // First, parse the pattern...
132 Tree = ParseTreePattern(RawPat);
133
134 // Run the type-inference engine...
135 InferAllTypes();
136
137 if (PTy == Instruction || PTy == Expander) {
138 // Check to make sure there is not any unset types in the tree pattern...
139 if (!isResolved()) {
140 std::cerr << "In pattern: " << *Tree << "\n";
141 error("Could not infer all types!");
142 }
143
144 // Check to see if we have a top-level (set) of a register.
145 if (Tree->getOperator()->getName() == "set") {
146 assert(Tree->getNumChildren() == 2 && "Set with != 2 arguments?");
147 if (!Tree->getChild(0)->isLeaf())
148 error("Arg #0 of set should be a register or register class!");
149 ResultNode = Tree->getChild(0);
150 ResultName = Tree->getChildName(0);
151 Tree = Tree->getChild(1);
152 }
153 }
154
155 calculateArgs(Tree, "");
156}
157
158void Pattern::error(const std::string &Msg) const {
159 std::string M = "In ";
160 switch (PTy) {
161 case Nonterminal: M += "nonterminal "; break;
162 case Instruction: M += "instruction "; break;
163 case Expander : M += "expander "; break;
164 }
165 throw M + TheRecord->getName() + ": " + Msg;
166}
167
168/// calculateArgs - Compute the list of all of the arguments to this pattern,
169/// which are the non-void leaf nodes in this pattern.
170///
171void Pattern::calculateArgs(TreePatternNode *N, const std::string &Name) {
172 if (N->isLeaf() || N->getNumChildren() == 0) {
173 if (N->getType() != MVT::isVoid)
174 Args.push_back(std::make_pair(N, Name));
175 } else {
176 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
177 calculateArgs(N->getChild(i), N->getChildName(i));
178 }
179}
180
181/// getIntrinsicType - Check to see if the specified record has an intrinsic
182/// type which should be applied to it. This infer the type of register
183/// references from the register file information, for example.
184///
185MVT::ValueType Pattern::getIntrinsicType(Record *R) const {
186 // Check to see if this is a register or a register class...
187 if (R->isSubClassOf("RegisterClass"))
188 return getValueType(R->getValueAsDef("RegType"));
189 else if (R->isSubClassOf("Nonterminal"))
190 return ISE.ReadNonterminal(R)->getTree()->getType();
191 else if (R->isSubClassOf("Register")) {
192 std::cerr << "WARNING: Explicit registers not handled yet!\n";
193 return MVT::Other;
194 }
195
196 error("Unknown value used: " + R->getName());
197 return MVT::Other;
198}
199
200TreePatternNode *Pattern::ParseTreePattern(DagInit *Dag) {
201 Record *Operator = Dag->getNodeType();
202
203 if (Operator->isSubClassOf("ValueType")) {
204 // If the operator is a ValueType, then this must be "type cast" of a leaf
205 // node.
206 if (Dag->getNumArgs() != 1)
207 error("Type cast only valid for a leaf node!");
208
209 Init *Arg = Dag->getArg(0);
210 TreePatternNode *New;
211 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
212 New = new TreePatternNode(DI);
213 // If it's a regclass or something else known, set the type.
214 New->setType(getIntrinsicType(DI->getDef()));
215 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
216 New = ParseTreePattern(DI);
217 } else {
218 Arg->dump();
219 error("Unknown leaf value for tree pattern!");
220 return 0;
221 }
222
223 // Apply the type cast...
224 New->updateNodeType(getValueType(Operator), TheRecord->getName());
225 return New;
226 }
227
228 if (!ISE.getNodeTypes().count(Operator))
229 error("Unrecognized node '" + Operator->getName() + "'!");
230
231 std::vector<std::pair<TreePatternNode*, std::string> > Children;
232
233 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
234 Init *Arg = Dag->getArg(i);
235 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
236 Children.push_back(std::make_pair(ParseTreePattern(DI),
237 Dag->getArgName(i)));
238 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
239 Record *R = DefI->getDef();
240 // Direct reference to a leaf DagNode? Turn it into a DagNode if its own.
241 if (R->isSubClassOf("DagNode")) {
242 Dag->setArg(i, new DagInit(R,
243 std::vector<std::pair<Init*, std::string> >()));
244 --i; // Revisit this node...
245 } else {
246 Children.push_back(std::make_pair(new TreePatternNode(DefI),
247 Dag->getArgName(i)));
248 // If it's a regclass or something else known, set the type.
249 Children.back().first->setType(getIntrinsicType(R));
250 }
251 } else {
252 Arg->dump();
253 error("Unknown leaf value for tree pattern!");
254 }
255 }
256
257 return new TreePatternNode(Operator, Children);
258}
259
260void Pattern::InferAllTypes() {
261 bool MadeChange, AnyUnset;
262 do {
263 MadeChange = false;
264 AnyUnset = InferTypes(Tree, MadeChange);
265 } while ((AnyUnset || MadeChange) && !(AnyUnset && !MadeChange));
266 Resolved = !AnyUnset;
267}
268
269
270// InferTypes - Perform type inference on the tree, returning true if there
271// are any remaining untyped nodes and setting MadeChange if any changes were
272// made.
273bool Pattern::InferTypes(TreePatternNode *N, bool &MadeChange) {
274 if (N->isLeaf()) return N->getType() == MVT::Other;
275
276 bool AnyUnset = false;
277 Record *Operator = N->getOperator();
278 const NodeType &NT = ISE.getNodeType(Operator);
279
280 // Check to see if we can infer anything about the argument types from the
281 // return types...
282 if (N->getNumChildren() != NT.ArgTypes.size())
283 error("Incorrect number of children for " + Operator->getName() + " node!");
284
285 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
286 TreePatternNode *Child = N->getChild(i);
287 AnyUnset |= InferTypes(Child, MadeChange);
288
289 switch (NT.ArgTypes[i]) {
290 case NodeType::Any: break;
291 case NodeType::I8:
292 MadeChange |= Child->updateNodeType(MVT::i1, TheRecord->getName());
293 break;
294 case NodeType::Arg0:
295 MadeChange |= Child->updateNodeType(N->getChild(0)->getType(),
296 TheRecord->getName());
297 break;
298 case NodeType::Arg1:
299 MadeChange |= Child->updateNodeType(N->getChild(1)->getType(),
300 TheRecord->getName());
301 break;
302 case NodeType::Val:
303 if (Child->getType() == MVT::isVoid)
304 error("Inferred a void node in an illegal place!");
305 break;
306 case NodeType::Ptr:
307 MadeChange |= Child->updateNodeType(ISE.getTarget().getPointerType(),
308 TheRecord->getName());
309 break;
310 case NodeType::Void:
311 MadeChange |= Child->updateNodeType(MVT::isVoid, TheRecord->getName());
312 break;
313 default: assert(0 && "Invalid argument ArgType!");
314 }
315 }
316
317 // See if we can infer anything about the return type now...
318 switch (NT.ResultType) {
319 case NodeType::Any: break;
320 case NodeType::Void:
321 MadeChange |= N->updateNodeType(MVT::isVoid, TheRecord->getName());
322 break;
323 case NodeType::I8:
324 MadeChange |= N->updateNodeType(MVT::i1, TheRecord->getName());
325 break;
326 case NodeType::Arg0:
327 MadeChange |= N->updateNodeType(N->getChild(0)->getType(),
328 TheRecord->getName());
329 break;
330 case NodeType::Arg1:
331 MadeChange |= N->updateNodeType(N->getChild(1)->getType(),
332 TheRecord->getName());
333 break;
334 case NodeType::Ptr:
335 MadeChange |= N->updateNodeType(ISE.getTarget().getPointerType(),
336 TheRecord->getName());
337 break;
338 case NodeType::Val:
339 if (N->getType() == MVT::isVoid)
340 error("Inferred a void node in an illegal place!");
341 break;
342 default:
343 assert(0 && "Unhandled type constraint!");
344 break;
345 }
346
Chris Lattner429aaa52004-11-05 04:50:59 +0000347 return AnyUnset | (N->getType() == MVT::Other);
Chris Lattnerf5bd1b72003-10-05 19:27:59 +0000348}
349
350/// clone - This method is used to make an exact copy of the current pattern,
351/// then change the "TheRecord" instance variable to the specified record.
352///
353Pattern *Pattern::clone(Record *R) const {
354 assert(PTy == Nonterminal && "Can only clone nonterminals");
355 return new Pattern(Tree->clone(), R, Resolved, ISE);
356}
357
358
359
Chris Lattner68478662004-08-01 03:55:39 +0000360std::ostream &llvm::operator<<(std::ostream &OS, const Pattern &P) {
Chris Lattnerf5bd1b72003-10-05 19:27:59 +0000361 switch (P.getPatternType()) {
362 case Pattern::Nonterminal: OS << "Nonterminal pattern "; break;
363 case Pattern::Instruction: OS << "Instruction pattern "; break;
364 case Pattern::Expander: OS << "Expander pattern "; break;
365 }
366
367 OS << P.getRecord()->getName() << ":\t";
368
369 if (Record *Result = P.getResult())
370 OS << Result->getName() << " = ";
371 OS << *P.getTree();
372
373 if (!P.isResolved())
374 OS << " [not completely resolved]";
375 return OS;
376}
377
378void Pattern::dump() const { std::cerr << *this; }
379
380
381
382/// getSlotName - If this is a leaf node, return the slot name that the operand
383/// will update.
384std::string Pattern::getSlotName() const {
385 if (getPatternType() == Pattern::Nonterminal) {
386 // Just use the nonterminal name, which will already include the type if
387 // it has been cloned.
388 return getRecord()->getName();
389 } else {
390 std::string SlotName;
391 if (getResult())
392 SlotName = getResult()->getName()+"_";
393 else
394 SlotName = "Void_";
395 return SlotName + getName(getTree()->getType());
396 }
397}
398
399/// getSlotName - If this is a leaf node, return the slot name that the
400/// operand will update.
401std::string Pattern::getSlotName(Record *R) {
402 if (R->isSubClassOf("Nonterminal")) {
403 // Just use the nonterminal name, which will already include the type if
404 // it has been cloned.
405 return R->getName();
406 } else if (R->isSubClassOf("RegisterClass")) {
407 MVT::ValueType Ty = getValueType(R->getValueAsDef("RegType"));
408 return R->getName() + "_" + getName(Ty);
409 } else {
410 assert(0 && "Don't know how to get a slot name for this!");
411 }
412 return "";
413}
414
415//===----------------------------------------------------------------------===//
416// PatternOrganizer implementation
417//
418
419/// addPattern - Add the specified pattern to the appropriate location in the
420/// collection.
421void PatternOrganizer::addPattern(Pattern *P) {
422 NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
423 if (!P->getTree()->isLeaf())
424 Nodes[P->getTree()->getOperator()].push_back(P);
425 else {
426 // Right now we only support DefInit's with node types...
427 Nodes[P->getTree()->getValueRecord()].push_back(P);
428 }
429}
430
431
432
433//===----------------------------------------------------------------------===//
434// InstrSelectorEmitter implementation
435//
436
437/// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
438/// turning them into the more accessible NodeTypes data structure.
439///
440void InstrSelectorEmitter::ReadNodeTypes() {
441 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
442 DEBUG(std::cerr << "Getting node types: ");
443 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
444 Record *Node = Nodes[i];
445
446 // Translate the return type...
447 NodeType::ArgResultTypes RetTy =
448 NodeType::Translate(Node->getValueAsDef("RetType"));
449
450 // Translate the arguments...
451 ListInit *Args = Node->getValueAsListInit("ArgTypes");
452 std::vector<NodeType::ArgResultTypes> ArgTypes;
453
454 for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
455 if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
456 ArgTypes.push_back(NodeType::Translate(DI->getDef()));
457 else
458 throw "In node " + Node->getName() + ", argument is not a Def!";
459
460 if (a == 0 && ArgTypes.back() == NodeType::Arg0)
461 throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
462 if (a == 1 && ArgTypes.back() == NodeType::Arg1)
463 throw "In node " + Node->getName() + ", arg 1 cannot have type 'arg1'!";
464 }
465 if ((RetTy == NodeType::Arg0 && Args->getSize() == 0) ||
466 (RetTy == NodeType::Arg1 && Args->getSize() < 2))
467 throw "In node " + Node->getName() +
468 ", invalid return type for node with this many operands!";
469
470 // Add the node type mapping now...
471 NodeTypes[Node] = NodeType(RetTy, ArgTypes);
472 DEBUG(std::cerr << Node->getName() << ", ");
473 }
474 DEBUG(std::cerr << "DONE!\n");
475}
476
477Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
478 Pattern *&P = Patterns[R];
479 if (P) return P; // Don't reread it!
480
481 DagInit *DI = R->getValueAsDag("Pattern");
482 P = new Pattern(Pattern::Nonterminal, DI, R, *this);
483 DEBUG(std::cerr << "Parsed " << *P << "\n");
484 return P;
485}
486
487
488// ReadNonTerminals - Read in all nonterminals and incorporate them into our
489// pattern database.
490void InstrSelectorEmitter::ReadNonterminals() {
491 std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
492 for (unsigned i = 0, e = NTs.size(); i != e; ++i)
493 ReadNonterminal(NTs[i]);
494}
495
496
497/// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
498/// those with a useful Pattern field.
499///
500void InstrSelectorEmitter::ReadInstructionPatterns() {
501 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
502 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
503 Record *Inst = Insts[i];
504 if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
505 Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
506 DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
507 }
508 }
509}
510
511/// ReadExpanderPatterns - Read in all expander patterns...
512///
513void InstrSelectorEmitter::ReadExpanderPatterns() {
514 std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
515 for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
516 Record *Expander = Expanders[i];
517 DagInit *DI = Expander->getValueAsDag("Pattern");
518 Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
519 DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
520 }
521}
522
523
524// InstantiateNonterminals - Instantiate any unresolved nonterminals with
525// information from the context that they are used in.
526//
527void InstrSelectorEmitter::InstantiateNonterminals() {
528 DEBUG(std::cerr << "Instantiating nonterminals:\n");
529 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
530 E = Patterns.end(); I != E; ++I)
531 if (I->second->isResolved())
532 I->second->InstantiateNonterminals();
533}
534
535/// InstantiateNonterminal - This method takes the nonterminal specified by
536/// NT, which should not be completely resolved, clones it, applies ResultTy
537/// to its root, then runs the type inference stuff on it. This should
538/// produce a newly resolved nonterminal, which we make a record for and
539/// return. To be extra fancy and efficient, this only makes one clone for
540/// each type it is instantiated with.
541Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
542 MVT::ValueType ResultTy) {
543 assert(!NT->isResolved() && "Nonterminal is already resolved!");
544
545 // Check to see if we have already instantiated this pair...
546 Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
547 if (Slot) return Slot;
548
549 Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
550
551 // Copy over the superclasses...
552 const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
553 for (unsigned i = 0, e = SCs.size(); i != e; ++i)
554 New->addSuperClass(SCs[i]);
555
556 DEBUG(std::cerr << " Nonterminal '" << NT->getRecord()->getName()
557 << "' for type '" << getName(ResultTy) << "', producing '"
558 << New->getName() << "'\n");
559
560 // Copy the pattern...
561 Pattern *NewPat = NT->clone(New);
562
563 // Apply the type to the root...
564 NewPat->getTree()->updateNodeType(ResultTy, New->getName());
565
566 // Infer types...
567 NewPat->InferAllTypes();
568
569 // Make sure everything is good to go now...
570 if (!NewPat->isResolved())
571 NewPat->error("Instantiating nonterminal did not resolve all types!");
572
573 // Add the pattern to the patterns map, add the record to the RecordKeeper,
574 // return the new record.
575 Patterns[New] = NewPat;
576 Records.addDef(New);
577 return Slot = New;
578}
579
580// CalculateComputableValues - Fill in the ComputableValues map through
581// analysis of the patterns we are playing with.
582void InstrSelectorEmitter::CalculateComputableValues() {
583 // Loop over all of the patterns, adding them to the ComputableValues map
584 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
585 E = Patterns.end(); I != E; ++I)
586 if (I->second->isResolved()) {
587 // We don't want to add patterns like R32 = R32. This is a hack working
588 // around a special case of a general problem, but for now we explicitly
589 // forbid these patterns. They can never match anyway.
590 Pattern *P = I->second;
591 if (!P->getResult() || !P->getTree()->isLeaf() ||
592 P->getResult() != P->getTree()->getValueRecord())
593 ComputableValues.addPattern(P);
594 }
595}
596
597#if 0
598// MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
599// patterns which have the same top-level structure as P from the 'From' list to
600// the 'To' list.
601static void MoveIdenticalPatterns(TreePatternNode *P,
602 std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
603 std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
604 assert(!P->isLeaf() && "All leaves are identical!");
605
606 const std::vector<TreePatternNode*> &PChildren = P->getChildren();
607 for (unsigned i = 0; i != From.size(); ++i) {
608 TreePatternNode *N = From[i].second;
609 assert(P->getOperator() == N->getOperator() &&"Differing operators?");
610 assert(PChildren.size() == N->getChildren().size() &&
611 "Nodes with different arity??");
612 bool isDifferent = false;
613 for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
614 TreePatternNode *PC = PChildren[c];
615 TreePatternNode *NC = N->getChild(c);
616 if (PC->isLeaf() != NC->isLeaf()) {
617 isDifferent = true;
618 break;
619 }
620
621 if (!PC->isLeaf()) {
622 if (PC->getOperator() != NC->getOperator()) {
623 isDifferent = true;
624 break;
625 }
626 } else { // It's a leaf!
627 if (PC->getValueRecord() != NC->getValueRecord()) {
628 isDifferent = true;
629 break;
630 }
631 }
632 }
633 // If it's the same as the reference one, move it over now...
634 if (!isDifferent) {
635 To.push_back(std::make_pair(From[i].first, N));
636 From.erase(From.begin()+i);
637 --i; // Don't skip an entry...
638 }
639 }
640}
641#endif
642
643static std::string getNodeName(Record *R) {
644 RecordVal *RV = R->getValue("EnumName");
645 if (RV)
646 if (Init *I = RV->getValue())
647 if (StringInit *SI = dynamic_cast<StringInit*>(I))
648 return SI->getValue();
649 return R->getName();
650}
651
652
653static void EmitPatternPredicates(TreePatternNode *Tree,
654 const std::string &VarName, std::ostream &OS){
655 OS << " && " << VarName << "->getNodeType() == ISD::"
656 << getNodeName(Tree->getOperator());
657
658 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
659 if (!Tree->getChild(c)->isLeaf())
660 EmitPatternPredicates(Tree->getChild(c),
661 VarName + "->getUse(" + utostr(c)+")", OS);
662}
663
664static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
665 std::ostream &OS) {
666 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
667 if (Tree->getChild(c)->isLeaf()) {
668 OS << " + Match_"
669 << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
670 << VarName << "->getUse(" << c << "))";
671 } else {
672 EmitPatternCosts(Tree->getChild(c),
673 VarName + "->getUse(" + utostr(c) + ")", OS);
674 }
675}
676
677
678// EmitMatchCosters - Given a list of patterns, which all have the same root
679// pattern operator, emit an efficient decision tree to decide which one to
680// pick. This is structured this way to avoid reevaluations of non-obvious
681// subexpressions.
682void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
683 const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
684 const std::string &VarPrefix,
685 unsigned IndentAmt) {
686 assert(!Patterns.empty() && "No patterns to emit matchers for!");
687 std::string Indent(IndentAmt, ' ');
688
689 // Load all of the operands of the root node into scalars for fast access
690 const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
691 for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
692 OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
693 << " = N->getUse(" << i << ");\n";
694
695 // Compute the costs of computing the various nonterminals/registers, which
696 // are directly used at this level.
697 OS << "\n" << Indent << "// Operand matching costs...\n";
698 std::set<std::string> ComputedValues; // Avoid duplicate computations...
699 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
700 TreePatternNode *NParent = Patterns[i].second;
701 for (unsigned c = 0, e = NParent->getNumChildren(); c != e; ++c) {
702 TreePatternNode *N = NParent->getChild(c);
703 if (N->isLeaf()) {
704 Record *VR = N->getValueRecord();
705 const std::string &LeafName = VR->getName();
706 std::string OpName = VarPrefix + "_Op" + utostr(c);
707 std::string ValName = OpName + "_" + LeafName + "_Cost";
708 if (!ComputedValues.count(ValName)) {
709 OS << Indent << "unsigned " << ValName << " = Match_"
710 << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
711 ComputedValues.insert(ValName);
712 }
713 }
714 }
715 }
716 OS << "\n";
717
718
719 std::string LocCostName = VarPrefix + "_Cost";
720 OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
721 << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
722
723#if 0
724 // Separate out all of the patterns into groups based on what their top-level
725 // signature looks like...
726 std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
727 while (!PatternsLeft.empty()) {
728 // Process all of the patterns that have the same signature as the last
729 // element...
730 std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
731 MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
732 assert(!Group.empty() && "Didn't at least pick the source pattern?");
733
734#if 0
735 OS << "PROCESSING GROUP:\n";
736 for (unsigned i = 0, e = Group.size(); i != e; ++i)
737 OS << " " << *Group[i].first << "\n";
738 OS << "\n\n";
739#endif
740
741 OS << Indent << "{ // ";
742
743 if (Group.size() != 1) {
744 OS << Group.size() << " size group...\n";
745 OS << Indent << " unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
746 } else {
747 OS << *Group[0].first << "\n";
748 OS << Indent << " unsigned " << VarPrefix << "_Pattern = "
749 << Group[0].first->getRecord()->getName() << "_Pattern;\n";
750 }
751
752 OS << Indent << " unsigned " << LocCostName << " = ";
753 if (Group.size() == 1)
754 OS << "1;\n"; // Add inst cost if at individual rec
755 else
756 OS << "0;\n";
757
758 // Loop over all of the operands, adding in their costs...
759 TreePatternNode *N = Group[0].second;
760 const std::vector<TreePatternNode*> &Children = N->getChildren();
761
762 // If necessary, emit conditionals to check for the appropriate tree
763 // structure here...
764 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
765 TreePatternNode *C = Children[i];
766 if (C->isLeaf()) {
767 // We already calculated the cost for this leaf, add it in now...
768 OS << Indent << " " << LocCostName << " += "
769 << VarPrefix << "_Op" << utostr(i) << "_"
770 << C->getValueRecord()->getName() << "_Cost;\n";
771 } else {
772 // If it's not a leaf, we have to check to make sure that the current
773 // node has the appropriate structure, then recurse into it...
774 OS << Indent << " if (" << VarPrefix << "_Op" << i
775 << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
776 << ") {\n";
777 std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
778 for (unsigned n = 0, e = Group.size(); n != e; ++n)
779 SubPatterns.push_back(std::make_pair(Group[n].first,
780 Group[n].second->getChild(i)));
781 EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
782 IndentAmt + 4);
783 OS << Indent << " }\n";
784 }
785 }
786
787 // If the cost for this match is less than the minimum computed cost so far,
788 // update the minimum cost and selected pattern.
789 OS << Indent << " if (" << LocCostName << " < " << LocCostName << "Min) { "
790 << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
791 << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
792
793 OS << Indent << "}\n";
794 }
795#endif
796
797 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
798 Pattern *P = Patterns[i].first;
799 TreePatternNode *PTree = P->getTree();
800 unsigned PatternCost = 1;
801
802 // Check to see if there are any non-leaf elements in the pattern. If so,
803 // we need to emit a predicate for this match.
804 bool AnyNonLeaf = false;
805 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
806 if (!PTree->getChild(c)->isLeaf()) {
807 AnyNonLeaf = true;
808 break;
809 }
810
811 if (!AnyNonLeaf) { // No predicate necessary, just output a scope...
812 OS << " {// " << *P << "\n";
813 } else {
814 // We need to emit a predicate to make sure the tree pattern matches, do
815 // so now...
816 OS << " if (1";
817 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
818 if (!PTree->getChild(c)->isLeaf())
819 EmitPatternPredicates(PTree->getChild(c),
820 VarPrefix + "_Op" + utostr(c), OS);
821
822 OS << ") {\n // " << *P << "\n";
823 }
824
825 OS << " unsigned PatCost = " << PatternCost;
826
827 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
828 if (PTree->getChild(c)->isLeaf()) {
829 OS << " + " << VarPrefix << "_Op" << c << "_"
830 << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
831 } else {
832 EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
833 }
834 OS << ";\n";
835 OS << " if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
836 << P->getRecord()->getName() << "_Pattern; }\n"
837 << " }\n";
838 }
839}
840
841static void ReduceAllOperands(TreePatternNode *N, const std::string &Name,
842 std::vector<std::pair<TreePatternNode*, std::string> > &Operands,
843 std::ostream &OS) {
844 if (N->isLeaf()) {
845 // If this is a leaf, register or nonterminal reference...
846 std::string SlotName = Pattern::getSlotName(N->getValueRecord());
847 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = Reduce_"
848 << SlotName << "(" << Name << ", MBB);\n";
849 Operands.push_back(std::make_pair(N, Name+"Val"));
850 } else if (N->getNumChildren() == 0) {
851 // This is a reference to a leaf tree node, like an immediate or frame
852 // index.
853 if (N->getType() != MVT::isVoid) {
854 std::string SlotName =
855 getNodeName(N->getOperator()) + "_" + getName(N->getType());
856 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = "
857 << Name << "->getValue<ReducedValue_" << SlotName << ">(ISD::"
858 << SlotName << "_Slot);\n";
859 Operands.push_back(std::make_pair(N, Name+"Val"));
860 }
861 } else {
862 // Otherwise this is an interior node...
863 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
864 std::string ChildName = Name + "_Op" + utostr(i);
865 OS << " SelectionDAGNode *" << ChildName << " = " << Name
866 << "->getUse(" << i << ");\n";
867 ReduceAllOperands(N->getChild(i), ChildName, Operands, OS);
868 }
869 }
870}
871
872/// PrintExpanderOperand - Print out Arg as part of the instruction emission
873/// process for the expander pattern P. This argument may be referencing some
874/// values defined in P, or may just be physical register references or
875/// something like that. If PrintArg is true, we are printing out arguments to
876/// the BuildMI call. If it is false, we are printing the result register
877/// name.
878void InstrSelectorEmitter::PrintExpanderOperand(Init *Arg,
879 const std::string &NameVar,
880 TreePatternNode *ArgDeclNode,
881 Pattern *P, bool PrintArg,
882 std::ostream &OS) {
883 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
884 Record *Arg = DI->getDef();
885 if (!ArgDeclNode->isLeaf() && ArgDeclNode->getNumChildren() != 0)
886 P->error("Expected leaf node as argument!");
887 Record *ArgDecl = ArgDeclNode->isLeaf() ? ArgDeclNode->getValueRecord() :
888 ArgDeclNode->getOperator();
889 if (Arg->isSubClassOf("Register")) {
890 // This is a physical register reference... make sure that the instruction
891 // requested a register!
892 if (!ArgDecl->isSubClassOf("RegisterClass"))
893 P->error("Argument mismatch for instruction pattern!");
894
895 // FIXME: This should check to see if the register is in the specified
896 // register class!
897 if (PrintArg) OS << ".addReg(";
898 OS << getQualifiedName(Arg);
899 if (PrintArg) OS << ")";
900 return;
901 } else if (Arg->isSubClassOf("RegisterClass")) {
902 // If this is a symbolic register class reference, we must be using a
903 // named value.
904 if (NameVar.empty()) P->error("Did not specify WHICH register to pass!");
905 if (Arg != ArgDecl) P->error("Instruction pattern mismatch!");
906
907 if (PrintArg) OS << ".addReg(";
908 OS << NameVar;
909 if (PrintArg) OS << ")";
910 return;
911 } else if (Arg->getName() == "frameidx") {
912 if (!PrintArg) P->error("Cannot define a new frameidx value!");
913 OS << ".addFrameIndex(" << NameVar << ")";
914 return;
915 } else if (Arg->getName() == "basicblock") {
916 if (!PrintArg) P->error("Cannot define a new basicblock value!");
917 OS << ".addMBB(" << NameVar << ")";
918 return;
919 }
920 P->error("Unknown operand type '" + Arg->getName() + "' to expander!");
921 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
922 if (!NameVar.empty())
923 P->error("Illegal to specify a name for a constant initializer arg!");
924
925 // Hack this check to allow R32 values with 0 as the initializer for memory
926 // references... FIXME!
927 if (ArgDeclNode->isLeaf() && II->getValue() == 0 &&
928 ArgDeclNode->getValueRecord()->getName() == "R32") {
929 OS << ".addReg(0)";
930 } else {
931 if (ArgDeclNode->isLeaf() || ArgDeclNode->getOperator()->getName()!="imm")
932 P->error("Illegal immediate int value '" + itostr(II->getValue()) +
933 "' operand!");
934 OS << ".addZImm(" << II->getValue() << ")";
935 }
936 return;
937 }
938 P->error("Unknown operand type to expander!");
939}
940
941static std::string getArgName(Pattern *P, const std::string &ArgName,
942 const std::vector<std::pair<TreePatternNode*, std::string> > &Operands) {
943 assert(P->getNumArgs() == Operands.size() &&"Argument computation mismatch!");
944 if (ArgName.empty()) return "";
945
946 for (unsigned i = 0, e = P->getNumArgs(); i != e; ++i)
947 if (P->getArgName(i) == ArgName)
948 return Operands[i].second + "->Val";
949
950 if (ArgName == P->getResultName())
951 return "NewReg";
952 P->error("Pattern does not define a value named $" + ArgName + "!");
953 return "";
954}
955
956
957void InstrSelectorEmitter::run(std::ostream &OS) {
958 // Type-check all of the node types to ensure we "understand" them.
959 ReadNodeTypes();
960
961 // Read in all of the nonterminals, instructions, and expanders...
962 ReadNonterminals();
963 ReadInstructionPatterns();
964 ReadExpanderPatterns();
965
966 // Instantiate any unresolved nonterminals with information from the context
967 // that they are used in.
968 InstantiateNonterminals();
969
970 // Clear InstantiatedNTs, we don't need it anymore...
971 InstantiatedNTs.clear();
972
973 DEBUG(std::cerr << "Patterns acquired:\n");
974 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
975 E = Patterns.end(); I != E; ++I)
976 if (I->second->isResolved())
977 DEBUG(std::cerr << " " << *I->second << "\n");
978
979 CalculateComputableValues();
980
Brian Gaeke960707c2003-11-11 22:41:34 +0000981 OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
982
Chris Lattnerf5bd1b72003-10-05 19:27:59 +0000983 EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
984 " target", OS);
Chris Lattnerc9d99ef2004-08-17 03:08:28 +0000985 OS << "namespace llvm {\n\n";
Chris Lattnerf5bd1b72003-10-05 19:27:59 +0000986
987 // Output the slot number enums...
988 OS << "\nenum { // Slot numbers...\n"
989 << " LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
990 for (PatternOrganizer::iterator I = ComputableValues.begin(),
991 E = ComputableValues.end(); I != E; ++I)
992 OS << " " << I->first << "_Slot,\n";
993 OS << " NumSlots\n};\n\n// Reduction value typedefs...\n";
994
995 // Output the reduction value typedefs...
996 for (PatternOrganizer::iterator I = ComputableValues.begin(),
997 E = ComputableValues.end(); I != E; ++I) {
998
999 OS << "typedef ReducedValue<unsigned, " << I->first
1000 << "_Slot> ReducedValue_" << I->first << ";\n";
1001 }
1002
1003 // Output the pattern enums...
1004 OS << "\n\n"
1005 << "enum { // Patterns...\n"
1006 << " NotComputed = 0,\n"
1007 << " NoMatchPattern, \n";
1008 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1009 E = ComputableValues.end(); I != E; ++I) {
1010 OS << " // " << I->first << " patterns...\n";
1011 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1012 E = I->second.end(); J != E; ++J)
1013 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1014 OS << " " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
1015 }
1016 OS << "};\n\n";
1017
1018 //===--------------------------------------------------------------------===//
1019 // Emit the class definition...
1020 //
1021 OS << "namespace {\n"
1022 << " class " << Target.getName() << "ISel {\n"
1023 << " SelectionDAG &DAG;\n"
1024 << " public:\n"
Brian Gaeke666aaf72004-01-24 09:23:46 +00001025 << " " << Target.getName () << "ISel(SelectionDAG &D) : DAG(D) {}\n"
Chris Lattnerf5bd1b72003-10-05 19:27:59 +00001026 << " void generateCode();\n"
1027 << " private:\n"
1028 << " unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
1029 << " return DAG.getMachineFunction().getSSARegMap()->createVirt"
1030 "ualRegister(RC);\n"
1031 << " }\n\n"
1032 << " // DAG matching methods for classes... all of these methods"
1033 " return the cost\n"
1034 << " // of producing a value of the specified class and type, which"
1035 " also gets\n"
1036 << " // added to the DAG node.\n";
1037
1038 // Output all of the matching prototypes for slots...
1039 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1040 E = ComputableValues.end(); I != E; ++I)
1041 OS << " unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
1042 OS << "\n // DAG matching methods for DAG nodes...\n";
1043
1044 // Output all of the matching prototypes for slot/node pairs
1045 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1046 E = ComputableValues.end(); I != E; ++I)
1047 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1048 E = I->second.end(); J != E; ++J)
1049 OS << " unsigned Match_" << I->first << "_" << getNodeName(J->first)
1050 << "(SelectionDAGNode *N);\n";
1051
1052 // Output all of the dag reduction methods prototypes...
1053 OS << "\n // DAG reduction methods...\n";
1054 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1055 E = ComputableValues.end(); I != E; ++I)
1056 OS << " ReducedValue_" << I->first << " *Reduce_" << I->first
1057 << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
1058 << "MachineBasicBlock *MBB);\n";
1059 OS << " };\n}\n\n";
1060
1061 // Emit the generateCode entry-point...
Brian Gaeke666aaf72004-01-24 09:23:46 +00001062 OS << "void " << Target.getName () << "ISel::generateCode() {\n"
Chris Lattnerf5bd1b72003-10-05 19:27:59 +00001063 << " SelectionDAGNode *Root = DAG.getRoot();\n"
1064 << " assert(Root->getValueType() == MVT::isVoid && "
1065 "\"Root of DAG produces value??\");\n\n"
1066 << " std::cerr << \"\\n\";\n"
1067 << " unsigned Cost = Match_Void_void(Root);\n"
1068 << " if (Cost >= ~0U >> 1) {\n"
1069 << " std::cerr << \"Match failed!\\n\";\n"
1070 << " Root->dump();\n"
1071 << " abort();\n"
1072 << " }\n\n"
1073 << " std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
1074 << " Reduce_Void_void(Root, 0);\n"
1075 << "}\n\n"
1076 << "//===" << std::string(70, '-') << "===//\n"
1077 << "// Matching methods...\n"
1078 << "//\n\n";
1079
1080 //===--------------------------------------------------------------------===//
1081 // Emit all of the matcher methods...
1082 //
1083 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1084 E = ComputableValues.end(); I != E; ++I) {
1085 const std::string &SlotName = I->first;
1086 OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
1087 << "(SelectionDAGNode *N) {\n"
1088 << " assert(N->getValueType() == MVT::"
1089 << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
1090 << ");\n" << " // If we already have a cost available for " << SlotName
1091 << " use it!\n"
1092 << " if (N->getPatternFor(" << SlotName << "_Slot))\n"
1093 << " return N->getCostFor(" << SlotName << "_Slot);\n\n"
1094 << " unsigned Cost;\n"
1095 << " switch (N->getNodeType()) {\n"
1096 << " default: Cost = ~0U >> 1; // Match failed\n"
1097 << " N->setPatternCostFor(" << SlotName << "_Slot, NoMatchPattern, Cost, NumSlots);\n"
1098 << " break;\n";
1099
1100 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1101 E = I->second.end(); J != E; ++J)
1102 if (!J->first->isSubClassOf("Nonterminal"))
1103 OS << " case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
1104 << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
1105 OS << " }\n"; // End of the switch statement
1106
1107 // Emit any patterns which have a nonterminal leaf as the RHS. These may
1108 // match multiple root nodes, so they cannot be handled with the switch...
1109 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1110 E = I->second.end(); J != E; ++J)
1111 if (J->first->isSubClassOf("Nonterminal")) {
1112 OS << " unsigned " << J->first->getName() << "_Cost = Match_"
1113 << getNodeName(J->first) << "(N);\n"
1114 << " if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
1115 << getNodeName(J->first) << "_Cost;\n";
1116 }
1117
1118 OS << " return Cost;\n}\n\n";
1119
1120 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1121 E = I->second.end(); J != E; ++J) {
1122 Record *Operator = J->first;
1123 bool isNonterm = Operator->isSubClassOf("Nonterminal");
1124 if (!isNonterm) {
1125 OS << "unsigned " << Target.getName() << "ISel::Match_";
1126 if (!isNonterm) OS << SlotName << "_";
1127 OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
1128 << " unsigned Pattern = NoMatchPattern;\n"
1129 << " unsigned MinCost = ~0U >> 1;\n";
1130
1131 std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
1132 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1133 Patterns.push_back(std::make_pair(J->second[i],
1134 J->second[i]->getTree()));
1135 EmitMatchCosters(OS, Patterns, "N", 2);
1136
1137 OS << "\n N->setPatternCostFor(" << SlotName
1138 << "_Slot, Pattern, MinCost, NumSlots);\n"
1139 << " return MinCost;\n"
1140 << "}\n";
1141 }
1142 }
1143 }
1144
1145 //===--------------------------------------------------------------------===//
1146 // Emit all of the reducer methods...
1147 //
1148 OS << "\n\n//===" << std::string(70, '-') << "===//\n"
1149 << "// Reducer methods...\n"
1150 << "//\n";
1151
1152 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1153 E = ComputableValues.end(); I != E; ++I) {
1154 const std::string &SlotName = I->first;
1155 OS << "ReducedValue_" << SlotName << " *" << Target.getName()
1156 << "ISel::Reduce_" << SlotName
1157 << "(SelectionDAGNode *N, MachineBasicBlock *MBB) {\n"
1158 << " ReducedValue_" << SlotName << " *Val = N->hasValue<ReducedValue_"
1159 << SlotName << ">(" << SlotName << "_Slot);\n"
1160 << " if (Val) return Val;\n"
1161 << " if (N->getBB()) MBB = N->getBB();\n\n"
1162 << " switch (N->getPatternFor(" << SlotName << "_Slot)) {\n";
1163
1164 // Loop over all of the patterns that can produce a value for this slot...
1165 PatternOrganizer::NodesForSlot &NodesForSlot = I->second;
1166 for (PatternOrganizer::NodesForSlot::iterator J = NodesForSlot.begin(),
1167 E = NodesForSlot.end(); J != E; ++J)
1168 for (unsigned i = 0, e = J->second.size(); i != e; ++i) {
1169 Pattern *P = J->second[i];
1170 OS << " case " << P->getRecord()->getName() << "_Pattern: {\n"
1171 << " // " << *P << "\n";
1172 // Loop over the operands, reducing them...
1173 std::vector<std::pair<TreePatternNode*, std::string> > Operands;
1174 ReduceAllOperands(P->getTree(), "N", Operands, OS);
1175
1176 // Now that we have reduced all of our operands, and have the values
1177 // that reduction produces, perform the reduction action for this
1178 // pattern.
1179 std::string Result;
1180
1181 // If the pattern produces a register result, generate a new register
1182 // now.
1183 if (Record *R = P->getResult()) {
1184 assert(R->isSubClassOf("RegisterClass") &&
1185 "Only handle register class results so far!");
1186 OS << " unsigned NewReg = makeAnotherReg(" << Target.getName()
1187 << "::" << R->getName() << "RegisterClass);\n";
1188 Result = "NewReg";
1189 DEBUG(OS << " std::cerr << \"%reg\" << NewReg << \" =\t\";\n");
1190 } else {
1191 DEBUG(OS << " std::cerr << \"\t\t\";\n");
1192 Result = "0";
1193 }
1194
1195 // Print out the pattern that matched...
1196 DEBUG(OS << " std::cerr << \" " << P->getRecord()->getName() <<'"');
1197 DEBUG(for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1198 if (Operands[i].first->isLeaf()) {
1199 Record *RV = Operands[i].first->getValueRecord();
1200 assert(RV->isSubClassOf("RegisterClass") &&
1201 "Only handles registers here so far!");
1202 OS << " << \" %reg\" << " << Operands[i].second
1203 << "->Val";
1204 } else {
1205 OS << " << ' ' << " << Operands[i].second
1206 << "->Val";
1207 });
1208 DEBUG(OS << " << \"\\n\";\n");
1209
1210 // Generate the reduction code appropriate to the particular type of
1211 // pattern that this is...
1212 switch (P->getPatternType()) {
1213 case Pattern::Instruction:
1214 // Instruction patterns just emit a single MachineInstr, using BuildMI
1215 OS << " BuildMI(MBB, " << Target.getName() << "::"
1216 << P->getRecord()->getName() << ", " << Operands.size();
1217 if (P->getResult()) OS << ", NewReg";
1218 OS << ")";
1219
1220 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1221 TreePatternNode *Op = Operands[i].first;
1222 if (Op->isLeaf()) {
1223 Record *RV = Op->getValueRecord();
1224 assert(RV->isSubClassOf("RegisterClass") &&
1225 "Only handles registers here so far!");
1226 OS << ".addReg(" << Operands[i].second << "->Val)";
1227 } else if (Op->getOperator()->getName() == "imm") {
1228 OS << ".addZImm(" << Operands[i].second << "->Val)";
1229 } else if (Op->getOperator()->getName() == "basicblock") {
1230 OS << ".addMBB(" << Operands[i].second << "->Val)";
1231 } else {
1232 assert(0 && "Unknown value type!");
1233 }
1234 }
1235 OS << ";\n";
1236 break;
1237 case Pattern::Expander: {
1238 // Expander patterns emit one machine instr for each instruction in
1239 // the list of instructions expanded to.
1240 ListInit *Insts = P->getRecord()->getValueAsListInit("Result");
1241 for (unsigned IN = 0, e = Insts->getSize(); IN != e; ++IN) {
1242 DagInit *DIInst = dynamic_cast<DagInit*>(Insts->getElement(IN));
1243 if (!DIInst) P->error("Result list must contain instructions!");
1244 Record *InstRec = DIInst->getNodeType();
1245 Pattern *InstPat = getPattern(InstRec);
1246 if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
1247 P->error("Instruction list must contain Instruction patterns!");
1248
1249 bool hasResult = InstPat->getResult() != 0;
1250 if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
1251 P->error("Incorrect number of arguments specified for inst '" +
1252 InstPat->getRecord()->getName() + "' in result list!");
1253 }
1254
1255 // Start emission of the instruction...
1256 OS << " BuildMI(MBB, " << Target.getName() << "::"
1257 << InstRec->getName() << ", "
1258 << DIInst->getNumArgs()-hasResult;
1259 // Emit register result if necessary..
1260 if (hasResult) {
1261 std::string ArgNameVal =
1262 getArgName(P, DIInst->getArgName(0), Operands);
1263 PrintExpanderOperand(DIInst->getArg(0), ArgNameVal,
1264 InstPat->getResultNode(), P, false,
1265 OS << ", ");
1266 }
1267 OS << ")";
1268
1269 for (unsigned i = hasResult, e = DIInst->getNumArgs(); i != e; ++i){
1270 std::string ArgNameVal =
1271 getArgName(P, DIInst->getArgName(i), Operands);
1272
1273 PrintExpanderOperand(DIInst->getArg(i), ArgNameVal,
1274 InstPat->getArg(i-hasResult), P, true, OS);
1275 }
1276
1277 OS << ";\n";
1278 }
1279 break;
1280 }
1281 default:
1282 assert(0 && "Reduction of this type of pattern not implemented!");
1283 }
1284
1285 OS << " Val = new ReducedValue_" << SlotName << "(" << Result<<");\n"
1286 << " break;\n"
1287 << " }\n";
1288 }
1289
1290
1291 OS << " default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
1292 << " }\n\n N->addValue(Val); // Do not ever recalculate this\n"
1293 << " return Val;\n}\n\n";
1294 }
Chris Lattnerc9d99ef2004-08-17 03:08:28 +00001295 OS << "} // End llvm namespace \n";
Chris Lattnerf5bd1b72003-10-05 19:27:59 +00001296}