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