]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/utils/TableGen/DAGISelMatcherEmitter.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 "CodeGenDAGPatterns.h"
15 #include "DAGISelMatcher.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/TinyPtrVector.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/TableGen/Error.h"
26 #include "llvm/TableGen/Record.h"
27 using namespace llvm;
28
29 enum {
30   IndexWidth = 6,
31   FullIndexWidth = IndexWidth + 4,
32   HistOpcWidth = 40,
33 };
34
35 cl::OptionCategory DAGISelCat("Options for -gen-dag-isel");
36
37 // To reduce generated source code size.
38 static cl::opt<bool> OmitComments("omit-comments",
39                                   cl::desc("Do not generate comments"),
40                                   cl::init(false), cl::cat(DAGISelCat));
41
42 static cl::opt<bool> InstrumentCoverage(
43     "instrument-coverage",
44     cl::desc("Generates tables to help identify patterns matched"),
45     cl::init(false), cl::cat(DAGISelCat));
46
47 namespace {
48 class MatcherTableEmitter {
49   const CodeGenDAGPatterns &CGP;
50
51   DenseMap<TreePattern *, unsigned> NodePredicateMap;
52   std::vector<TreePredicateFn> NodePredicates;
53   std::vector<TreePredicateFn> NodePredicatesWithOperands;
54
55   // We de-duplicate the predicates by code string, and use this map to track
56   // all the patterns with "identical" predicates.
57   StringMap<TinyPtrVector<TreePattern *>> NodePredicatesByCodeToRun;
58
59   StringMap<unsigned> PatternPredicateMap;
60   std::vector<std::string> PatternPredicates;
61
62   DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
63   std::vector<const ComplexPattern*> ComplexPatterns;
64
65
66   DenseMap<Record*, unsigned> NodeXFormMap;
67   std::vector<Record*> NodeXForms;
68
69   std::vector<std::string> VecIncludeStrings;
70   MapVector<std::string, unsigned, StringMap<unsigned> > VecPatterns;
71
72   unsigned getPatternIdxFromTable(std::string &&P, std::string &&include_loc) {
73     const auto It = VecPatterns.find(P);
74     if (It == VecPatterns.end()) {
75       VecPatterns.insert(make_pair(std::move(P), VecPatterns.size()));
76       VecIncludeStrings.push_back(std::move(include_loc));
77       return VecIncludeStrings.size() - 1;
78     }
79     return It->second;
80   }
81
82 public:
83   MatcherTableEmitter(const CodeGenDAGPatterns &cgp)
84     : CGP(cgp) {}
85
86   unsigned EmitMatcherList(const Matcher *N, unsigned Indent,
87                            unsigned StartIdx, raw_ostream &OS);
88
89   void EmitPredicateFunctions(raw_ostream &OS);
90
91   void EmitHistogram(const Matcher *N, raw_ostream &OS);
92
93   void EmitPatternMatchTable(raw_ostream &OS);
94
95 private:
96   void EmitNodePredicatesFunction(const std::vector<TreePredicateFn> &Preds,
97                                   StringRef Decl, raw_ostream &OS);
98
99   unsigned EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
100                        raw_ostream &OS);
101
102   unsigned getNodePredicate(TreePredicateFn Pred) {
103     TreePattern *TP = Pred.getOrigPatFragRecord();
104     unsigned &Entry = NodePredicateMap[TP];
105     if (Entry == 0) {
106       TinyPtrVector<TreePattern *> &SameCodePreds =
107           NodePredicatesByCodeToRun[Pred.getCodeToRunOnSDNode()];
108       if (SameCodePreds.empty()) {
109         // We've never seen a predicate with the same code: allocate an entry.
110         if (Pred.usesOperands()) {
111           NodePredicatesWithOperands.push_back(Pred);
112           Entry = NodePredicatesWithOperands.size();
113         } else {
114           NodePredicates.push_back(Pred);
115           Entry = NodePredicates.size();
116         }
117       } else {
118         // We did see an identical predicate: re-use it.
119         Entry = NodePredicateMap[SameCodePreds.front()];
120         assert(Entry != 0);
121         assert(TreePredicateFn(SameCodePreds.front()).usesOperands() ==
122                Pred.usesOperands() &&
123                "PatFrags with some code must have same usesOperands setting");
124       }
125       // In both cases, we've never seen this particular predicate before, so
126       // mark it in the list of predicates sharing the same code.
127       SameCodePreds.push_back(TP);
128     }
129     return Entry-1;
130   }
131
132   unsigned getPatternPredicate(StringRef PredName) {
133     unsigned &Entry = PatternPredicateMap[PredName];
134     if (Entry == 0) {
135       PatternPredicates.push_back(PredName.str());
136       Entry = PatternPredicates.size();
137     }
138     return Entry-1;
139   }
140   unsigned getComplexPat(const ComplexPattern &P) {
141     unsigned &Entry = ComplexPatternMap[&P];
142     if (Entry == 0) {
143       ComplexPatterns.push_back(&P);
144       Entry = ComplexPatterns.size();
145     }
146     return Entry-1;
147   }
148
149   unsigned getNodeXFormID(Record *Rec) {
150     unsigned &Entry = NodeXFormMap[Rec];
151     if (Entry == 0) {
152       NodeXForms.push_back(Rec);
153       Entry = NodeXForms.size();
154     }
155     return Entry-1;
156   }
157
158 };
159 } // end anonymous namespace.
160
161 static std::string GetPatFromTreePatternNode(const TreePatternNode *N) {
162   std::string str;
163   raw_string_ostream Stream(str);
164   Stream << *N;
165   Stream.str();
166   return str;
167 }
168
169 static unsigned GetVBRSize(unsigned Val) {
170   if (Val <= 127) return 1;
171
172   unsigned NumBytes = 0;
173   while (Val >= 128) {
174     Val >>= 7;
175     ++NumBytes;
176   }
177   return NumBytes+1;
178 }
179
180 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
181 /// bytes emitted.
182 static uint64_t EmitVBRValue(uint64_t Val, raw_ostream &OS) {
183   if (Val <= 127) {
184     OS << Val << ", ";
185     return 1;
186   }
187
188   uint64_t InVal = Val;
189   unsigned NumBytes = 0;
190   while (Val >= 128) {
191     OS << (Val&127) << "|128,";
192     Val >>= 7;
193     ++NumBytes;
194   }
195   OS << Val;
196   if (!OmitComments)
197     OS << "/*" << InVal << "*/";
198   OS << ", ";
199   return NumBytes+1;
200 }
201
202 // This is expensive and slow.
203 static std::string getIncludePath(const Record *R) {
204   std::string str;
205   raw_string_ostream Stream(str);
206   auto Locs = R->getLoc();
207   SMLoc L;
208   if (Locs.size() > 1) {
209     // Get where the pattern prototype was instantiated
210     L = Locs[1];
211   } else if (Locs.size() == 1) {
212     L = Locs[0];
213   }
214   unsigned CurBuf = SrcMgr.FindBufferContainingLoc(L);
215   assert(CurBuf && "Invalid or unspecified location!");
216
217   Stream << SrcMgr.getBufferInfo(CurBuf).Buffer->getBufferIdentifier() << ":"
218          << SrcMgr.FindLineNumber(L, CurBuf);
219   Stream.str();
220   return str;
221 }
222
223 static void BeginEmitFunction(raw_ostream &OS, StringRef RetType,
224                               StringRef Decl, bool AddOverride) {
225   OS << "#ifdef GET_DAGISEL_DECL\n";
226   OS << RetType << ' ' << Decl;
227   if (AddOverride)
228     OS << " override";
229   OS << ";\n"
230         "#endif\n"
231         "#if defined(GET_DAGISEL_BODY) || DAGISEL_INLINE\n";
232   OS << RetType << " DAGISEL_CLASS_COLONCOLON " << Decl << "\n";
233   if (AddOverride) {
234     OS << "#if DAGISEL_INLINE\n"
235           "  override\n"
236           "#endif\n";
237   }
238 }
239
240 static void EndEmitFunction(raw_ostream &OS) {
241   OS << "#endif // GET_DAGISEL_BODY\n\n";
242 }
243
244 void MatcherTableEmitter::EmitPatternMatchTable(raw_ostream &OS) {
245
246   assert(isUInt<16>(VecPatterns.size()) &&
247          "Using only 16 bits to encode offset into Pattern Table");
248   assert(VecPatterns.size() == VecIncludeStrings.size() &&
249          "The sizes of Pattern and include vectors should be the same");
250
251   BeginEmitFunction(OS, "StringRef", "getPatternForIndex(unsigned Index)",
252                     true/*AddOverride*/);
253   OS << "{\n";
254   OS << "static const char * PATTERN_MATCH_TABLE[] = {\n";
255
256   for (const auto &It : VecPatterns) {
257     OS << "\"" << It.first << "\",\n";
258   }
259
260   OS << "\n};";
261   OS << "\nreturn StringRef(PATTERN_MATCH_TABLE[Index]);";
262   OS << "\n}";
263   EndEmitFunction(OS);
264
265   BeginEmitFunction(OS, "StringRef", "getIncludePathForIndex(unsigned Index)",
266                     true/*AddOverride*/);
267   OS << "{\n";
268   OS << "static const char * INCLUDE_PATH_TABLE[] = {\n";
269
270   for (const auto &It : VecIncludeStrings) {
271     OS << "\"" << It << "\",\n";
272   }
273
274   OS << "\n};";
275   OS << "\nreturn StringRef(INCLUDE_PATH_TABLE[Index]);";
276   OS << "\n}";
277   EndEmitFunction(OS);
278 }
279
280 /// EmitMatcher - Emit bytes for the specified matcher and return
281 /// the number of bytes emitted.
282 unsigned MatcherTableEmitter::
283 EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
284             raw_ostream &OS) {
285   OS.indent(Indent*2);
286
287   switch (N->getKind()) {
288   case Matcher::Scope: {
289     const ScopeMatcher *SM = cast<ScopeMatcher>(N);
290     assert(SM->getNext() == nullptr && "Shouldn't have next after scope");
291
292     unsigned StartIdx = CurrentIdx;
293
294     // Emit all of the children.
295     for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
296       if (i == 0) {
297         OS << "OPC_Scope, ";
298         ++CurrentIdx;
299       } else  {
300         if (!OmitComments) {
301           OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
302           OS.indent(Indent*2) << "/*Scope*/ ";
303         } else
304           OS.indent(Indent*2);
305       }
306
307       // We need to encode the child and the offset of the failure code before
308       // emitting either of them.  Handle this by buffering the output into a
309       // string while we get the size.  Unfortunately, the offset of the
310       // children depends on the VBR size of the child, so for large children we
311       // have to iterate a bit.
312       SmallString<128> TmpBuf;
313       unsigned ChildSize = 0;
314       unsigned VBRSize = 0;
315       do {
316         VBRSize = GetVBRSize(ChildSize);
317
318         TmpBuf.clear();
319         raw_svector_ostream OS(TmpBuf);
320         ChildSize = EmitMatcherList(SM->getChild(i), Indent+1,
321                                     CurrentIdx+VBRSize, OS);
322       } while (GetVBRSize(ChildSize) != VBRSize);
323
324       assert(ChildSize != 0 && "Should not have a zero-sized child!");
325
326       CurrentIdx += EmitVBRValue(ChildSize, OS);
327       if (!OmitComments) {
328         OS << "/*->" << CurrentIdx+ChildSize << "*/";
329
330         if (i == 0)
331           OS << " // " << SM->getNumChildren() << " children in Scope";
332       }
333
334       OS << '\n' << TmpBuf;
335       CurrentIdx += ChildSize;
336     }
337
338     // Emit a zero as a sentinel indicating end of 'Scope'.
339     if (!OmitComments)
340       OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
341     OS.indent(Indent*2) << "0, ";
342     if (!OmitComments)
343       OS << "/*End of Scope*/";
344     OS << '\n';
345     return CurrentIdx - StartIdx + 1;
346   }
347
348   case Matcher::RecordNode:
349     OS << "OPC_RecordNode,";
350     if (!OmitComments)
351       OS << " // #"
352          << cast<RecordMatcher>(N)->getResultNo() << " = "
353          << cast<RecordMatcher>(N)->getWhatFor();
354     OS << '\n';
355     return 1;
356
357   case Matcher::RecordChild:
358     OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo()
359        << ',';
360     if (!OmitComments)
361       OS << " // #"
362          << cast<RecordChildMatcher>(N)->getResultNo() << " = "
363          << cast<RecordChildMatcher>(N)->getWhatFor();
364     OS << '\n';
365     return 1;
366
367   case Matcher::RecordMemRef:
368     OS << "OPC_RecordMemRef,\n";
369     return 1;
370
371   case Matcher::CaptureGlueInput:
372     OS << "OPC_CaptureGlueInput,\n";
373     return 1;
374
375   case Matcher::MoveChild: {
376     const auto *MCM = cast<MoveChildMatcher>(N);
377
378     OS << "OPC_MoveChild";
379     // Handle the specialized forms.
380     if (MCM->getChildNo() >= 8)
381       OS << ", ";
382     OS << MCM->getChildNo() << ",\n";
383     return (MCM->getChildNo() >= 8) ? 2 : 1;
384   }
385
386   case Matcher::MoveParent:
387     OS << "OPC_MoveParent,\n";
388     return 1;
389
390   case Matcher::CheckSame:
391     OS << "OPC_CheckSame, "
392        << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n";
393     return 2;
394
395   case Matcher::CheckChildSame:
396     OS << "OPC_CheckChild"
397        << cast<CheckChildSameMatcher>(N)->getChildNo() << "Same, "
398        << cast<CheckChildSameMatcher>(N)->getMatchNumber() << ",\n";
399     return 2;
400
401   case Matcher::CheckPatternPredicate: {
402     StringRef Pred =cast<CheckPatternPredicateMatcher>(N)->getPredicate();
403     OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
404     if (!OmitComments)
405       OS << " // " << Pred;
406     OS << '\n';
407     return 2;
408   }
409   case Matcher::CheckPredicate: {
410     TreePredicateFn Pred = cast<CheckPredicateMatcher>(N)->getPredicate();
411     unsigned OperandBytes = 0;
412
413     if (Pred.usesOperands()) {
414       unsigned NumOps = cast<CheckPredicateMatcher>(N)->getNumOperands();
415       OS << "OPC_CheckPredicateWithOperands, " << NumOps << "/*#Ops*/, ";
416       for (unsigned i = 0; i < NumOps; ++i)
417         OS << cast<CheckPredicateMatcher>(N)->getOperandNo(i) << ", ";
418       OperandBytes = 1 + NumOps;
419     } else {
420       OS << "OPC_CheckPredicate, ";
421     }
422
423     OS << getNodePredicate(Pred) << ',';
424     if (!OmitComments)
425       OS << " // " << Pred.getFnName();
426     OS << '\n';
427     return 2 + OperandBytes;
428   }
429
430   case Matcher::CheckOpcode:
431     OS << "OPC_CheckOpcode, TARGET_VAL("
432        << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << "),\n";
433     return 3;
434
435   case Matcher::SwitchOpcode:
436   case Matcher::SwitchType: {
437     unsigned StartIdx = CurrentIdx;
438
439     unsigned NumCases;
440     if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
441       OS << "OPC_SwitchOpcode ";
442       NumCases = SOM->getNumCases();
443     } else {
444       OS << "OPC_SwitchType ";
445       NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
446     }
447
448     if (!OmitComments)
449       OS << "/*" << NumCases << " cases */";
450     OS << ", ";
451     ++CurrentIdx;
452
453     // For each case we emit the size, then the opcode, then the matcher.
454     for (unsigned i = 0, e = NumCases; i != e; ++i) {
455       const Matcher *Child;
456       unsigned IdxSize;
457       if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
458         Child = SOM->getCaseMatcher(i);
459         IdxSize = 2;  // size of opcode in table is 2 bytes.
460       } else {
461         Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
462         IdxSize = 1;  // size of type in table is 1 byte.
463       }
464
465       // We need to encode the opcode and the offset of the case code before
466       // emitting the case code.  Handle this by buffering the output into a
467       // string while we get the size.  Unfortunately, the offset of the
468       // children depends on the VBR size of the child, so for large children we
469       // have to iterate a bit.
470       SmallString<128> TmpBuf;
471       unsigned ChildSize = 0;
472       unsigned VBRSize = 0;
473       do {
474         VBRSize = GetVBRSize(ChildSize);
475
476         TmpBuf.clear();
477         raw_svector_ostream OS(TmpBuf);
478         ChildSize = EmitMatcherList(Child, Indent+1, CurrentIdx+VBRSize+IdxSize,
479                                     OS);
480       } while (GetVBRSize(ChildSize) != VBRSize);
481
482       assert(ChildSize != 0 && "Should not have a zero-sized child!");
483
484       if (i != 0) {
485         if (!OmitComments)
486           OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
487         OS.indent(Indent*2);
488         if (!OmitComments)
489           OS << (isa<SwitchOpcodeMatcher>(N) ?
490                      "/*SwitchOpcode*/ " : "/*SwitchType*/ ");
491       }
492
493       // Emit the VBR.
494       CurrentIdx += EmitVBRValue(ChildSize, OS);
495
496       if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
497         OS << "TARGET_VAL(" << SOM->getCaseOpcode(i).getEnumName() << "),";
498       else
499         OS << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i)) << ',';
500
501       CurrentIdx += IdxSize;
502
503       if (!OmitComments)
504         OS << "// ->" << CurrentIdx+ChildSize;
505       OS << '\n';
506       OS << TmpBuf;
507       CurrentIdx += ChildSize;
508     }
509
510     // Emit the final zero to terminate the switch.
511     if (!OmitComments)
512       OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
513     OS.indent(Indent*2) << "0,";
514     if (!OmitComments)
515       OS << (isa<SwitchOpcodeMatcher>(N) ?
516              " // EndSwitchOpcode" : " // EndSwitchType");
517
518     OS << '\n';
519     ++CurrentIdx;
520     return CurrentIdx-StartIdx;
521   }
522
523  case Matcher::CheckType:
524     if (cast<CheckTypeMatcher>(N)->getResNo() == 0) {
525       OS << "OPC_CheckType, "
526          << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
527       return 2;
528     }
529     OS << "OPC_CheckTypeRes, " << cast<CheckTypeMatcher>(N)->getResNo()
530        << ", " << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
531     return 3;
532
533   case Matcher::CheckChildType:
534     OS << "OPC_CheckChild"
535        << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, "
536        << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n";
537     return 2;
538
539   case Matcher::CheckInteger: {
540     OS << "OPC_CheckInteger, ";
541     unsigned Bytes=1+EmitVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
542     OS << '\n';
543     return Bytes;
544   }
545   case Matcher::CheckChildInteger: {
546     OS << "OPC_CheckChild" << cast<CheckChildIntegerMatcher>(N)->getChildNo()
547        << "Integer, ";
548     unsigned Bytes=1+EmitVBRValue(cast<CheckChildIntegerMatcher>(N)->getValue(),
549                                   OS);
550     OS << '\n';
551     return Bytes;
552   }
553   case Matcher::CheckCondCode:
554     OS << "OPC_CheckCondCode, ISD::"
555        << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
556     return 2;
557
558   case Matcher::CheckValueType:
559     OS << "OPC_CheckValueType, MVT::"
560        << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
561     return 2;
562
563   case Matcher::CheckComplexPat: {
564     const CheckComplexPatMatcher *CCPM = cast<CheckComplexPatMatcher>(N);
565     const ComplexPattern &Pattern = CCPM->getPattern();
566     OS << "OPC_CheckComplexPat, /*CP*/" << getComplexPat(Pattern) << ", /*#*/"
567        << CCPM->getMatchNumber() << ',';
568
569     if (!OmitComments) {
570       OS << " // " << Pattern.getSelectFunc();
571       OS << ":$" << CCPM->getName();
572       for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i)
573         OS << " #" << CCPM->getFirstResult()+i;
574
575       if (Pattern.hasProperty(SDNPHasChain))
576         OS << " + chain result";
577     }
578     OS << '\n';
579     return 3;
580   }
581
582   case Matcher::CheckAndImm: {
583     OS << "OPC_CheckAndImm, ";
584     unsigned Bytes=1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
585     OS << '\n';
586     return Bytes;
587   }
588
589   case Matcher::CheckOrImm: {
590     OS << "OPC_CheckOrImm, ";
591     unsigned Bytes = 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
592     OS << '\n';
593     return Bytes;
594   }
595
596   case Matcher::CheckFoldableChainNode:
597     OS << "OPC_CheckFoldableChainNode,\n";
598     return 1;
599
600   case Matcher::EmitInteger: {
601     int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
602     OS << "OPC_EmitInteger, "
603        << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", ";
604     unsigned Bytes = 2+EmitVBRValue(Val, OS);
605     OS << '\n';
606     return Bytes;
607   }
608   case Matcher::EmitStringInteger: {
609     const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
610     // These should always fit into one byte.
611     OS << "OPC_EmitInteger, "
612       << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", "
613       << Val << ",\n";
614     return 3;
615   }
616
617   case Matcher::EmitRegister: {
618     const EmitRegisterMatcher *Matcher = cast<EmitRegisterMatcher>(N);
619     const CodeGenRegister *Reg = Matcher->getReg();
620     // If the enum value of the register is larger than one byte can handle,
621     // use EmitRegister2.
622     if (Reg && Reg->EnumValue > 255) {
623       OS << "OPC_EmitRegister2, " << getEnumName(Matcher->getVT()) << ", ";
624       OS << "TARGET_VAL(" << getQualifiedName(Reg->TheDef) << "),\n";
625       return 4;
626     } else {
627       OS << "OPC_EmitRegister, " << getEnumName(Matcher->getVT()) << ", ";
628       if (Reg) {
629         OS << getQualifiedName(Reg->TheDef) << ",\n";
630       } else {
631         OS << "0 ";
632         if (!OmitComments)
633           OS << "/*zero_reg*/";
634         OS << ",\n";
635       }
636       return 3;
637     }
638   }
639
640   case Matcher::EmitConvertToTarget:
641     OS << "OPC_EmitConvertToTarget, "
642        << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
643     return 2;
644
645   case Matcher::EmitMergeInputChains: {
646     const EmitMergeInputChainsMatcher *MN =
647       cast<EmitMergeInputChainsMatcher>(N);
648
649     // Handle the specialized forms OPC_EmitMergeInputChains1_0, 1_1, and 1_2.
650     if (MN->getNumNodes() == 1 && MN->getNode(0) < 3) {
651       OS << "OPC_EmitMergeInputChains1_" << MN->getNode(0) << ",\n";
652       return 1;
653     }
654
655     OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
656     for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
657       OS << MN->getNode(i) << ", ";
658     OS << '\n';
659     return 2+MN->getNumNodes();
660   }
661   case Matcher::EmitCopyToReg:
662     OS << "OPC_EmitCopyToReg, "
663        << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
664        << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
665        << ",\n";
666     return 3;
667   case Matcher::EmitNodeXForm: {
668     const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
669     OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
670        << XF->getSlot() << ',';
671     if (!OmitComments)
672       OS << " // "<<XF->getNodeXForm()->getName();
673     OS <<'\n';
674     return 3;
675   }
676
677   case Matcher::EmitNode:
678   case Matcher::MorphNodeTo: {
679     auto NumCoveredBytes = 0;
680     if (InstrumentCoverage) {
681       if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
682         NumCoveredBytes = 3;
683         OS << "OPC_Coverage, ";
684         std::string src =
685             GetPatFromTreePatternNode(SNT->getPattern().getSrcPattern());
686         std::string dst =
687             GetPatFromTreePatternNode(SNT->getPattern().getDstPattern());
688         Record *PatRecord = SNT->getPattern().getSrcRecord();
689         std::string include_src = getIncludePath(PatRecord);
690         unsigned Offset =
691             getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
692         OS << "TARGET_VAL(" << Offset << "),\n";
693         OS.indent(FullIndexWidth + Indent * 2);
694       }
695     }
696     const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
697     OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
698     bool CompressVTs = EN->getNumVTs() < 3;
699     if (CompressVTs)
700       OS << EN->getNumVTs();
701
702     OS << ", TARGET_VAL(" << EN->getOpcodeName() << "), 0";
703
704     if (EN->hasChain())   OS << "|OPFL_Chain";
705     if (EN->hasInFlag())  OS << "|OPFL_GlueInput";
706     if (EN->hasOutFlag()) OS << "|OPFL_GlueOutput";
707     if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
708     if (EN->getNumFixedArityOperands() != -1)
709       OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
710     OS << ",\n";
711
712     OS.indent(FullIndexWidth + Indent*2+4);
713     if (!CompressVTs) {
714       OS << EN->getNumVTs();
715       if (!OmitComments)
716         OS << "/*#VTs*/";
717       OS << ", ";
718     }
719     for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
720       OS << getEnumName(EN->getVT(i)) << ", ";
721
722     OS << EN->getNumOperands();
723     if (!OmitComments)
724       OS << "/*#Ops*/";
725     OS << ", ";
726     unsigned NumOperandBytes = 0;
727     for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
728       NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
729
730     if (!OmitComments) {
731       // Print the result #'s for EmitNode.
732       if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
733         if (unsigned NumResults = EN->getNumVTs()) {
734           OS << " // Results =";
735           unsigned First = E->getFirstResultSlot();
736           for (unsigned i = 0; i != NumResults; ++i)
737             OS << " #" << First+i;
738         }
739       }
740       OS << '\n';
741
742       if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
743         OS.indent(FullIndexWidth + Indent*2) << "// Src: "
744           << *SNT->getPattern().getSrcPattern() << " - Complexity = "
745           << SNT->getPattern().getPatternComplexity(CGP) << '\n';
746         OS.indent(FullIndexWidth + Indent*2) << "// Dst: "
747           << *SNT->getPattern().getDstPattern() << '\n';
748       }
749     } else
750       OS << '\n';
751
752     return 5 + !CompressVTs + EN->getNumVTs() + NumOperandBytes +
753            NumCoveredBytes;
754   }
755   case Matcher::CompleteMatch: {
756     const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
757     auto NumCoveredBytes = 0;
758     if (InstrumentCoverage) {
759       NumCoveredBytes = 3;
760       OS << "OPC_Coverage, ";
761       std::string src =
762           GetPatFromTreePatternNode(CM->getPattern().getSrcPattern());
763       std::string dst =
764           GetPatFromTreePatternNode(CM->getPattern().getDstPattern());
765       Record *PatRecord = CM->getPattern().getSrcRecord();
766       std::string include_src = getIncludePath(PatRecord);
767       unsigned Offset =
768           getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
769       OS << "TARGET_VAL(" << Offset << "),\n";
770       OS.indent(FullIndexWidth + Indent * 2);
771     }
772     OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
773     unsigned NumResultBytes = 0;
774     for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
775       NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
776     OS << '\n';
777     if (!OmitComments) {
778       OS.indent(FullIndexWidth + Indent*2) << " // Src: "
779         << *CM->getPattern().getSrcPattern() << " - Complexity = "
780         << CM->getPattern().getPatternComplexity(CGP) << '\n';
781       OS.indent(FullIndexWidth + Indent*2) << " // Dst: "
782         << *CM->getPattern().getDstPattern();
783     }
784     OS << '\n';
785     return 2 + NumResultBytes + NumCoveredBytes;
786   }
787   }
788   llvm_unreachable("Unreachable");
789 }
790
791 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
792 unsigned MatcherTableEmitter::
793 EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
794                 raw_ostream &OS) {
795   unsigned Size = 0;
796   while (N) {
797     if (!OmitComments)
798       OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
799     unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
800     Size += MatcherSize;
801     CurrentIdx += MatcherSize;
802
803     // If there are other nodes in this list, iterate to them, otherwise we're
804     // done.
805     N = N->getNext();
806   }
807   return Size;
808 }
809
810 void MatcherTableEmitter::EmitNodePredicatesFunction(
811     const std::vector<TreePredicateFn> &Preds, StringRef Decl,
812     raw_ostream &OS) {
813   if (Preds.empty())
814     return;
815
816   BeginEmitFunction(OS, "bool", Decl, true/*AddOverride*/);
817   OS << "{\n";
818   OS << "  switch (PredNo) {\n";
819   OS << "  default: llvm_unreachable(\"Invalid predicate in table?\");\n";
820   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
821     // Emit the predicate code corresponding to this pattern.
822     TreePredicateFn PredFn = Preds[i];
823
824     assert(!PredFn.isAlwaysTrue() && "No code in this predicate");
825     OS << "  case " << i << ": { \n";
826     for (auto *SimilarPred :
827           NodePredicatesByCodeToRun[PredFn.getCodeToRunOnSDNode()])
828       OS << "    // " << TreePredicateFn(SimilarPred).getFnName() <<'\n';
829
830     OS << PredFn.getCodeToRunOnSDNode() << "\n  }\n";
831   }
832   OS << "  }\n";
833   OS << "}\n";
834   EndEmitFunction(OS);
835 }
836
837 void MatcherTableEmitter::EmitPredicateFunctions(raw_ostream &OS) {
838   // Emit pattern predicates.
839   if (!PatternPredicates.empty()) {
840     BeginEmitFunction(OS, "bool",
841           "CheckPatternPredicate(unsigned PredNo) const", true/*AddOverride*/);
842     OS << "{\n";
843     OS << "  switch (PredNo) {\n";
844     OS << "  default: llvm_unreachable(\"Invalid predicate in table?\");\n";
845     for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
846       OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n";
847     OS << "  }\n";
848     OS << "}\n";
849     EndEmitFunction(OS);
850   }
851
852   // Emit Node predicates.
853   EmitNodePredicatesFunction(
854       NodePredicates, "CheckNodePredicate(SDNode *Node, unsigned PredNo) const",
855       OS);
856   EmitNodePredicatesFunction(
857       NodePredicatesWithOperands,
858       "CheckNodePredicateWithOperands(SDNode *Node, unsigned PredNo, "
859       "const SmallVectorImpl<SDValue> &Operands) const",
860       OS);
861
862   // Emit CompletePattern matchers.
863   // FIXME: This should be const.
864   if (!ComplexPatterns.empty()) {
865     BeginEmitFunction(OS, "bool",
866           "CheckComplexPattern(SDNode *Root, SDNode *Parent,\n"
867           "      SDValue N, unsigned PatternNo,\n"
868           "      SmallVectorImpl<std::pair<SDValue, SDNode*>> &Result)",
869           true/*AddOverride*/);
870     OS << "{\n";
871     OS << "  unsigned NextRes = Result.size();\n";
872     OS << "  switch (PatternNo) {\n";
873     OS << "  default: llvm_unreachable(\"Invalid pattern # in table?\");\n";
874     for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
875       const ComplexPattern &P = *ComplexPatterns[i];
876       unsigned NumOps = P.getNumOperands();
877
878       if (P.hasProperty(SDNPHasChain))
879         ++NumOps;  // Get the chained node too.
880
881       OS << "  case " << i << ":\n";
882       if (InstrumentCoverage)
883         OS << "  {\n";
884       OS << "    Result.resize(NextRes+" << NumOps << ");\n";
885       if (InstrumentCoverage)
886         OS << "    bool Succeeded = " << P.getSelectFunc();
887       else
888         OS << "  return " << P.getSelectFunc();
889
890       OS << "(";
891       // If the complex pattern wants the root of the match, pass it in as the
892       // first argument.
893       if (P.hasProperty(SDNPWantRoot))
894         OS << "Root, ";
895
896       // If the complex pattern wants the parent of the operand being matched,
897       // pass it in as the next argument.
898       if (P.hasProperty(SDNPWantParent))
899         OS << "Parent, ";
900
901       OS << "N";
902       for (unsigned i = 0; i != NumOps; ++i)
903         OS << ", Result[NextRes+" << i << "].first";
904       OS << ");\n";
905       if (InstrumentCoverage) {
906         OS << "    if (Succeeded)\n";
907         OS << "       dbgs() << \"\\nCOMPLEX_PATTERN: " << P.getSelectFunc()
908            << "\\n\" ;\n";
909         OS << "    return Succeeded;\n";
910         OS << "    }\n";
911       }
912     }
913     OS << "  }\n";
914     OS << "}\n";
915     EndEmitFunction(OS);
916   }
917
918
919   // Emit SDNodeXForm handlers.
920   // FIXME: This should be const.
921   if (!NodeXForms.empty()) {
922     BeginEmitFunction(OS, "SDValue",
923           "RunSDNodeXForm(SDValue V, unsigned XFormNo)", true/*AddOverride*/);
924     OS << "{\n";
925     OS << "  switch (XFormNo) {\n";
926     OS << "  default: llvm_unreachable(\"Invalid xform # in table?\");\n";
927
928     // FIXME: The node xform could take SDValue's instead of SDNode*'s.
929     for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) {
930       const CodeGenDAGPatterns::NodeXForm &Entry =
931         CGP.getSDNodeTransform(NodeXForms[i]);
932
933       Record *SDNode = Entry.first;
934       const std::string &Code = Entry.second;
935
936       OS << "  case " << i << ": {  ";
937       if (!OmitComments)
938         OS << "// " << NodeXForms[i]->getName();
939       OS << '\n';
940
941       std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
942       if (ClassName == "SDNode")
943         OS << "    SDNode *N = V.getNode();\n";
944       else
945         OS << "    " << ClassName << " *N = cast<" << ClassName
946            << ">(V.getNode());\n";
947       OS << Code << "\n  }\n";
948     }
949     OS << "  }\n";
950     OS << "}\n";
951     EndEmitFunction(OS);
952   }
953 }
954
955 static void BuildHistogram(const Matcher *M, std::vector<unsigned> &OpcodeFreq){
956   for (; M != nullptr; M = M->getNext()) {
957     // Count this node.
958     if (unsigned(M->getKind()) >= OpcodeFreq.size())
959       OpcodeFreq.resize(M->getKind()+1);
960     OpcodeFreq[M->getKind()]++;
961
962     // Handle recursive nodes.
963     if (const ScopeMatcher *SM = dyn_cast<ScopeMatcher>(M)) {
964       for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i)
965         BuildHistogram(SM->getChild(i), OpcodeFreq);
966     } else if (const SwitchOpcodeMatcher *SOM =
967                  dyn_cast<SwitchOpcodeMatcher>(M)) {
968       for (unsigned i = 0, e = SOM->getNumCases(); i != e; ++i)
969         BuildHistogram(SOM->getCaseMatcher(i), OpcodeFreq);
970     } else if (const SwitchTypeMatcher *STM = dyn_cast<SwitchTypeMatcher>(M)) {
971       for (unsigned i = 0, e = STM->getNumCases(); i != e; ++i)
972         BuildHistogram(STM->getCaseMatcher(i), OpcodeFreq);
973     }
974   }
975 }
976
977 static StringRef getOpcodeString(Matcher::KindTy Kind) {
978   switch (Kind) {
979   case Matcher::Scope: return "OPC_Scope"; break;
980   case Matcher::RecordNode: return "OPC_RecordNode"; break;
981   case Matcher::RecordChild: return "OPC_RecordChild"; break;
982   case Matcher::RecordMemRef: return "OPC_RecordMemRef"; break;
983   case Matcher::CaptureGlueInput: return "OPC_CaptureGlueInput"; break;
984   case Matcher::MoveChild: return "OPC_MoveChild"; break;
985   case Matcher::MoveParent: return "OPC_MoveParent"; break;
986   case Matcher::CheckSame: return "OPC_CheckSame"; break;
987   case Matcher::CheckChildSame: return "OPC_CheckChildSame"; break;
988   case Matcher::CheckPatternPredicate:
989     return "OPC_CheckPatternPredicate"; break;
990   case Matcher::CheckPredicate: return "OPC_CheckPredicate"; break;
991   case Matcher::CheckOpcode: return "OPC_CheckOpcode"; break;
992   case Matcher::SwitchOpcode: return "OPC_SwitchOpcode"; break;
993   case Matcher::CheckType: return "OPC_CheckType"; break;
994   case Matcher::SwitchType: return "OPC_SwitchType"; break;
995   case Matcher::CheckChildType: return "OPC_CheckChildType"; break;
996   case Matcher::CheckInteger: return "OPC_CheckInteger"; break;
997   case Matcher::CheckChildInteger: return "OPC_CheckChildInteger"; break;
998   case Matcher::CheckCondCode: return "OPC_CheckCondCode"; break;
999   case Matcher::CheckValueType: return "OPC_CheckValueType"; break;
1000   case Matcher::CheckComplexPat: return "OPC_CheckComplexPat"; break;
1001   case Matcher::CheckAndImm: return "OPC_CheckAndImm"; break;
1002   case Matcher::CheckOrImm: return "OPC_CheckOrImm"; break;
1003   case Matcher::CheckFoldableChainNode:
1004     return "OPC_CheckFoldableChainNode"; break;
1005   case Matcher::EmitInteger: return "OPC_EmitInteger"; break;
1006   case Matcher::EmitStringInteger: return "OPC_EmitStringInteger"; break;
1007   case Matcher::EmitRegister: return "OPC_EmitRegister"; break;
1008   case Matcher::EmitConvertToTarget: return "OPC_EmitConvertToTarget"; break;
1009   case Matcher::EmitMergeInputChains: return "OPC_EmitMergeInputChains"; break;
1010   case Matcher::EmitCopyToReg: return "OPC_EmitCopyToReg"; break;
1011   case Matcher::EmitNode: return "OPC_EmitNode"; break;
1012   case Matcher::MorphNodeTo: return "OPC_MorphNodeTo"; break;
1013   case Matcher::EmitNodeXForm: return "OPC_EmitNodeXForm"; break;
1014   case Matcher::CompleteMatch: return "OPC_CompleteMatch"; break;
1015   }
1016
1017   llvm_unreachable("Unhandled opcode?");
1018 }
1019
1020 void MatcherTableEmitter::EmitHistogram(const Matcher *M,
1021                                         raw_ostream &OS) {
1022   if (OmitComments)
1023     return;
1024
1025   std::vector<unsigned> OpcodeFreq;
1026   BuildHistogram(M, OpcodeFreq);
1027
1028   OS << "  // Opcode Histogram:\n";
1029   for (unsigned i = 0, e = OpcodeFreq.size(); i != e; ++i) {
1030     OS << "  // #"
1031        << left_justify(getOpcodeString((Matcher::KindTy)i), HistOpcWidth)
1032        << " = " << OpcodeFreq[i] << '\n';
1033   }
1034   OS << '\n';
1035 }
1036
1037
1038 void llvm::EmitMatcherTable(const Matcher *TheMatcher,
1039                             const CodeGenDAGPatterns &CGP,
1040                             raw_ostream &OS) {
1041   OS << "#if defined(GET_DAGISEL_DECL) && defined(GET_DAGISEL_BODY)\n";
1042   OS << "#error GET_DAGISEL_DECL and GET_DAGISEL_BODY cannot be both defined, ";
1043   OS << "undef both for inline definitions\n";
1044   OS << "#endif\n\n";
1045
1046   // Emit a check for omitted class name.
1047   OS << "#ifdef GET_DAGISEL_BODY\n";
1048   OS << "#define LOCAL_DAGISEL_STRINGIZE(X) LOCAL_DAGISEL_STRINGIZE_(X)\n";
1049   OS << "#define LOCAL_DAGISEL_STRINGIZE_(X) #X\n";
1050   OS << "static_assert(sizeof(LOCAL_DAGISEL_STRINGIZE(GET_DAGISEL_BODY)) > 1,"
1051         "\n";
1052   OS << "   \"GET_DAGISEL_BODY is empty: it should be defined with the class "
1053         "name\");\n";
1054   OS << "#undef LOCAL_DAGISEL_STRINGIZE_\n";
1055   OS << "#undef LOCAL_DAGISEL_STRINGIZE\n";
1056   OS << "#endif\n\n";
1057
1058   OS << "#if !defined(GET_DAGISEL_DECL) && !defined(GET_DAGISEL_BODY)\n";
1059   OS << "#define DAGISEL_INLINE 1\n";
1060   OS << "#else\n";
1061   OS << "#define DAGISEL_INLINE 0\n";
1062   OS << "#endif\n\n";
1063
1064   OS << "#if !DAGISEL_INLINE\n";
1065   OS << "#define DAGISEL_CLASS_COLONCOLON GET_DAGISEL_BODY ::\n";
1066   OS << "#else\n";
1067   OS << "#define DAGISEL_CLASS_COLONCOLON\n";
1068   OS << "#endif\n\n";
1069
1070   BeginEmitFunction(OS, "void", "SelectCode(SDNode *N)", false/*AddOverride*/);
1071   MatcherTableEmitter MatcherEmitter(CGP);
1072
1073   OS << "{\n";
1074   OS << "  // Some target values are emitted as 2 bytes, TARGET_VAL handles\n";
1075   OS << "  // this.\n";
1076   OS << "  #define TARGET_VAL(X) X & 255, unsigned(X) >> 8\n";
1077   OS << "  static const unsigned char MatcherTable[] = {\n";
1078   unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 1, 0, OS);
1079   OS << "    0\n  }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
1080
1081   MatcherEmitter.EmitHistogram(TheMatcher, OS);
1082
1083   OS << "  #undef TARGET_VAL\n";
1084   OS << "  SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n";
1085   OS << "}\n";
1086   EndEmitFunction(OS);
1087
1088   // Next up, emit the function for node and pattern predicates:
1089   MatcherEmitter.EmitPredicateFunctions(OS);
1090
1091   if (InstrumentCoverage)
1092     MatcherEmitter.EmitPatternMatchTable(OS);
1093
1094   // Clean up the preprocessor macros.
1095   OS << "\n";
1096   OS << "#ifdef DAGISEL_INLINE\n";
1097   OS << "#undef DAGISEL_INLINE\n";
1098   OS << "#endif\n";
1099   OS << "#ifdef DAGISEL_CLASS_COLONCOLON\n";
1100   OS << "#undef DAGISEL_CLASS_COLONCOLON\n";
1101   OS << "#endif\n";
1102   OS << "#ifdef GET_DAGISEL_DECL\n";
1103   OS << "#undef GET_DAGISEL_DECL\n";
1104   OS << "#endif\n";
1105   OS << "#ifdef GET_DAGISEL_BODY\n";
1106   OS << "#undef GET_DAGISEL_BODY\n";
1107   OS << "#endif\n";
1108 }