add plumbing for handling multiple result nodes
[oota-llvm.git] / utils / TableGen / DAGISelMatcherEmitter.cpp
1 //===- DAGISelMatcherEmitter.cpp - Matcher Emitter ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains code to generate C++ code a matcher.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "DAGISelMatcher.h"
15 #include "CodeGenDAGPatterns.h"
16 #include "Record.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/FormattedStream.h"
22 using namespace llvm;
23
24 enum {
25   CommentIndent = 30
26 };
27
28 // To reduce generated source code size.
29 static cl::opt<bool>
30 OmitComments("omit-comments", cl::desc("Do not generate comments"),
31              cl::init(false));
32
33 namespace {
34 class MatcherTableEmitter {
35   StringMap<unsigned> NodePredicateMap, PatternPredicateMap;
36   std::vector<std::string> NodePredicates, PatternPredicates;
37
38   DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
39   std::vector<const ComplexPattern*> ComplexPatterns;
40
41
42   DenseMap<Record*, unsigned> NodeXFormMap;
43   std::vector<Record*> NodeXForms;
44
45 public:
46   MatcherTableEmitter() {}
47
48   unsigned EmitMatcherList(const Matcher *N, unsigned Indent,
49                            unsigned StartIdx, formatted_raw_ostream &OS);
50   
51   void EmitPredicateFunctions(const CodeGenDAGPatterns &CGP,
52                               formatted_raw_ostream &OS);
53   
54   void EmitHistogram(const Matcher *N, formatted_raw_ostream &OS);
55 private:
56   unsigned EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
57                        formatted_raw_ostream &OS);
58   
59   unsigned getNodePredicate(StringRef PredName) {
60     unsigned &Entry = NodePredicateMap[PredName];
61     if (Entry == 0) {
62       NodePredicates.push_back(PredName.str());
63       Entry = NodePredicates.size();
64     }
65     return Entry-1;
66   }
67   unsigned getPatternPredicate(StringRef PredName) {
68     unsigned &Entry = PatternPredicateMap[PredName];
69     if (Entry == 0) {
70       PatternPredicates.push_back(PredName.str());
71       Entry = PatternPredicates.size();
72     }
73     return Entry-1;
74   }
75   
76   unsigned getComplexPat(const ComplexPattern &P) {
77     unsigned &Entry = ComplexPatternMap[&P];
78     if (Entry == 0) {
79       ComplexPatterns.push_back(&P);
80       Entry = ComplexPatterns.size();
81     }
82     return Entry-1;
83   }
84   
85   unsigned getNodeXFormID(Record *Rec) {
86     unsigned &Entry = NodeXFormMap[Rec];
87     if (Entry == 0) {
88       NodeXForms.push_back(Rec);
89       Entry = NodeXForms.size();
90     }
91     return Entry-1;
92   }
93   
94 };
95 } // end anonymous namespace.
96
97 static unsigned GetVBRSize(unsigned Val) {
98   if (Val <= 127) return 1;
99   
100   unsigned NumBytes = 0;
101   while (Val >= 128) {
102     Val >>= 7;
103     ++NumBytes;
104   }
105   return NumBytes+1;
106 }
107
108 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
109 /// bytes emitted.
110 static uint64_t EmitVBRValue(uint64_t Val, raw_ostream &OS) {
111   if (Val <= 127) {
112     OS << Val << ", ";
113     return 1;
114   }
115   
116   uint64_t InVal = Val;
117   unsigned NumBytes = 0;
118   while (Val >= 128) {
119     OS << (Val&127) << "|128,";
120     Val >>= 7;
121     ++NumBytes;
122   }
123   OS << Val;
124   if (!OmitComments)
125     OS << "/*" << InVal << "*/";
126   OS << ", ";
127   return NumBytes+1;
128 }
129
130 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
131 /// the number of bytes emitted.
132 unsigned MatcherTableEmitter::
133 EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
134             formatted_raw_ostream &OS) {
135   OS.PadToColumn(Indent*2);
136   
137   switch (N->getKind()) {
138   case Matcher::Scope: {
139     const ScopeMatcher *SM = cast<ScopeMatcher>(N);
140     assert(SM->getNext() == 0 && "Shouldn't have next after scope");
141     
142     unsigned StartIdx = CurrentIdx;
143     
144     // Emit all of the children.
145     for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
146       if (i == 0) {
147         OS << "OPC_Scope, ";
148         ++CurrentIdx;
149       } else  {
150         if (!OmitComments) {
151           OS << "/*" << CurrentIdx << "*/";
152           OS.PadToColumn(Indent*2) << "/*Scope*/ ";
153         } else
154           OS.PadToColumn(Indent*2);
155       }
156
157       // We need to encode the child and the offset of the failure code before
158       // emitting either of them.  Handle this by buffering the output into a
159       // string while we get the size.  Unfortunately, the offset of the
160       // children depends on the VBR size of the child, so for large children we
161       // have to iterate a bit.
162       SmallString<128> TmpBuf;
163       unsigned ChildSize = 0;
164       unsigned VBRSize = 0;
165       do {
166         VBRSize = GetVBRSize(ChildSize);
167         
168         TmpBuf.clear();
169         raw_svector_ostream OS(TmpBuf);
170         formatted_raw_ostream FOS(OS);
171         ChildSize = EmitMatcherList(SM->getChild(i), Indent+1,
172                                     CurrentIdx+VBRSize, FOS);
173       } while (GetVBRSize(ChildSize) != VBRSize);
174       
175       assert(ChildSize != 0 && "Should not have a zero-sized child!");
176     
177       CurrentIdx += EmitVBRValue(ChildSize, OS);
178       if (!OmitComments) {
179         OS << "/*->" << CurrentIdx+ChildSize << "*/";
180       
181         if (i == 0)
182           OS.PadToColumn(CommentIndent) << "// " << SM->getNumChildren()
183             << " children in Scope";
184       }
185       
186       OS << '\n' << TmpBuf.str();
187       CurrentIdx += ChildSize;
188     }
189     
190     // Emit a zero as a sentinel indicating end of 'Scope'.
191     if (!OmitComments)
192       OS << "/*" << CurrentIdx << "*/";
193     OS.PadToColumn(Indent*2) << "0, ";
194     if (!OmitComments)
195       OS << "/*End of Scope*/";
196     OS << '\n';
197     return CurrentIdx - StartIdx + 1;
198   }
199       
200   case Matcher::RecordNode:
201     OS << "OPC_RecordNode,";
202     if (!OmitComments)
203       OS.PadToColumn(CommentIndent) << "// #"
204         << cast<RecordMatcher>(N)->getResultNo() << " = "
205         << cast<RecordMatcher>(N)->getWhatFor();
206     OS << '\n';
207     return 1;
208
209   case Matcher::RecordChild:
210     OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo()
211        << ',';
212     if (!OmitComments)
213       OS.PadToColumn(CommentIndent) << "// #"
214         << cast<RecordChildMatcher>(N)->getResultNo() << " = "
215         << cast<RecordChildMatcher>(N)->getWhatFor();
216     OS << '\n';
217     return 1;
218       
219   case Matcher::RecordMemRef:
220     OS << "OPC_RecordMemRef,\n";
221     return 1;
222       
223   case Matcher::CaptureFlagInput:
224     OS << "OPC_CaptureFlagInput,\n";
225     return 1;
226       
227   case Matcher::MoveChild:
228     OS << "OPC_MoveChild, " << cast<MoveChildMatcher>(N)->getChildNo() << ",\n";
229     return 2;
230       
231   case Matcher::MoveParent:
232     OS << "OPC_MoveParent,\n";
233     return 1;
234       
235   case Matcher::CheckSame:
236     OS << "OPC_CheckSame, "
237        << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n";
238     return 2;
239
240   case Matcher::CheckPatternPredicate: {
241     StringRef Pred = cast<CheckPatternPredicateMatcher>(N)->getPredicate();
242     OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
243     if (!OmitComments)
244       OS.PadToColumn(CommentIndent) << "// " << Pred;
245     OS << '\n';
246     return 2;
247   }
248   case Matcher::CheckPredicate: {
249     StringRef Pred = cast<CheckPredicateMatcher>(N)->getPredicateName();
250     OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
251     if (!OmitComments)
252       OS.PadToColumn(CommentIndent) << "// " << Pred;
253     OS << '\n';
254     return 2;
255   }
256
257   case Matcher::CheckOpcode:
258     OS << "OPC_CheckOpcode, "
259        << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << ",\n";
260     return 2;
261       
262   case Matcher::SwitchOpcode:
263   case Matcher::SwitchType: {
264     unsigned StartIdx = CurrentIdx;
265     
266     unsigned NumCases;
267     if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
268       OS << "OPC_SwitchOpcode ";
269       NumCases = SOM->getNumCases();
270     } else {
271       OS << "OPC_SwitchType ";
272       NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
273     }
274
275     if (!OmitComments)
276       OS << "/*" << NumCases << " cases */";
277     OS << ", ";
278     ++CurrentIdx;
279     
280     // For each case we emit the size, then the opcode, then the matcher.
281     for (unsigned i = 0, e = NumCases; i != e; ++i) {
282       const Matcher *Child;
283       if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
284         Child = SOM->getCaseMatcher(i);
285       else
286         Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
287       
288       // We need to encode the opcode and the offset of the case code before
289       // emitting the case code.  Handle this by buffering the output into a
290       // string while we get the size.  Unfortunately, the offset of the
291       // children depends on the VBR size of the child, so for large children we
292       // have to iterate a bit.
293       SmallString<128> TmpBuf;
294       unsigned ChildSize = 0;
295       unsigned VBRSize = 0;
296       do {
297         VBRSize = GetVBRSize(ChildSize);
298         
299         TmpBuf.clear();
300         raw_svector_ostream OS(TmpBuf);
301         formatted_raw_ostream FOS(OS);
302         ChildSize = EmitMatcherList(Child, Indent+1, CurrentIdx+VBRSize+1, FOS);
303       } while (GetVBRSize(ChildSize) != VBRSize);
304       
305       assert(ChildSize != 0 && "Should not have a zero-sized child!");
306       
307       if (i != 0) {
308         OS.PadToColumn(Indent*2);
309         if (!OmitComments)
310         OS << (isa<SwitchOpcodeMatcher>(N) ?
311                    "/*SwitchOpcode*/ " : "/*SwitchType*/ ");
312       }
313       
314       // Emit the VBR.
315       CurrentIdx += EmitVBRValue(ChildSize, OS);
316       
317       OS << ' ';
318       if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
319         OS << SOM->getCaseOpcode(i).getEnumName();
320       else
321         OS << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i));
322       OS << ',';
323       
324       if (!OmitComments)
325         OS << "// ->" << CurrentIdx+ChildSize+1;
326       OS << '\n';
327       ++CurrentIdx;
328       OS << TmpBuf.str();
329       CurrentIdx += ChildSize;
330     }
331
332     // Emit the final zero to terminate the switch.
333     OS.PadToColumn(Indent*2) << "0, ";
334     if (!OmitComments)
335       OS << (isa<SwitchOpcodeMatcher>(N) ?
336              "// EndSwitchOpcode" : "// EndSwitchType");
337
338     OS << '\n';
339     ++CurrentIdx;
340     return CurrentIdx-StartIdx;
341   }
342
343  case Matcher::CheckType:
344     assert(cast<CheckTypeMatcher>(N)->getResNo() == 0 &&
345            "FIXME: Add support for CheckType of resno != 0");
346     OS << "OPC_CheckType, "
347        << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
348     return 2;
349       
350   case Matcher::CheckChildType:
351     OS << "OPC_CheckChild"
352        << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, "
353        << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n";
354     return 2;
355       
356   case Matcher::CheckInteger: {
357     OS << "OPC_CheckInteger, ";
358     unsigned Bytes=1+EmitVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
359     OS << '\n';
360     return Bytes;
361   }
362   case Matcher::CheckCondCode:
363     OS << "OPC_CheckCondCode, ISD::"
364        << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
365     return 2;
366       
367   case Matcher::CheckValueType:
368     OS << "OPC_CheckValueType, MVT::"
369        << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
370     return 2;
371
372   case Matcher::CheckComplexPat: {
373     const CheckComplexPatMatcher *CCPM = cast<CheckComplexPatMatcher>(N);
374     const ComplexPattern &Pattern = CCPM->getPattern();
375     OS << "OPC_CheckComplexPat, /*CP*/" << getComplexPat(Pattern) << ", /*#*/"
376        << CCPM->getMatchNumber() << ',';
377     
378     if (!OmitComments) {
379       OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
380       OS << ":$" << CCPM->getName();
381       for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i)
382         OS << " #" << CCPM->getFirstResult()+i;
383            
384       if (Pattern.hasProperty(SDNPHasChain))
385         OS << " + chain result";
386     }
387     OS << '\n';
388     return 3;
389   }
390       
391   case Matcher::CheckAndImm: {
392     OS << "OPC_CheckAndImm, ";
393     unsigned Bytes=1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
394     OS << '\n';
395     return Bytes;
396   }
397
398   case Matcher::CheckOrImm: {
399     OS << "OPC_CheckOrImm, ";
400     unsigned Bytes = 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
401     OS << '\n';
402     return Bytes;
403   }
404       
405   case Matcher::CheckFoldableChainNode:
406     OS << "OPC_CheckFoldableChainNode,\n";
407     return 1;
408       
409   case Matcher::EmitInteger: {
410     int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
411     OS << "OPC_EmitInteger, "
412        << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", ";
413     unsigned Bytes = 2+EmitVBRValue(Val, OS);
414     OS << '\n';
415     return Bytes;
416   }
417   case Matcher::EmitStringInteger: {
418     const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
419     // These should always fit into one byte.
420     OS << "OPC_EmitInteger, "
421       << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", "
422       << Val << ",\n";
423     return 3;
424   }
425       
426   case Matcher::EmitRegister:
427     OS << "OPC_EmitRegister, "
428        << getEnumName(cast<EmitRegisterMatcher>(N)->getVT()) << ", ";
429     if (Record *R = cast<EmitRegisterMatcher>(N)->getReg())
430       OS << getQualifiedName(R) << ",\n";
431     else {
432       OS << "0 ";
433       if (!OmitComments)
434         OS << "/*zero_reg*/";
435       OS << ",\n";
436     }
437     return 3;
438       
439   case Matcher::EmitConvertToTarget:
440     OS << "OPC_EmitConvertToTarget, "
441        << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
442     return 2;
443       
444   case Matcher::EmitMergeInputChains: {
445     const EmitMergeInputChainsMatcher *MN =
446       cast<EmitMergeInputChainsMatcher>(N);
447     OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
448     for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
449       OS << MN->getNode(i) << ", ";
450     OS << '\n';
451     return 2+MN->getNumNodes();
452   }
453   case Matcher::EmitCopyToReg:
454     OS << "OPC_EmitCopyToReg, "
455        << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
456        << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
457        << ",\n";
458     return 3;
459   case Matcher::EmitNodeXForm: {
460     const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
461     OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
462        << XF->getSlot() << ',';
463     if (!OmitComments)
464       OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName();
465     OS <<'\n';
466     return 3;
467   }
468       
469   case Matcher::EmitNode:
470   case Matcher::MorphNodeTo: {
471     const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
472     OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
473     OS << ", TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
474     
475     if (EN->hasChain())   OS << "|OPFL_Chain";
476     if (EN->hasInFlag())  OS << "|OPFL_FlagInput";
477     if (EN->hasOutFlag()) OS << "|OPFL_FlagOutput";
478     if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
479     if (EN->getNumFixedArityOperands() != -1)
480       OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
481     OS << ",\n";
482     
483     OS.PadToColumn(Indent*2+4) << EN->getNumVTs();
484     if (!OmitComments)
485       OS << "/*#VTs*/";
486     OS << ", ";
487     for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
488       OS << getEnumName(EN->getVT(i)) << ", ";
489
490     OS << EN->getNumOperands();
491     if (!OmitComments)
492       OS << "/*#Ops*/";
493     OS << ", ";
494     unsigned NumOperandBytes = 0;
495     for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
496       NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
497     
498     if (!OmitComments) {
499       // Print the result #'s for EmitNode.
500       if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
501         if (unsigned NumResults = EN->getNumVTs()) {
502           OS.PadToColumn(CommentIndent) << "// Results = ";
503           unsigned First = E->getFirstResultSlot();
504           for (unsigned i = 0; i != NumResults; ++i)
505             OS << "#" << First+i << " ";
506         }
507       }
508       OS << '\n';
509
510       if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
511         OS.PadToColumn(Indent*2) << "// Src: "
512           << *SNT->getPattern().getSrcPattern() << '\n';
513         OS.PadToColumn(Indent*2) << "// Dst: "
514           << *SNT->getPattern().getDstPattern() << '\n';
515       }
516     } else
517       OS << '\n';
518     
519     return 6+EN->getNumVTs()+NumOperandBytes;
520   }
521   case Matcher::MarkFlagResults: {
522     const MarkFlagResultsMatcher *CFR = cast<MarkFlagResultsMatcher>(N);
523     OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
524     unsigned NumOperandBytes = 0;
525     for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
526       NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
527     OS << '\n';
528     return 2+NumOperandBytes;
529   }
530   case Matcher::CompleteMatch: {
531     const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
532     OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
533     unsigned NumResultBytes = 0;
534     for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
535       NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
536     OS << '\n';
537     if (!OmitComments) {
538       OS.PadToColumn(Indent*2) << "// Src: "
539         << *CM->getPattern().getSrcPattern() << '\n';
540       OS.PadToColumn(Indent*2) << "// Dst: "
541         << *CM->getPattern().getDstPattern();
542     }
543     OS << '\n';
544     return 2 + NumResultBytes;
545   }
546   }
547   assert(0 && "Unreachable");
548   return 0;
549 }
550
551 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
552 unsigned MatcherTableEmitter::
553 EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
554                 formatted_raw_ostream &OS) {
555   unsigned Size = 0;
556   while (N) {
557     if (!OmitComments)
558       OS << "/*" << CurrentIdx << "*/";
559     unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
560     Size += MatcherSize;
561     CurrentIdx += MatcherSize;
562     
563     // If there are other nodes in this list, iterate to them, otherwise we're
564     // done.
565     N = N->getNext();
566   }
567   return Size;
568 }
569
570 void MatcherTableEmitter::EmitPredicateFunctions(const CodeGenDAGPatterns &CGP,
571                                                  formatted_raw_ostream &OS) {
572   // Emit pattern predicates.
573   if (!PatternPredicates.empty()) {
574     OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
575     OS << "  switch (PredNo) {\n";
576     OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
577     for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
578       OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n";
579     OS << "  }\n";
580     OS << "}\n\n";
581   }
582    
583   // Emit Node predicates.
584   // FIXME: Annoyingly, these are stored by name, which we never even emit. Yay?
585   StringMap<TreePattern*> PFsByName;
586   
587   for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
588        I != E; ++I)
589     PFsByName[I->first->getName()] = I->second;
590   
591   if (!NodePredicates.empty()) {
592     OS << "bool CheckNodePredicate(SDNode *Node, unsigned PredNo) const {\n";
593     OS << "  switch (PredNo) {\n";
594     OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
595     for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i) {
596       // FIXME: Storing this by name is horrible.
597       TreePattern *P =PFsByName[NodePredicates[i].substr(strlen("Predicate_"))];
598       assert(P && "Unknown name?");
599       
600       // Emit the predicate code corresponding to this pattern.
601       std::string Code = P->getRecord()->getValueAsCode("Predicate");
602       assert(!Code.empty() && "No code in this predicate");
603       OS << "  case " << i << ": { // " << NodePredicates[i] << '\n';
604       std::string ClassName;
605       if (P->getOnlyTree()->isLeaf())
606         ClassName = "SDNode";
607       else
608         ClassName =
609           CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
610       if (ClassName == "SDNode")
611         OS << "    SDNode *N = Node;\n";
612       else
613         OS << "    " << ClassName << "*N = cast<" << ClassName << ">(Node);\n";
614       OS << Code << "\n  }\n";
615     }
616     OS << "  }\n";
617     OS << "}\n\n";
618   }
619   
620   // Emit CompletePattern matchers.
621   // FIXME: This should be const.
622   if (!ComplexPatterns.empty()) {
623     OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
624     OS << "      unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
625     OS << "  switch (PatternNo) {\n";
626     OS << "  default: assert(0 && \"Invalid pattern # in table?\");\n";
627     for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
628       const ComplexPattern &P = *ComplexPatterns[i];
629       unsigned NumOps = P.getNumOperands();
630
631       if (P.hasProperty(SDNPHasChain))
632         ++NumOps;  // Get the chained node too.
633       
634       OS << "  case " << i << ":\n";
635       OS << "    Result.resize(Result.size()+" << NumOps << ");\n";
636       OS << "    return "  << P.getSelectFunc();
637
638       OS << "(Root, N";
639       for (unsigned i = 0; i != NumOps; ++i)
640         OS << ", Result[Result.size()-" << (NumOps-i) << ']';
641       OS << ");\n";
642     }
643     OS << "  }\n";
644     OS << "}\n\n";
645   }
646   
647   
648   // Emit SDNodeXForm handlers.
649   // FIXME: This should be const.
650   if (!NodeXForms.empty()) {
651     OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
652     OS << "  switch (XFormNo) {\n";
653     OS << "  default: assert(0 && \"Invalid xform # in table?\");\n";
654     
655     // FIXME: The node xform could take SDValue's instead of SDNode*'s.
656     for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) {
657       const CodeGenDAGPatterns::NodeXForm &Entry =
658         CGP.getSDNodeTransform(NodeXForms[i]);
659       
660       Record *SDNode = Entry.first;
661       const std::string &Code = Entry.second;
662       
663       OS << "  case " << i << ": {  ";
664       if (!OmitComments)
665         OS << "// " << NodeXForms[i]->getName();
666       OS << '\n';
667       
668       std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
669       if (ClassName == "SDNode")
670         OS << "    SDNode *N = V.getNode();\n";
671       else
672         OS << "    " << ClassName << " *N = cast<" << ClassName
673            << ">(V.getNode());\n";
674       OS << Code << "\n  }\n";
675     }
676     OS << "  }\n";
677     OS << "}\n\n";
678   }
679 }
680
681 static void BuildHistogram(const Matcher *M, std::vector<unsigned> &OpcodeFreq){
682   for (; M != 0; M = M->getNext()) {
683     // Count this node.
684     if (unsigned(M->getKind()) >= OpcodeFreq.size())
685       OpcodeFreq.resize(M->getKind()+1);
686     OpcodeFreq[M->getKind()]++;
687   
688     // Handle recursive nodes.
689     if (const ScopeMatcher *SM = dyn_cast<ScopeMatcher>(M)) {
690       for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i)
691         BuildHistogram(SM->getChild(i), OpcodeFreq);
692     } else if (const SwitchOpcodeMatcher *SOM = 
693                  dyn_cast<SwitchOpcodeMatcher>(M)) {
694       for (unsigned i = 0, e = SOM->getNumCases(); i != e; ++i)
695         BuildHistogram(SOM->getCaseMatcher(i), OpcodeFreq);
696     } else if (const SwitchTypeMatcher *STM = dyn_cast<SwitchTypeMatcher>(M)) {
697       for (unsigned i = 0, e = STM->getNumCases(); i != e; ++i)
698         BuildHistogram(STM->getCaseMatcher(i), OpcodeFreq);
699     }
700   }
701 }
702
703 void MatcherTableEmitter::EmitHistogram(const Matcher *M,
704                                         formatted_raw_ostream &OS) {
705   if (OmitComments)
706     return;
707   
708   std::vector<unsigned> OpcodeFreq;
709   BuildHistogram(M, OpcodeFreq);
710   
711   OS << "  // Opcode Histogram:\n";
712   for (unsigned i = 0, e = OpcodeFreq.size(); i != e; ++i) {
713     OS << "  // #";
714     switch ((Matcher::KindTy)i) {
715     case Matcher::Scope: OS << "OPC_Scope"; break; 
716     case Matcher::RecordNode: OS << "OPC_RecordNode"; break; 
717     case Matcher::RecordChild: OS << "OPC_RecordChild"; break;
718     case Matcher::RecordMemRef: OS << "OPC_RecordMemRef"; break;
719     case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break;
720     case Matcher::MoveChild: OS << "OPC_MoveChild"; break;
721     case Matcher::MoveParent: OS << "OPC_MoveParent"; break;
722     case Matcher::CheckSame: OS << "OPC_CheckSame"; break;
723     case Matcher::CheckPatternPredicate:
724       OS << "OPC_CheckPatternPredicate"; break;
725     case Matcher::CheckPredicate: OS << "OPC_CheckPredicate"; break;
726     case Matcher::CheckOpcode: OS << "OPC_CheckOpcode"; break;
727     case Matcher::SwitchOpcode: OS << "OPC_SwitchOpcode"; break;
728     case Matcher::CheckType: OS << "OPC_CheckType"; break;
729     case Matcher::SwitchType: OS << "OPC_SwitchType"; break;
730     case Matcher::CheckChildType: OS << "OPC_CheckChildType"; break;
731     case Matcher::CheckInteger: OS << "OPC_CheckInteger"; break;
732     case Matcher::CheckCondCode: OS << "OPC_CheckCondCode"; break;
733     case Matcher::CheckValueType: OS << "OPC_CheckValueType"; break;
734     case Matcher::CheckComplexPat: OS << "OPC_CheckComplexPat"; break;
735     case Matcher::CheckAndImm: OS << "OPC_CheckAndImm"; break;
736     case Matcher::CheckOrImm: OS << "OPC_CheckOrImm"; break;
737     case Matcher::CheckFoldableChainNode:
738       OS << "OPC_CheckFoldableChainNode"; break;
739     case Matcher::EmitInteger: OS << "OPC_EmitInteger"; break;
740     case Matcher::EmitStringInteger: OS << "OPC_EmitStringInteger"; break;
741     case Matcher::EmitRegister: OS << "OPC_EmitRegister"; break;
742     case Matcher::EmitConvertToTarget: OS << "OPC_EmitConvertToTarget"; break;
743     case Matcher::EmitMergeInputChains: OS << "OPC_EmitMergeInputChains"; break;
744     case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break;
745     case Matcher::EmitNode: OS << "OPC_EmitNode"; break;
746     case Matcher::MorphNodeTo: OS << "OPC_MorphNodeTo"; break;
747     case Matcher::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break;
748     case Matcher::MarkFlagResults: OS << "OPC_MarkFlagResults"; break;
749     case Matcher::CompleteMatch: OS << "OPC_CompleteMatch"; break;    
750     }
751     
752     OS.PadToColumn(40) << " = " << OpcodeFreq[i] << '\n';
753   }
754   OS << '\n';
755 }
756
757
758 void llvm::EmitMatcherTable(const Matcher *TheMatcher,
759                             const CodeGenDAGPatterns &CGP, raw_ostream &O) {
760   formatted_raw_ostream OS(O);
761   
762   OS << "// The main instruction selector code.\n";
763   OS << "SDNode *SelectCode(SDNode *N) {\n";
764
765   MatcherTableEmitter MatcherEmitter;
766
767   OS << "  // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
768   OS << "  #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
769   OS << "  static const unsigned char MatcherTable[] = {\n";
770   unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 5, 0, OS);
771   OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
772   
773   MatcherEmitter.EmitHistogram(TheMatcher, OS);
774   
775   OS << "  #undef TARGET_OPCODE\n";
776   OS << "  return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
777   OS << '\n';
778   
779   // Next up, emit the function for node and pattern predicates:
780   MatcherEmitter.EmitPredicateFunctions(CGP, OS);
781 }