DAGISelMatcherEmitter.cpp revision 5d3569e93ce31052a55d6e64b7153d055d60d8e8
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"
22using namespace llvm;
23
24enum {
25  CommentIndent = 30
26};
27
28// To reduce generated source code size.
29static cl::opt<bool>
30OmitComments("omit-comments", cl::desc("Do not generate comments"),
31             cl::init(false));
32
33namespace {
34class 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
45public:
46  MatcherTableEmitter() {}
47
48  unsigned EmitMatcherList(const Matcher *N, unsigned Indent,
49                           unsigned StartIdx, formatted_raw_ostream &OS);
50
51  void EmitPredicateFunctions(const CodeGenDAGPatterns &CGP,
52                              formatted_raw_ostream &OS);
53
54  void EmitHistogram(const Matcher *N, formatted_raw_ostream &OS);
55private:
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
97static 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.
110static 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.
132unsigned MatcherTableEmitter::
133EmitMatcher(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    OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
453    for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
454      OS << MN->getNode(i) << ", ";
455    OS << '\n';
456    return 2+MN->getNumNodes();
457  }
458  case Matcher::EmitCopyToReg:
459    OS << "OPC_EmitCopyToReg, "
460       << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
461       << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
462       << ",\n";
463    return 3;
464  case Matcher::EmitNodeXForm: {
465    const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
466    OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
467       << XF->getSlot() << ',';
468    if (!OmitComments)
469      OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName();
470    OS <<'\n';
471    return 3;
472  }
473
474  case Matcher::EmitNode:
475  case Matcher::MorphNodeTo: {
476    const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
477    OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
478    OS << ", TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
479
480    if (EN->hasChain())   OS << "|OPFL_Chain";
481    if (EN->hasInFlag())  OS << "|OPFL_FlagInput";
482    if (EN->hasOutFlag()) OS << "|OPFL_FlagOutput";
483    if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
484    if (EN->getNumFixedArityOperands() != -1)
485      OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
486    OS << ",\n";
487
488    OS.PadToColumn(Indent*2+4) << EN->getNumVTs();
489    if (!OmitComments)
490      OS << "/*#VTs*/";
491    OS << ", ";
492    for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
493      OS << getEnumName(EN->getVT(i)) << ", ";
494
495    OS << EN->getNumOperands();
496    if (!OmitComments)
497      OS << "/*#Ops*/";
498    OS << ", ";
499    unsigned NumOperandBytes = 0;
500    for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
501      NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
502
503    if (!OmitComments) {
504      // Print the result #'s for EmitNode.
505      if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
506        if (unsigned NumResults = EN->getNumVTs()) {
507          OS.PadToColumn(CommentIndent) << "// Results = ";
508          unsigned First = E->getFirstResultSlot();
509          for (unsigned i = 0; i != NumResults; ++i)
510            OS << "#" << First+i << " ";
511        }
512      }
513      OS << '\n';
514
515      if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
516        OS.PadToColumn(Indent*2) << "// Src: "
517          << *SNT->getPattern().getSrcPattern() << '\n';
518        OS.PadToColumn(Indent*2) << "// Dst: "
519          << *SNT->getPattern().getDstPattern() << '\n';
520      }
521    } else
522      OS << '\n';
523
524    return 6+EN->getNumVTs()+NumOperandBytes;
525  }
526  case Matcher::MarkFlagResults: {
527    const MarkFlagResultsMatcher *CFR = cast<MarkFlagResultsMatcher>(N);
528    OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
529    unsigned NumOperandBytes = 0;
530    for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
531      NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
532    OS << '\n';
533    return 2+NumOperandBytes;
534  }
535  case Matcher::CompleteMatch: {
536    const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
537    OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
538    unsigned NumResultBytes = 0;
539    for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
540      NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
541    OS << '\n';
542    if (!OmitComments) {
543      OS.PadToColumn(Indent*2) << "// Src: "
544        << *CM->getPattern().getSrcPattern() << '\n';
545      OS.PadToColumn(Indent*2) << "// Dst: "
546        << *CM->getPattern().getDstPattern();
547    }
548    OS << '\n';
549    return 2 + NumResultBytes;
550  }
551  }
552  assert(0 && "Unreachable");
553  return 0;
554}
555
556/// EmitMatcherList - Emit the bytes for the specified matcher subtree.
557unsigned MatcherTableEmitter::
558EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
559                formatted_raw_ostream &OS) {
560  unsigned Size = 0;
561  while (N) {
562    if (!OmitComments)
563      OS << "/*" << CurrentIdx << "*/";
564    unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
565    Size += MatcherSize;
566    CurrentIdx += MatcherSize;
567
568    // If there are other nodes in this list, iterate to them, otherwise we're
569    // done.
570    N = N->getNext();
571  }
572  return Size;
573}
574
575void MatcherTableEmitter::EmitPredicateFunctions(const CodeGenDAGPatterns &CGP,
576                                                 formatted_raw_ostream &OS) {
577  // Emit pattern predicates.
578  if (!PatternPredicates.empty()) {
579    OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
580    OS << "  switch (PredNo) {\n";
581    OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
582    for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
583      OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n";
584    OS << "  }\n";
585    OS << "}\n\n";
586  }
587
588  // Emit Node predicates.
589  // FIXME: Annoyingly, these are stored by name, which we never even emit. Yay?
590  StringMap<TreePattern*> PFsByName;
591
592  for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
593       I != E; ++I)
594    PFsByName[I->first->getName()] = I->second;
595
596  if (!NodePredicates.empty()) {
597    OS << "bool CheckNodePredicate(SDNode *Node, unsigned PredNo) const {\n";
598    OS << "  switch (PredNo) {\n";
599    OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
600    for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i) {
601      // FIXME: Storing this by name is horrible.
602      TreePattern *P =PFsByName[NodePredicates[i].substr(strlen("Predicate_"))];
603      assert(P && "Unknown name?");
604
605      // Emit the predicate code corresponding to this pattern.
606      std::string Code = P->getRecord()->getValueAsCode("Predicate");
607      assert(!Code.empty() && "No code in this predicate");
608      OS << "  case " << i << ": { // " << NodePredicates[i] << '\n';
609      std::string ClassName;
610      if (P->getOnlyTree()->isLeaf())
611        ClassName = "SDNode";
612      else
613        ClassName =
614          CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
615      if (ClassName == "SDNode")
616        OS << "    SDNode *N = Node;\n";
617      else
618        OS << "    " << ClassName << "*N = cast<" << ClassName << ">(Node);\n";
619      OS << Code << "\n  }\n";
620    }
621    OS << "  }\n";
622    OS << "}\n\n";
623  }
624
625  // Emit CompletePattern matchers.
626  // FIXME: This should be const.
627  if (!ComplexPatterns.empty()) {
628    OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
629    OS << "      unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
630    OS << "  switch (PatternNo) {\n";
631    OS << "  default: assert(0 && \"Invalid pattern # in table?\");\n";
632    for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
633      const ComplexPattern &P = *ComplexPatterns[i];
634      unsigned NumOps = P.getNumOperands();
635
636      if (P.hasProperty(SDNPHasChain))
637        ++NumOps;  // Get the chained node too.
638
639      OS << "  case " << i << ":\n";
640      OS << "    Result.resize(Result.size()+" << NumOps << ");\n";
641      OS << "    return "  << P.getSelectFunc();
642
643      OS << "(Root, N";
644      for (unsigned i = 0; i != NumOps; ++i)
645        OS << ", Result[Result.size()-" << (NumOps-i) << ']';
646      OS << ");\n";
647    }
648    OS << "  }\n";
649    OS << "}\n\n";
650  }
651
652
653  // Emit SDNodeXForm handlers.
654  // FIXME: This should be const.
655  if (!NodeXForms.empty()) {
656    OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
657    OS << "  switch (XFormNo) {\n";
658    OS << "  default: assert(0 && \"Invalid xform # in table?\");\n";
659
660    // FIXME: The node xform could take SDValue's instead of SDNode*'s.
661    for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) {
662      const CodeGenDAGPatterns::NodeXForm &Entry =
663        CGP.getSDNodeTransform(NodeXForms[i]);
664
665      Record *SDNode = Entry.first;
666      const std::string &Code = Entry.second;
667
668      OS << "  case " << i << ": {  ";
669      if (!OmitComments)
670        OS << "// " << NodeXForms[i]->getName();
671      OS << '\n';
672
673      std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
674      if (ClassName == "SDNode")
675        OS << "    SDNode *N = V.getNode();\n";
676      else
677        OS << "    " << ClassName << " *N = cast<" << ClassName
678           << ">(V.getNode());\n";
679      OS << Code << "\n  }\n";
680    }
681    OS << "  }\n";
682    OS << "}\n\n";
683  }
684}
685
686static void BuildHistogram(const Matcher *M, std::vector<unsigned> &OpcodeFreq){
687  for (; M != 0; M = M->getNext()) {
688    // Count this node.
689    if (unsigned(M->getKind()) >= OpcodeFreq.size())
690      OpcodeFreq.resize(M->getKind()+1);
691    OpcodeFreq[M->getKind()]++;
692
693    // Handle recursive nodes.
694    if (const ScopeMatcher *SM = dyn_cast<ScopeMatcher>(M)) {
695      for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i)
696        BuildHistogram(SM->getChild(i), OpcodeFreq);
697    } else if (const SwitchOpcodeMatcher *SOM =
698                 dyn_cast<SwitchOpcodeMatcher>(M)) {
699      for (unsigned i = 0, e = SOM->getNumCases(); i != e; ++i)
700        BuildHistogram(SOM->getCaseMatcher(i), OpcodeFreq);
701    } else if (const SwitchTypeMatcher *STM = dyn_cast<SwitchTypeMatcher>(M)) {
702      for (unsigned i = 0, e = STM->getNumCases(); i != e; ++i)
703        BuildHistogram(STM->getCaseMatcher(i), OpcodeFreq);
704    }
705  }
706}
707
708void MatcherTableEmitter::EmitHistogram(const Matcher *M,
709                                        formatted_raw_ostream &OS) {
710  if (OmitComments)
711    return;
712
713  std::vector<unsigned> OpcodeFreq;
714  BuildHistogram(M, OpcodeFreq);
715
716  OS << "  // Opcode Histogram:\n";
717  for (unsigned i = 0, e = OpcodeFreq.size(); i != e; ++i) {
718    OS << "  // #";
719    switch ((Matcher::KindTy)i) {
720    case Matcher::Scope: OS << "OPC_Scope"; break;
721    case Matcher::RecordNode: OS << "OPC_RecordNode"; break;
722    case Matcher::RecordChild: OS << "OPC_RecordChild"; break;
723    case Matcher::RecordMemRef: OS << "OPC_RecordMemRef"; break;
724    case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break;
725    case Matcher::MoveChild: OS << "OPC_MoveChild"; break;
726    case Matcher::MoveParent: OS << "OPC_MoveParent"; break;
727    case Matcher::CheckSame: OS << "OPC_CheckSame"; break;
728    case Matcher::CheckPatternPredicate:
729      OS << "OPC_CheckPatternPredicate"; break;
730    case Matcher::CheckPredicate: OS << "OPC_CheckPredicate"; break;
731    case Matcher::CheckOpcode: OS << "OPC_CheckOpcode"; break;
732    case Matcher::SwitchOpcode: OS << "OPC_SwitchOpcode"; break;
733    case Matcher::CheckType: OS << "OPC_CheckType"; break;
734    case Matcher::SwitchType: OS << "OPC_SwitchType"; break;
735    case Matcher::CheckChildType: OS << "OPC_CheckChildType"; break;
736    case Matcher::CheckInteger: OS << "OPC_CheckInteger"; break;
737    case Matcher::CheckCondCode: OS << "OPC_CheckCondCode"; break;
738    case Matcher::CheckValueType: OS << "OPC_CheckValueType"; break;
739    case Matcher::CheckComplexPat: OS << "OPC_CheckComplexPat"; break;
740    case Matcher::CheckAndImm: OS << "OPC_CheckAndImm"; break;
741    case Matcher::CheckOrImm: OS << "OPC_CheckOrImm"; break;
742    case Matcher::CheckFoldableChainNode:
743      OS << "OPC_CheckFoldableChainNode"; break;
744    case Matcher::EmitInteger: OS << "OPC_EmitInteger"; break;
745    case Matcher::EmitStringInteger: OS << "OPC_EmitStringInteger"; break;
746    case Matcher::EmitRegister: OS << "OPC_EmitRegister"; break;
747    case Matcher::EmitConvertToTarget: OS << "OPC_EmitConvertToTarget"; break;
748    case Matcher::EmitMergeInputChains: OS << "OPC_EmitMergeInputChains"; break;
749    case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break;
750    case Matcher::EmitNode: OS << "OPC_EmitNode"; break;
751    case Matcher::MorphNodeTo: OS << "OPC_MorphNodeTo"; break;
752    case Matcher::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break;
753    case Matcher::MarkFlagResults: OS << "OPC_MarkFlagResults"; break;
754    case Matcher::CompleteMatch: OS << "OPC_CompleteMatch"; break;
755    }
756
757    OS.PadToColumn(40) << " = " << OpcodeFreq[i] << '\n';
758  }
759  OS << '\n';
760}
761
762
763void llvm::EmitMatcherTable(const Matcher *TheMatcher,
764                            const CodeGenDAGPatterns &CGP, raw_ostream &O) {
765  formatted_raw_ostream OS(O);
766
767  OS << "// The main instruction selector code.\n";
768  OS << "SDNode *SelectCode(SDNode *N) {\n";
769
770  MatcherTableEmitter MatcherEmitter;
771
772  OS << "  // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
773  OS << "  #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
774  OS << "  static const unsigned char MatcherTable[] = {\n";
775  unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 5, 0, OS);
776  OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
777
778  MatcherEmitter.EmitHistogram(TheMatcher, OS);
779
780  OS << "  #undef TARGET_OPCODE\n";
781  OS << "  return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
782  OS << '\n';
783
784  // Next up, emit the function for node and pattern predicates:
785  MatcherEmitter.EmitPredicateFunctions(CGP, OS);
786}
787