enhance comment output to specify what recorded slot
[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   // Per opcode frequence count. 
46   std::vector<unsigned> Histogram;
47 public:
48   MatcherTableEmitter() {}
49
50   unsigned EmitMatcherList(const Matcher *N, unsigned Indent,
51                            unsigned StartIdx, formatted_raw_ostream &OS);
52   
53   void EmitPredicateFunctions(const CodeGenDAGPatterns &CGP,
54                               formatted_raw_ostream &OS);
55   
56   void EmitHistogram(formatted_raw_ostream &OS);
57 private:
58   unsigned EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
59                        formatted_raw_ostream &OS);
60   
61   unsigned getNodePredicate(StringRef PredName) {
62     unsigned &Entry = NodePredicateMap[PredName];
63     if (Entry == 0) {
64       NodePredicates.push_back(PredName.str());
65       Entry = NodePredicates.size();
66     }
67     return Entry-1;
68   }
69   unsigned getPatternPredicate(StringRef PredName) {
70     unsigned &Entry = PatternPredicateMap[PredName];
71     if (Entry == 0) {
72       PatternPredicates.push_back(PredName.str());
73       Entry = PatternPredicates.size();
74     }
75     return Entry-1;
76   }
77   
78   unsigned getComplexPat(const ComplexPattern &P) {
79     unsigned &Entry = ComplexPatternMap[&P];
80     if (Entry == 0) {
81       ComplexPatterns.push_back(&P);
82       Entry = ComplexPatterns.size();
83     }
84     return Entry-1;
85   }
86   
87   unsigned getNodeXFormID(Record *Rec) {
88     unsigned &Entry = NodeXFormMap[Rec];
89     if (Entry == 0) {
90       NodeXForms.push_back(Rec);
91       Entry = NodeXForms.size();
92     }
93     return Entry-1;
94   }
95   
96 };
97 } // end anonymous namespace.
98
99 static unsigned GetVBRSize(unsigned Val) {
100   if (Val <= 127) return 1;
101   
102   unsigned NumBytes = 0;
103   while (Val >= 128) {
104     Val >>= 7;
105     ++NumBytes;
106   }
107   return NumBytes+1;
108 }
109
110 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
111 /// bytes emitted.
112 static uint64_t EmitVBRValue(uint64_t Val, raw_ostream &OS) {
113   if (Val <= 127) {
114     OS << Val << ", ";
115     return 1;
116   }
117   
118   uint64_t InVal = Val;
119   unsigned NumBytes = 0;
120   while (Val >= 128) {
121     OS << (Val&127) << "|128,";
122     Val >>= 7;
123     ++NumBytes;
124   }
125   OS << Val;
126   if (!OmitComments)
127     OS << "/*" << InVal << "*/";
128   OS << ", ";
129   return NumBytes+1;
130 }
131
132 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
133 /// the number of bytes emitted.
134 unsigned MatcherTableEmitter::
135 EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
136             formatted_raw_ostream &OS) {
137   OS.PadToColumn(Indent*2);
138   
139   switch (N->getKind()) {
140   case Matcher::Scope: {
141     const ScopeMatcher *SM = cast<ScopeMatcher>(N);
142     assert(SM->getNext() == 0 && "Shouldn't have next after scope");
143     
144     unsigned StartIdx = CurrentIdx;
145     
146     // Emit all of the children.
147     for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
148       if (i == 0) {
149         OS << "OPC_Scope, ";
150         ++CurrentIdx;
151       } else  {
152         if (!OmitComments) {
153           OS << "/*" << CurrentIdx << "*/";
154           OS.PadToColumn(Indent*2) << "/*Scope*/ ";
155         } else
156           OS.PadToColumn(Indent*2);
157       }
158
159       // We need to encode the child and the offset of the failure code before
160       // emitting either of them.  Handle this by buffering the output into a
161       // string while we get the size.  Unfortunately, the offset of the
162       // children depends on the VBR size of the child, so for large children we
163       // have to iterate a bit.
164       SmallString<128> TmpBuf;
165       unsigned ChildSize = 0;
166       unsigned VBRSize = 0;
167       do {
168         VBRSize = GetVBRSize(ChildSize);
169         
170         TmpBuf.clear();
171         raw_svector_ostream OS(TmpBuf);
172         formatted_raw_ostream FOS(OS);
173         ChildSize = EmitMatcherList(SM->getChild(i), Indent+1,
174                                     CurrentIdx+VBRSize, FOS);
175       } while (GetVBRSize(ChildSize) != VBRSize);
176       
177       assert(ChildSize != 0 && "Should not have a zero-sized child!");
178     
179       CurrentIdx += EmitVBRValue(ChildSize, OS);
180       if (!OmitComments) {
181         OS << "/*->" << CurrentIdx+ChildSize << "*/";
182       
183         if (i == 0)
184           OS.PadToColumn(CommentIndent) << "// " << SM->getNumChildren()
185             << " children in Scope";
186       }
187       
188       OS << '\n' << TmpBuf.str();
189       CurrentIdx += ChildSize;
190     }
191     
192     // Emit a zero as a sentinel indicating end of 'Scope'.
193     if (!OmitComments)
194       OS << "/*" << CurrentIdx << "*/";
195     OS.PadToColumn(Indent*2) << "0, ";
196     if (!OmitComments)
197       OS << "/*End of Scope*/";
198     OS << '\n';
199     return CurrentIdx - StartIdx + 1;
200   }
201       
202   case Matcher::RecordNode:
203     OS << "OPC_RecordNode,";
204     if (!OmitComments)
205       OS.PadToColumn(CommentIndent) << "// #"
206         << cast<RecordMatcher>(N)->getResultNo() << " = "
207         << cast<RecordMatcher>(N)->getWhatFor();
208     OS << '\n';
209     return 1;
210
211   case Matcher::RecordChild:
212     OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo()
213        << ',';
214     if (!OmitComments)
215       OS.PadToColumn(CommentIndent) << "// #"
216         << cast<RecordChildMatcher>(N)->getResultNo() << " = "
217         << cast<RecordChildMatcher>(N)->getWhatFor();
218     OS << '\n';
219     return 1;
220       
221   case Matcher::RecordMemRef:
222     OS << "OPC_RecordMemRef,\n";
223     return 1;
224       
225   case Matcher::CaptureFlagInput:
226     OS << "OPC_CaptureFlagInput,\n";
227     return 1;
228       
229   case Matcher::MoveChild:
230     OS << "OPC_MoveChild, " << cast<MoveChildMatcher>(N)->getChildNo() << ",\n";
231     return 2;
232       
233   case Matcher::MoveParent:
234     OS << "OPC_MoveParent,\n";
235     return 1;
236       
237   case Matcher::CheckSame:
238     OS << "OPC_CheckSame, "
239        << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n";
240     return 2;
241
242   case Matcher::CheckPatternPredicate: {
243     StringRef Pred = cast<CheckPatternPredicateMatcher>(N)->getPredicate();
244     OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
245     if (!OmitComments)
246       OS.PadToColumn(CommentIndent) << "// " << Pred;
247     OS << '\n';
248     return 2;
249   }
250   case Matcher::CheckPredicate: {
251     StringRef Pred = cast<CheckPredicateMatcher>(N)->getPredicateName();
252     OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
253     if (!OmitComments)
254       OS.PadToColumn(CommentIndent) << "// " << Pred;
255     OS << '\n';
256     return 2;
257   }
258
259   case Matcher::CheckOpcode:
260     OS << "OPC_CheckOpcode, "
261        << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << ",\n";
262     return 2;
263       
264   case Matcher::SwitchOpcode:
265   case Matcher::SwitchType: {
266     unsigned StartIdx = CurrentIdx;
267     
268     unsigned NumCases;
269     if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
270       OS << "OPC_SwitchOpcode ";
271       NumCases = SOM->getNumCases();
272     } else {
273       OS << "OPC_SwitchType ";
274       NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
275     }
276
277     if (!OmitComments)
278       OS << "/*" << NumCases << " cases */";
279     OS << ", ";
280     ++CurrentIdx;
281     
282     // For each case we emit the size, then the opcode, then the matcher.
283     for (unsigned i = 0, e = NumCases; i != e; ++i) {
284       const Matcher *Child;
285       if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
286         Child = SOM->getCaseMatcher(i);
287       else
288         Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
289       
290       // We need to encode the opcode and the offset of the case code before
291       // emitting the case code.  Handle this by buffering the output into a
292       // string while we get the size.  Unfortunately, the offset of the
293       // children depends on the VBR size of the child, so for large children we
294       // have to iterate a bit.
295       SmallString<128> TmpBuf;
296       unsigned ChildSize = 0;
297       unsigned VBRSize = 0;
298       do {
299         VBRSize = GetVBRSize(ChildSize);
300         
301         TmpBuf.clear();
302         raw_svector_ostream OS(TmpBuf);
303         formatted_raw_ostream FOS(OS);
304         ChildSize = EmitMatcherList(Child, Indent+1, CurrentIdx+VBRSize+1, FOS);
305       } while (GetVBRSize(ChildSize) != VBRSize);
306       
307       assert(ChildSize != 0 && "Should not have a zero-sized child!");
308       
309       if (i != 0) {
310         OS.PadToColumn(Indent*2);
311         if (!OmitComments)
312         OS << (isa<SwitchOpcodeMatcher>(N) ?
313                    "/*SwitchOpcode*/ " : "/*SwitchType*/ ");
314       }
315       
316       // Emit the VBR.
317       CurrentIdx += EmitVBRValue(ChildSize, OS);
318       
319       OS << ' ';
320       if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
321         OS << SOM->getCaseOpcode(i).getEnumName();
322       else
323         OS << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i));
324       OS << ',';
325       
326       if (!OmitComments)
327         OS << "// ->" << CurrentIdx+ChildSize+1;
328       OS << '\n';
329       ++CurrentIdx;
330       OS << TmpBuf.str();
331       CurrentIdx += ChildSize;
332     }
333
334     // Emit the final zero to terminate the switch.
335     OS.PadToColumn(Indent*2) << "0, ";
336     if (!OmitComments)
337       OS << (isa<SwitchOpcodeMatcher>(N) ?
338              "// EndSwitchOpcode" : "// EndSwitchType");
339
340     OS << '\n';
341     ++CurrentIdx;
342     return CurrentIdx-StartIdx;
343   }
344
345  case Matcher::CheckType:
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 ComplexPattern &Pattern =
374       cast<CheckComplexPatMatcher>(N)->getPattern();
375     OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
376     if (!OmitComments) {
377       OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
378       OS << ':';
379       for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i)
380         OS << " #" << cast<CheckComplexPatMatcher>(N)->getFirstResult()+i;
381            
382       if (Pattern.hasProperty(SDNPHasChain))
383         OS << " + chain result";
384     }
385     OS << '\n';
386     return 2;
387   }
388       
389   case Matcher::CheckAndImm: {
390     OS << "OPC_CheckAndImm, ";
391     unsigned Bytes=1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
392     OS << '\n';
393     return Bytes;
394   }
395
396   case Matcher::CheckOrImm: {
397     OS << "OPC_CheckOrImm, ";
398     unsigned Bytes = 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
399     OS << '\n';
400     return Bytes;
401   }
402       
403   case Matcher::CheckFoldableChainNode:
404     OS << "OPC_CheckFoldableChainNode,\n";
405     return 1;
406       
407   case Matcher::EmitInteger: {
408     int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
409     OS << "OPC_EmitInteger, "
410        << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", ";
411     unsigned Bytes = 2+EmitVBRValue(Val, OS);
412     OS << '\n';
413     return Bytes;
414   }
415   case Matcher::EmitStringInteger: {
416     const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
417     // These should always fit into one byte.
418     OS << "OPC_EmitInteger, "
419       << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", "
420       << Val << ",\n";
421     return 3;
422   }
423       
424   case Matcher::EmitRegister:
425     OS << "OPC_EmitRegister, "
426        << getEnumName(cast<EmitRegisterMatcher>(N)->getVT()) << ", ";
427     if (Record *R = cast<EmitRegisterMatcher>(N)->getReg())
428       OS << getQualifiedName(R) << ",\n";
429     else {
430       OS << "0 ";
431       if (!OmitComments)
432         OS << "/*zero_reg*/";
433       OS << ",\n";
434     }
435     return 3;
436       
437   case Matcher::EmitConvertToTarget:
438     OS << "OPC_EmitConvertToTarget, "
439        << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
440     return 2;
441       
442   case Matcher::EmitMergeInputChains: {
443     const EmitMergeInputChainsMatcher *MN =
444       cast<EmitMergeInputChainsMatcher>(N);
445     OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
446     for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
447       OS << MN->getNode(i) << ", ";
448     OS << '\n';
449     return 2+MN->getNumNodes();
450   }
451   case Matcher::EmitCopyToReg:
452     OS << "OPC_EmitCopyToReg, "
453        << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
454        << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
455        << ",\n";
456     return 3;
457   case Matcher::EmitNodeXForm: {
458     const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
459     OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
460        << XF->getSlot() << ',';
461     if (!OmitComments)
462       OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName();
463     OS <<'\n';
464     return 3;
465   }
466       
467   case Matcher::EmitNode:
468   case Matcher::MorphNodeTo: {
469     const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
470     OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
471     OS << ", TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
472     
473     if (EN->hasChain())   OS << "|OPFL_Chain";
474     if (EN->hasInFlag())  OS << "|OPFL_FlagInput";
475     if (EN->hasOutFlag()) OS << "|OPFL_FlagOutput";
476     if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
477     if (EN->getNumFixedArityOperands() != -1)
478       OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
479     OS << ",\n";
480     
481     OS.PadToColumn(Indent*2+4) << EN->getNumVTs();
482     if (!OmitComments)
483       OS << "/*#VTs*/";
484     OS << ", ";
485     for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
486       OS << getEnumName(EN->getVT(i)) << ", ";
487
488     OS << EN->getNumOperands();
489     if (!OmitComments)
490       OS << "/*#Ops*/";
491     OS << ", ";
492     unsigned NumOperandBytes = 0;
493     for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
494       NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
495     
496     if (!OmitComments) {
497       // Print the result #'s for EmitNode.
498       if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
499         if (unsigned NumResults = EN->getNumVTs()) {
500           OS.PadToColumn(CommentIndent) << "// Results = ";
501           unsigned First = E->getFirstResultSlot();
502           for (unsigned i = 0; i != NumResults; ++i)
503             OS << "#" << First+i << " ";
504         }
505       }
506       OS << '\n';
507
508       if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
509         OS.PadToColumn(Indent*2) << "// Src: "
510           << *SNT->getPattern().getSrcPattern() << '\n';
511         OS.PadToColumn(Indent*2) << "// Dst: "
512           << *SNT->getPattern().getDstPattern() << '\n';
513       }
514     } else
515       OS << '\n';
516     
517     return 6+EN->getNumVTs()+NumOperandBytes;
518   }
519   case Matcher::MarkFlagResults: {
520     const MarkFlagResultsMatcher *CFR = cast<MarkFlagResultsMatcher>(N);
521     OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
522     unsigned NumOperandBytes = 0;
523     for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
524       NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
525     OS << '\n';
526     return 2+NumOperandBytes;
527   }
528   case Matcher::CompleteMatch: {
529     const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
530     OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
531     unsigned NumResultBytes = 0;
532     for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
533       NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
534     OS << '\n';
535     if (!OmitComments) {
536       OS.PadToColumn(Indent*2) << "// Src: "
537         << *CM->getPattern().getSrcPattern() << '\n';
538       OS.PadToColumn(Indent*2) << "// Dst: "
539         << *CM->getPattern().getDstPattern();
540     }
541     OS << '\n';
542     return 2 + NumResultBytes;
543   }
544   }
545   assert(0 && "Unreachable");
546   return 0;
547 }
548
549 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
550 unsigned MatcherTableEmitter::
551 EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
552                 formatted_raw_ostream &OS) {
553   unsigned Size = 0;
554   while (N) {
555     if (unsigned(N->getKind()) >= Histogram.size())
556       Histogram.resize(N->getKind()+1);
557     Histogram[N->getKind()]++;
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 void MatcherTableEmitter::EmitHistogram(formatted_raw_ostream &OS) {
683   if (OmitComments)
684     return;
685   OS << "  // Opcode Histogram:\n";
686   for (unsigned i = 0, e = Histogram.size(); i != e; ++i) {
687     OS << "  // #";
688     switch ((Matcher::KindTy)i) {
689     case Matcher::Scope: OS << "OPC_Scope"; break; 
690     case Matcher::RecordNode: OS << "OPC_RecordNode"; break; 
691     case Matcher::RecordChild: OS << "OPC_RecordChild"; break;
692     case Matcher::RecordMemRef: OS << "OPC_RecordMemRef"; break;
693     case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break;
694     case Matcher::MoveChild: OS << "OPC_MoveChild"; break;
695     case Matcher::MoveParent: OS << "OPC_MoveParent"; break;
696     case Matcher::CheckSame: OS << "OPC_CheckSame"; break;
697     case Matcher::CheckPatternPredicate:
698       OS << "OPC_CheckPatternPredicate"; break;
699     case Matcher::CheckPredicate: OS << "OPC_CheckPredicate"; break;
700     case Matcher::CheckOpcode: OS << "OPC_CheckOpcode"; break;
701     case Matcher::SwitchOpcode: OS << "OPC_SwitchOpcode"; break;
702     case Matcher::CheckType: OS << "OPC_CheckType"; break;
703     case Matcher::SwitchType: OS << "OPC_SwitchType"; break;
704     case Matcher::CheckChildType: OS << "OPC_CheckChildType"; break;
705     case Matcher::CheckInteger: OS << "OPC_CheckInteger"; break;
706     case Matcher::CheckCondCode: OS << "OPC_CheckCondCode"; break;
707     case Matcher::CheckValueType: OS << "OPC_CheckValueType"; break;
708     case Matcher::CheckComplexPat: OS << "OPC_CheckComplexPat"; break;
709     case Matcher::CheckAndImm: OS << "OPC_CheckAndImm"; break;
710     case Matcher::CheckOrImm: OS << "OPC_CheckOrImm"; break;
711     case Matcher::CheckFoldableChainNode:
712       OS << "OPC_CheckFoldableChainNode"; break;
713     case Matcher::EmitInteger: OS << "OPC_EmitInteger"; break;
714     case Matcher::EmitStringInteger: OS << "OPC_EmitStringInteger"; break;
715     case Matcher::EmitRegister: OS << "OPC_EmitRegister"; break;
716     case Matcher::EmitConvertToTarget: OS << "OPC_EmitConvertToTarget"; break;
717     case Matcher::EmitMergeInputChains: OS << "OPC_EmitMergeInputChains"; break;
718     case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break;
719     case Matcher::EmitNode: OS << "OPC_EmitNode"; break;
720     case Matcher::MorphNodeTo: OS << "OPC_MorphNodeTo"; break;
721     case Matcher::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break;
722     case Matcher::MarkFlagResults: OS << "OPC_MarkFlagResults"; break;
723     case Matcher::CompleteMatch: OS << "OPC_CompleteMatch"; break;    
724     }
725     
726     OS.PadToColumn(40) << " = " << Histogram[i] << '\n';
727   }
728   OS << '\n';
729 }
730
731
732 void llvm::EmitMatcherTable(const Matcher *TheMatcher,
733                             const CodeGenDAGPatterns &CGP, raw_ostream &O) {
734   formatted_raw_ostream OS(O);
735   
736   OS << "// The main instruction selector code.\n";
737   OS << "SDNode *SelectCode(SDNode *N) {\n";
738
739   MatcherTableEmitter MatcherEmitter;
740
741   OS << "  // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
742   OS << "  #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
743   OS << "  static const unsigned char MatcherTable[] = {\n";
744   unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 5, 0, OS);
745   OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
746   
747   MatcherEmitter.EmitHistogram(OS);
748   
749   OS << "  #undef TARGET_OPCODE\n";
750   OS << "  return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
751   OS << '\n';
752   
753   // Next up, emit the function for node and pattern predicates:
754   MatcherEmitter.EmitPredicateFunctions(CGP, OS);
755 }