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