blob: 9988d55684b007398520d9c0a20b24599cb486eb [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"
16#include "CodeGenWrappers.h"
17#include "Record.h"
18#include "Support/Debug.h"
19#include "Support/StringExtras.h"
20#include <set>
21
22NodeType::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
59 throw "Type inferfence contradiction found for pattern " + RecName;
60}
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
105std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N) {
106 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
347 return AnyUnset | N->getType() == MVT::Other;
348}
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
360std::ostream &operator<<(std::ostream &OS, const Pattern &P) {
361 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
981 EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
982 " target", OS);
983 OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
984
985 // Output the slot number enums...
986 OS << "\nenum { // Slot numbers...\n"
987 << " LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
988 for (PatternOrganizer::iterator I = ComputableValues.begin(),
989 E = ComputableValues.end(); I != E; ++I)
990 OS << " " << I->first << "_Slot,\n";
991 OS << " NumSlots\n};\n\n// Reduction value typedefs...\n";
992
993 // Output the reduction value typedefs...
994 for (PatternOrganizer::iterator I = ComputableValues.begin(),
995 E = ComputableValues.end(); I != E; ++I) {
996
997 OS << "typedef ReducedValue<unsigned, " << I->first
998 << "_Slot> ReducedValue_" << I->first << ";\n";
999 }
1000
1001 // Output the pattern enums...
1002 OS << "\n\n"
1003 << "enum { // Patterns...\n"
1004 << " NotComputed = 0,\n"
1005 << " NoMatchPattern, \n";
1006 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1007 E = ComputableValues.end(); I != E; ++I) {
1008 OS << " // " << I->first << " patterns...\n";
1009 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1010 E = I->second.end(); J != E; ++J)
1011 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1012 OS << " " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
1013 }
1014 OS << "};\n\n";
1015
1016 //===--------------------------------------------------------------------===//
1017 // Emit the class definition...
1018 //
1019 OS << "namespace {\n"
1020 << " class " << Target.getName() << "ISel {\n"
1021 << " SelectionDAG &DAG;\n"
1022 << " public:\n"
1023 << " X86ISel(SelectionDAG &D) : DAG(D) {}\n"
1024 << " void generateCode();\n"
1025 << " private:\n"
1026 << " unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
1027 << " return DAG.getMachineFunction().getSSARegMap()->createVirt"
1028 "ualRegister(RC);\n"
1029 << " }\n\n"
1030 << " // DAG matching methods for classes... all of these methods"
1031 " return the cost\n"
1032 << " // of producing a value of the specified class and type, which"
1033 " also gets\n"
1034 << " // added to the DAG node.\n";
1035
1036 // Output all of the matching prototypes for slots...
1037 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1038 E = ComputableValues.end(); I != E; ++I)
1039 OS << " unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
1040 OS << "\n // DAG matching methods for DAG nodes...\n";
1041
1042 // Output all of the matching prototypes for slot/node pairs
1043 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1044 E = ComputableValues.end(); I != E; ++I)
1045 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1046 E = I->second.end(); J != E; ++J)
1047 OS << " unsigned Match_" << I->first << "_" << getNodeName(J->first)
1048 << "(SelectionDAGNode *N);\n";
1049
1050 // Output all of the dag reduction methods prototypes...
1051 OS << "\n // DAG reduction methods...\n";
1052 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1053 E = ComputableValues.end(); I != E; ++I)
1054 OS << " ReducedValue_" << I->first << " *Reduce_" << I->first
1055 << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
1056 << "MachineBasicBlock *MBB);\n";
1057 OS << " };\n}\n\n";
1058
1059 // Emit the generateCode entry-point...
1060 OS << "void X86ISel::generateCode() {\n"
1061 << " SelectionDAGNode *Root = DAG.getRoot();\n"
1062 << " assert(Root->getValueType() == MVT::isVoid && "
1063 "\"Root of DAG produces value??\");\n\n"
1064 << " std::cerr << \"\\n\";\n"
1065 << " unsigned Cost = Match_Void_void(Root);\n"
1066 << " if (Cost >= ~0U >> 1) {\n"
1067 << " std::cerr << \"Match failed!\\n\";\n"
1068 << " Root->dump();\n"
1069 << " abort();\n"
1070 << " }\n\n"
1071 << " std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
1072 << " Reduce_Void_void(Root, 0);\n"
1073 << "}\n\n"
1074 << "//===" << std::string(70, '-') << "===//\n"
1075 << "// Matching methods...\n"
1076 << "//\n\n";
1077
1078 //===--------------------------------------------------------------------===//
1079 // Emit all of the matcher methods...
1080 //
1081 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1082 E = ComputableValues.end(); I != E; ++I) {
1083 const std::string &SlotName = I->first;
1084 OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
1085 << "(SelectionDAGNode *N) {\n"
1086 << " assert(N->getValueType() == MVT::"
1087 << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
1088 << ");\n" << " // If we already have a cost available for " << SlotName
1089 << " use it!\n"
1090 << " if (N->getPatternFor(" << SlotName << "_Slot))\n"
1091 << " return N->getCostFor(" << SlotName << "_Slot);\n\n"
1092 << " unsigned Cost;\n"
1093 << " switch (N->getNodeType()) {\n"
1094 << " default: Cost = ~0U >> 1; // Match failed\n"
1095 << " N->setPatternCostFor(" << SlotName << "_Slot, NoMatchPattern, Cost, NumSlots);\n"
1096 << " break;\n";
1097
1098 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1099 E = I->second.end(); J != E; ++J)
1100 if (!J->first->isSubClassOf("Nonterminal"))
1101 OS << " case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
1102 << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
1103 OS << " }\n"; // End of the switch statement
1104
1105 // Emit any patterns which have a nonterminal leaf as the RHS. These may
1106 // match multiple root nodes, so they cannot be handled with the switch...
1107 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1108 E = I->second.end(); J != E; ++J)
1109 if (J->first->isSubClassOf("Nonterminal")) {
1110 OS << " unsigned " << J->first->getName() << "_Cost = Match_"
1111 << getNodeName(J->first) << "(N);\n"
1112 << " if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
1113 << getNodeName(J->first) << "_Cost;\n";
1114 }
1115
1116 OS << " return Cost;\n}\n\n";
1117
1118 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1119 E = I->second.end(); J != E; ++J) {
1120 Record *Operator = J->first;
1121 bool isNonterm = Operator->isSubClassOf("Nonterminal");
1122 if (!isNonterm) {
1123 OS << "unsigned " << Target.getName() << "ISel::Match_";
1124 if (!isNonterm) OS << SlotName << "_";
1125 OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
1126 << " unsigned Pattern = NoMatchPattern;\n"
1127 << " unsigned MinCost = ~0U >> 1;\n";
1128
1129 std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
1130 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1131 Patterns.push_back(std::make_pair(J->second[i],
1132 J->second[i]->getTree()));
1133 EmitMatchCosters(OS, Patterns, "N", 2);
1134
1135 OS << "\n N->setPatternCostFor(" << SlotName
1136 << "_Slot, Pattern, MinCost, NumSlots);\n"
1137 << " return MinCost;\n"
1138 << "}\n";
1139 }
1140 }
1141 }
1142
1143 //===--------------------------------------------------------------------===//
1144 // Emit all of the reducer methods...
1145 //
1146 OS << "\n\n//===" << std::string(70, '-') << "===//\n"
1147 << "// Reducer methods...\n"
1148 << "//\n";
1149
1150 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1151 E = ComputableValues.end(); I != E; ++I) {
1152 const std::string &SlotName = I->first;
1153 OS << "ReducedValue_" << SlotName << " *" << Target.getName()
1154 << "ISel::Reduce_" << SlotName
1155 << "(SelectionDAGNode *N, MachineBasicBlock *MBB) {\n"
1156 << " ReducedValue_" << SlotName << " *Val = N->hasValue<ReducedValue_"
1157 << SlotName << ">(" << SlotName << "_Slot);\n"
1158 << " if (Val) return Val;\n"
1159 << " if (N->getBB()) MBB = N->getBB();\n\n"
1160 << " switch (N->getPatternFor(" << SlotName << "_Slot)) {\n";
1161
1162 // Loop over all of the patterns that can produce a value for this slot...
1163 PatternOrganizer::NodesForSlot &NodesForSlot = I->second;
1164 for (PatternOrganizer::NodesForSlot::iterator J = NodesForSlot.begin(),
1165 E = NodesForSlot.end(); J != E; ++J)
1166 for (unsigned i = 0, e = J->second.size(); i != e; ++i) {
1167 Pattern *P = J->second[i];
1168 OS << " case " << P->getRecord()->getName() << "_Pattern: {\n"
1169 << " // " << *P << "\n";
1170 // Loop over the operands, reducing them...
1171 std::vector<std::pair<TreePatternNode*, std::string> > Operands;
1172 ReduceAllOperands(P->getTree(), "N", Operands, OS);
1173
1174 // Now that we have reduced all of our operands, and have the values
1175 // that reduction produces, perform the reduction action for this
1176 // pattern.
1177 std::string Result;
1178
1179 // If the pattern produces a register result, generate a new register
1180 // now.
1181 if (Record *R = P->getResult()) {
1182 assert(R->isSubClassOf("RegisterClass") &&
1183 "Only handle register class results so far!");
1184 OS << " unsigned NewReg = makeAnotherReg(" << Target.getName()
1185 << "::" << R->getName() << "RegisterClass);\n";
1186 Result = "NewReg";
1187 DEBUG(OS << " std::cerr << \"%reg\" << NewReg << \" =\t\";\n");
1188 } else {
1189 DEBUG(OS << " std::cerr << \"\t\t\";\n");
1190 Result = "0";
1191 }
1192
1193 // Print out the pattern that matched...
1194 DEBUG(OS << " std::cerr << \" " << P->getRecord()->getName() <<'"');
1195 DEBUG(for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1196 if (Operands[i].first->isLeaf()) {
1197 Record *RV = Operands[i].first->getValueRecord();
1198 assert(RV->isSubClassOf("RegisterClass") &&
1199 "Only handles registers here so far!");
1200 OS << " << \" %reg\" << " << Operands[i].second
1201 << "->Val";
1202 } else {
1203 OS << " << ' ' << " << Operands[i].second
1204 << "->Val";
1205 });
1206 DEBUG(OS << " << \"\\n\";\n");
1207
1208 // Generate the reduction code appropriate to the particular type of
1209 // pattern that this is...
1210 switch (P->getPatternType()) {
1211 case Pattern::Instruction:
1212 // Instruction patterns just emit a single MachineInstr, using BuildMI
1213 OS << " BuildMI(MBB, " << Target.getName() << "::"
1214 << P->getRecord()->getName() << ", " << Operands.size();
1215 if (P->getResult()) OS << ", NewReg";
1216 OS << ")";
1217
1218 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1219 TreePatternNode *Op = Operands[i].first;
1220 if (Op->isLeaf()) {
1221 Record *RV = Op->getValueRecord();
1222 assert(RV->isSubClassOf("RegisterClass") &&
1223 "Only handles registers here so far!");
1224 OS << ".addReg(" << Operands[i].second << "->Val)";
1225 } else if (Op->getOperator()->getName() == "imm") {
1226 OS << ".addZImm(" << Operands[i].second << "->Val)";
1227 } else if (Op->getOperator()->getName() == "basicblock") {
1228 OS << ".addMBB(" << Operands[i].second << "->Val)";
1229 } else {
1230 assert(0 && "Unknown value type!");
1231 }
1232 }
1233 OS << ";\n";
1234 break;
1235 case Pattern::Expander: {
1236 // Expander patterns emit one machine instr for each instruction in
1237 // the list of instructions expanded to.
1238 ListInit *Insts = P->getRecord()->getValueAsListInit("Result");
1239 for (unsigned IN = 0, e = Insts->getSize(); IN != e; ++IN) {
1240 DagInit *DIInst = dynamic_cast<DagInit*>(Insts->getElement(IN));
1241 if (!DIInst) P->error("Result list must contain instructions!");
1242 Record *InstRec = DIInst->getNodeType();
1243 Pattern *InstPat = getPattern(InstRec);
1244 if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
1245 P->error("Instruction list must contain Instruction patterns!");
1246
1247 bool hasResult = InstPat->getResult() != 0;
1248 if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
1249 P->error("Incorrect number of arguments specified for inst '" +
1250 InstPat->getRecord()->getName() + "' in result list!");
1251 }
1252
1253 // Start emission of the instruction...
1254 OS << " BuildMI(MBB, " << Target.getName() << "::"
1255 << InstRec->getName() << ", "
1256 << DIInst->getNumArgs()-hasResult;
1257 // Emit register result if necessary..
1258 if (hasResult) {
1259 std::string ArgNameVal =
1260 getArgName(P, DIInst->getArgName(0), Operands);
1261 PrintExpanderOperand(DIInst->getArg(0), ArgNameVal,
1262 InstPat->getResultNode(), P, false,
1263 OS << ", ");
1264 }
1265 OS << ")";
1266
1267 for (unsigned i = hasResult, e = DIInst->getNumArgs(); i != e; ++i){
1268 std::string ArgNameVal =
1269 getArgName(P, DIInst->getArgName(i), Operands);
1270
1271 PrintExpanderOperand(DIInst->getArg(i), ArgNameVal,
1272 InstPat->getArg(i-hasResult), P, true, OS);
1273 }
1274
1275 OS << ";\n";
1276 }
1277 break;
1278 }
1279 default:
1280 assert(0 && "Reduction of this type of pattern not implemented!");
1281 }
1282
1283 OS << " Val = new ReducedValue_" << SlotName << "(" << Result<<");\n"
1284 << " break;\n"
1285 << " }\n";
1286 }
1287
1288
1289 OS << " default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
1290 << " }\n\n N->addValue(Val); // Do not ever recalculate this\n"
1291 << " return Val;\n}\n\n";
1292 }
1293}
1294