Change tblgen to emit FOOISD opcode names as two
[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, TARGET_OPCODE("
259        << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << "),\n";
260     return 3;
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 << "TARGET_OPCODE(" << SOM->getCaseOpcode(i).getEnumName() << "),";
320         CurrentIdx += 2;
321       } else {
322         OS << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i)) << ',';
323         ++CurrentIdx;
324       }
325       
326       if (!OmitComments)
327         OS << "// ->" << CurrentIdx+ChildSize;
328       OS << '\n';
329       OS << TmpBuf.str();
330       CurrentIdx += ChildSize;
331     }
332
333     // Emit the final zero to terminate the switch.
334     OS.PadToColumn(Indent*2) << "0, ";
335     if (!OmitComments)
336       OS << (isa<SwitchOpcodeMatcher>(N) ?
337              "// EndSwitchOpcode" : "// EndSwitchType");
338
339     OS << '\n';
340     ++CurrentIdx;
341     return CurrentIdx-StartIdx;
342   }
343
344  case Matcher::CheckType:
345     assert(cast<CheckTypeMatcher>(N)->getResNo() == 0 &&
346            "FIXME: Add support for CheckType of resno != 0");
347     OS << "OPC_CheckType, "
348        << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
349     return 2;
350       
351   case Matcher::CheckChildType:
352     OS << "OPC_CheckChild"
353        << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, "
354        << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n";
355     return 2;
356       
357   case Matcher::CheckInteger: {
358     OS << "OPC_CheckInteger, ";
359     unsigned Bytes=1+EmitVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
360     OS << '\n';
361     return Bytes;
362   }
363   case Matcher::CheckCondCode:
364     OS << "OPC_CheckCondCode, ISD::"
365        << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
366     return 2;
367       
368   case Matcher::CheckValueType:
369     OS << "OPC_CheckValueType, MVT::"
370        << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
371     return 2;
372
373   case Matcher::CheckComplexPat: {
374     const CheckComplexPatMatcher *CCPM = cast<CheckComplexPatMatcher>(N);
375     const ComplexPattern &Pattern = CCPM->getPattern();
376     OS << "OPC_CheckComplexPat, /*CP*/" << getComplexPat(Pattern) << ", /*#*/"
377        << CCPM->getMatchNumber() << ',';
378     
379     if (!OmitComments) {
380       OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
381       OS << ":$" << CCPM->getName();
382       for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i)
383         OS << " #" << CCPM->getFirstResult()+i;
384            
385       if (Pattern.hasProperty(SDNPHasChain))
386         OS << " + chain result";
387     }
388     OS << '\n';
389     return 3;
390   }
391       
392   case Matcher::CheckAndImm: {
393     OS << "OPC_CheckAndImm, ";
394     unsigned Bytes=1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
395     OS << '\n';
396     return Bytes;
397   }
398
399   case Matcher::CheckOrImm: {
400     OS << "OPC_CheckOrImm, ";
401     unsigned Bytes = 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
402     OS << '\n';
403     return Bytes;
404   }
405       
406   case Matcher::CheckFoldableChainNode:
407     OS << "OPC_CheckFoldableChainNode,\n";
408     return 1;
409       
410   case Matcher::EmitInteger: {
411     int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
412     OS << "OPC_EmitInteger, "
413        << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", ";
414     unsigned Bytes = 2+EmitVBRValue(Val, OS);
415     OS << '\n';
416     return Bytes;
417   }
418   case Matcher::EmitStringInteger: {
419     const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
420     // These should always fit into one byte.
421     OS << "OPC_EmitInteger, "
422       << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", "
423       << Val << ",\n";
424     return 3;
425   }
426       
427   case Matcher::EmitRegister:
428     OS << "OPC_EmitRegister, "
429        << getEnumName(cast<EmitRegisterMatcher>(N)->getVT()) << ", ";
430     if (Record *R = cast<EmitRegisterMatcher>(N)->getReg())
431       OS << getQualifiedName(R) << ",\n";
432     else {
433       OS << "0 ";
434       if (!OmitComments)
435         OS << "/*zero_reg*/";
436       OS << ",\n";
437     }
438     return 3;
439       
440   case Matcher::EmitConvertToTarget:
441     OS << "OPC_EmitConvertToTarget, "
442        << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
443     return 2;
444       
445   case Matcher::EmitMergeInputChains: {
446     const EmitMergeInputChainsMatcher *MN =
447       cast<EmitMergeInputChainsMatcher>(N);
448     OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
449     for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
450       OS << MN->getNode(i) << ", ";
451     OS << '\n';
452     return 2+MN->getNumNodes();
453   }
454   case Matcher::EmitCopyToReg:
455     OS << "OPC_EmitCopyToReg, "
456        << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
457        << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
458        << ",\n";
459     return 3;
460   case Matcher::EmitNodeXForm: {
461     const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
462     OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
463        << XF->getSlot() << ',';
464     if (!OmitComments)
465       OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName();
466     OS <<'\n';
467     return 3;
468   }
469       
470   case Matcher::EmitNode:
471   case Matcher::MorphNodeTo: {
472     const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
473     OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
474     OS << ", TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
475     
476     if (EN->hasChain())   OS << "|OPFL_Chain";
477     if (EN->hasInFlag())  OS << "|OPFL_FlagInput";
478     if (EN->hasOutFlag()) OS << "|OPFL_FlagOutput";
479     if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
480     if (EN->getNumFixedArityOperands() != -1)
481       OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
482     OS << ",\n";
483     
484     OS.PadToColumn(Indent*2+4) << EN->getNumVTs();
485     if (!OmitComments)
486       OS << "/*#VTs*/";
487     OS << ", ";
488     for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
489       OS << getEnumName(EN->getVT(i)) << ", ";
490
491     OS << EN->getNumOperands();
492     if (!OmitComments)
493       OS << "/*#Ops*/";
494     OS << ", ";
495     unsigned NumOperandBytes = 0;
496     for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
497       NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
498     
499     if (!OmitComments) {
500       // Print the result #'s for EmitNode.
501       if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
502         if (unsigned NumResults = EN->getNumVTs()) {
503           OS.PadToColumn(CommentIndent) << "// Results = ";
504           unsigned First = E->getFirstResultSlot();
505           for (unsigned i = 0; i != NumResults; ++i)
506             OS << "#" << First+i << " ";
507         }
508       }
509       OS << '\n';
510
511       if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
512         OS.PadToColumn(Indent*2) << "// Src: "
513           << *SNT->getPattern().getSrcPattern() << '\n';
514         OS.PadToColumn(Indent*2) << "// Dst: "
515           << *SNT->getPattern().getDstPattern() << '\n';
516       }
517     } else
518       OS << '\n';
519     
520     return 6+EN->getNumVTs()+NumOperandBytes;
521   }
522   case Matcher::MarkFlagResults: {
523     const MarkFlagResultsMatcher *CFR = cast<MarkFlagResultsMatcher>(N);
524     OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
525     unsigned NumOperandBytes = 0;
526     for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
527       NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
528     OS << '\n';
529     return 2+NumOperandBytes;
530   }
531   case Matcher::CompleteMatch: {
532     const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
533     OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
534     unsigned NumResultBytes = 0;
535     for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
536       NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
537     OS << '\n';
538     if (!OmitComments) {
539       OS.PadToColumn(Indent*2) << "// Src: "
540         << *CM->getPattern().getSrcPattern() << '\n';
541       OS.PadToColumn(Indent*2) << "// Dst: "
542         << *CM->getPattern().getDstPattern();
543     }
544     OS << '\n';
545     return 2 + NumResultBytes;
546   }
547   }
548   assert(0 && "Unreachable");
549   return 0;
550 }
551
552 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
553 unsigned MatcherTableEmitter::
554 EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
555                 formatted_raw_ostream &OS) {
556   unsigned Size = 0;
557   while (N) {
558     if (!OmitComments)
559       OS << "/*" << CurrentIdx << "*/";
560     unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
561     Size += MatcherSize;
562     CurrentIdx += MatcherSize;
563     
564     // If there are other nodes in this list, iterate to them, otherwise we're
565     // done.
566     N = N->getNext();
567   }
568   return Size;
569 }
570
571 void MatcherTableEmitter::EmitPredicateFunctions(const CodeGenDAGPatterns &CGP,
572                                                  formatted_raw_ostream &OS) {
573   // Emit pattern predicates.
574   if (!PatternPredicates.empty()) {
575     OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
576     OS << "  switch (PredNo) {\n";
577     OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
578     for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
579       OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n";
580     OS << "  }\n";
581     OS << "}\n\n";
582   }
583    
584   // Emit Node predicates.
585   // FIXME: Annoyingly, these are stored by name, which we never even emit. Yay?
586   StringMap<TreePattern*> PFsByName;
587   
588   for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
589        I != E; ++I)
590     PFsByName[I->first->getName()] = I->second;
591   
592   if (!NodePredicates.empty()) {
593     OS << "bool CheckNodePredicate(SDNode *Node, unsigned PredNo) const {\n";
594     OS << "  switch (PredNo) {\n";
595     OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
596     for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i) {
597       // FIXME: Storing this by name is horrible.
598       TreePattern *P =PFsByName[NodePredicates[i].substr(strlen("Predicate_"))];
599       assert(P && "Unknown name?");
600       
601       // Emit the predicate code corresponding to this pattern.
602       std::string Code = P->getRecord()->getValueAsCode("Predicate");
603       assert(!Code.empty() && "No code in this predicate");
604       OS << "  case " << i << ": { // " << NodePredicates[i] << '\n';
605       std::string ClassName;
606       if (P->getOnlyTree()->isLeaf())
607         ClassName = "SDNode";
608       else
609         ClassName =
610           CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
611       if (ClassName == "SDNode")
612         OS << "    SDNode *N = Node;\n";
613       else
614         OS << "    " << ClassName << "*N = cast<" << ClassName << ">(Node);\n";
615       OS << Code << "\n  }\n";
616     }
617     OS << "  }\n";
618     OS << "}\n\n";
619   }
620   
621   // Emit CompletePattern matchers.
622   // FIXME: This should be const.
623   if (!ComplexPatterns.empty()) {
624     OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
625     OS << "      unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
626     OS << "  switch (PatternNo) {\n";
627     OS << "  default: assert(0 && \"Invalid pattern # in table?\");\n";
628     for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
629       const ComplexPattern &P = *ComplexPatterns[i];
630       unsigned NumOps = P.getNumOperands();
631
632       if (P.hasProperty(SDNPHasChain))
633         ++NumOps;  // Get the chained node too.
634       
635       OS << "  case " << i << ":\n";
636       OS << "    Result.resize(Result.size()+" << NumOps << ");\n";
637       OS << "    return "  << P.getSelectFunc();
638
639       OS << "(Root, N";
640       for (unsigned i = 0; i != NumOps; ++i)
641         OS << ", Result[Result.size()-" << (NumOps-i) << ']';
642       OS << ");\n";
643     }
644     OS << "  }\n";
645     OS << "}\n\n";
646   }
647   
648   
649   // Emit SDNodeXForm handlers.
650   // FIXME: This should be const.
651   if (!NodeXForms.empty()) {
652     OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
653     OS << "  switch (XFormNo) {\n";
654     OS << "  default: assert(0 && \"Invalid xform # in table?\");\n";
655     
656     // FIXME: The node xform could take SDValue's instead of SDNode*'s.
657     for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) {
658       const CodeGenDAGPatterns::NodeXForm &Entry =
659         CGP.getSDNodeTransform(NodeXForms[i]);
660       
661       Record *SDNode = Entry.first;
662       const std::string &Code = Entry.second;
663       
664       OS << "  case " << i << ": {  ";
665       if (!OmitComments)
666         OS << "// " << NodeXForms[i]->getName();
667       OS << '\n';
668       
669       std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
670       if (ClassName == "SDNode")
671         OS << "    SDNode *N = V.getNode();\n";
672       else
673         OS << "    " << ClassName << " *N = cast<" << ClassName
674            << ">(V.getNode());\n";
675       OS << Code << "\n  }\n";
676     }
677     OS << "  }\n";
678     OS << "}\n\n";
679   }
680 }
681
682 static void BuildHistogram(const Matcher *M, std::vector<unsigned> &OpcodeFreq){
683   for (; M != 0; M = M->getNext()) {
684     // Count this node.
685     if (unsigned(M->getKind()) >= OpcodeFreq.size())
686       OpcodeFreq.resize(M->getKind()+1);
687     OpcodeFreq[M->getKind()]++;
688   
689     // Handle recursive nodes.
690     if (const ScopeMatcher *SM = dyn_cast<ScopeMatcher>(M)) {
691       for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i)
692         BuildHistogram(SM->getChild(i), OpcodeFreq);
693     } else if (const SwitchOpcodeMatcher *SOM = 
694                  dyn_cast<SwitchOpcodeMatcher>(M)) {
695       for (unsigned i = 0, e = SOM->getNumCases(); i != e; ++i)
696         BuildHistogram(SOM->getCaseMatcher(i), OpcodeFreq);
697     } else if (const SwitchTypeMatcher *STM = dyn_cast<SwitchTypeMatcher>(M)) {
698       for (unsigned i = 0, e = STM->getNumCases(); i != e; ++i)
699         BuildHistogram(STM->getCaseMatcher(i), OpcodeFreq);
700     }
701   }
702 }
703
704 void MatcherTableEmitter::EmitHistogram(const Matcher *M,
705                                         formatted_raw_ostream &OS) {
706   if (OmitComments)
707     return;
708   
709   std::vector<unsigned> OpcodeFreq;
710   BuildHistogram(M, OpcodeFreq);
711   
712   OS << "  // Opcode Histogram:\n";
713   for (unsigned i = 0, e = OpcodeFreq.size(); i != e; ++i) {
714     OS << "  // #";
715     switch ((Matcher::KindTy)i) {
716     case Matcher::Scope: OS << "OPC_Scope"; break; 
717     case Matcher::RecordNode: OS << "OPC_RecordNode"; break; 
718     case Matcher::RecordChild: OS << "OPC_RecordChild"; break;
719     case Matcher::RecordMemRef: OS << "OPC_RecordMemRef"; break;
720     case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break;
721     case Matcher::MoveChild: OS << "OPC_MoveChild"; break;
722     case Matcher::MoveParent: OS << "OPC_MoveParent"; break;
723     case Matcher::CheckSame: OS << "OPC_CheckSame"; break;
724     case Matcher::CheckPatternPredicate:
725       OS << "OPC_CheckPatternPredicate"; break;
726     case Matcher::CheckPredicate: OS << "OPC_CheckPredicate"; break;
727     case Matcher::CheckOpcode: OS << "OPC_CheckOpcode"; break;
728     case Matcher::SwitchOpcode: OS << "OPC_SwitchOpcode"; break;
729     case Matcher::CheckType: OS << "OPC_CheckType"; break;
730     case Matcher::SwitchType: OS << "OPC_SwitchType"; break;
731     case Matcher::CheckChildType: OS << "OPC_CheckChildType"; break;
732     case Matcher::CheckInteger: OS << "OPC_CheckInteger"; break;
733     case Matcher::CheckCondCode: OS << "OPC_CheckCondCode"; break;
734     case Matcher::CheckValueType: OS << "OPC_CheckValueType"; break;
735     case Matcher::CheckComplexPat: OS << "OPC_CheckComplexPat"; break;
736     case Matcher::CheckAndImm: OS << "OPC_CheckAndImm"; break;
737     case Matcher::CheckOrImm: OS << "OPC_CheckOrImm"; break;
738     case Matcher::CheckFoldableChainNode:
739       OS << "OPC_CheckFoldableChainNode"; break;
740     case Matcher::EmitInteger: OS << "OPC_EmitInteger"; break;
741     case Matcher::EmitStringInteger: OS << "OPC_EmitStringInteger"; break;
742     case Matcher::EmitRegister: OS << "OPC_EmitRegister"; break;
743     case Matcher::EmitConvertToTarget: OS << "OPC_EmitConvertToTarget"; break;
744     case Matcher::EmitMergeInputChains: OS << "OPC_EmitMergeInputChains"; break;
745     case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break;
746     case Matcher::EmitNode: OS << "OPC_EmitNode"; break;
747     case Matcher::MorphNodeTo: OS << "OPC_MorphNodeTo"; break;
748     case Matcher::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break;
749     case Matcher::MarkFlagResults: OS << "OPC_MarkFlagResults"; break;
750     case Matcher::CompleteMatch: OS << "OPC_CompleteMatch"; break;    
751     }
752     
753     OS.PadToColumn(40) << " = " << OpcodeFreq[i] << '\n';
754   }
755   OS << '\n';
756 }
757
758
759 void llvm::EmitMatcherTable(const Matcher *TheMatcher,
760                             const CodeGenDAGPatterns &CGP, raw_ostream &O) {
761   formatted_raw_ostream OS(O);
762   
763   OS << "// The main instruction selector code.\n";
764   OS << "SDNode *SelectCode(SDNode *N) {\n";
765
766   MatcherTableEmitter MatcherEmitter;
767
768   OS << "  // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
769   OS << "  #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
770   OS << "  static const unsigned char MatcherTable[] = {\n";
771   unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 5, 0, OS);
772   OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
773   
774   MatcherEmitter.EmitHistogram(TheMatcher, OS);
775   
776   OS << "  #undef TARGET_OPCODE\n";
777   OS << "  return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
778   OS << '\n';
779   
780   // Next up, emit the function for node and pattern predicates:
781   MatcherEmitter.EmitPredicateFunctions(CGP, OS);
782 }