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