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