1 //===- DAGISelMatcherEmitter.cpp - Matcher Emitter ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains code to generate C++ code for a matcher.
12 //===----------------------------------------------------------------------===//
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"
31 FullIndexWidth = IndexWidth + 4,
35 cl::OptionCategory DAGISelCat("Options for -gen-dag-isel");
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));
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));
48 class MatcherTableEmitter {
49 const CodeGenDAGPatterns &CGP;
51 DenseMap<TreePattern *, unsigned> NodePredicateMap;
52 std::vector<TreePredicateFn> NodePredicates;
53 std::vector<TreePredicateFn> NodePredicatesWithOperands;
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;
59 StringMap<unsigned> PatternPredicateMap;
60 std::vector<std::string> PatternPredicates;
62 DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
63 std::vector<const ComplexPattern*> ComplexPatterns;
66 DenseMap<Record*, unsigned> NodeXFormMap;
67 std::vector<Record*> NodeXForms;
69 std::vector<std::string> VecIncludeStrings;
70 MapVector<std::string, unsigned, StringMap<unsigned> > VecPatterns;
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;
83 MatcherTableEmitter(const CodeGenDAGPatterns &cgp)
86 unsigned EmitMatcherList(const Matcher *N, unsigned Indent,
87 unsigned StartIdx, raw_ostream &OS);
89 void EmitPredicateFunctions(raw_ostream &OS);
91 void EmitHistogram(const Matcher *N, raw_ostream &OS);
93 void EmitPatternMatchTable(raw_ostream &OS);
96 void EmitNodePredicatesFunction(const std::vector<TreePredicateFn> &Preds,
97 StringRef Decl, raw_ostream &OS);
99 unsigned EmitMatcher(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
102 unsigned getNodePredicate(TreePredicateFn Pred) {
103 TreePattern *TP = Pred.getOrigPatFragRecord();
104 unsigned &Entry = NodePredicateMap[TP];
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();
114 NodePredicates.push_back(Pred);
115 Entry = NodePredicates.size();
118 // We did see an identical predicate: re-use it.
119 Entry = NodePredicateMap[SameCodePreds.front()];
121 assert(TreePredicateFn(SameCodePreds.front()).usesOperands() ==
122 Pred.usesOperands() &&
123 "PatFrags with some code must have same usesOperands setting");
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);
132 unsigned getPatternPredicate(StringRef PredName) {
133 unsigned &Entry = PatternPredicateMap[PredName];
135 PatternPredicates.push_back(PredName.str());
136 Entry = PatternPredicates.size();
140 unsigned getComplexPat(const ComplexPattern &P) {
141 unsigned &Entry = ComplexPatternMap[&P];
143 ComplexPatterns.push_back(&P);
144 Entry = ComplexPatterns.size();
149 unsigned getNodeXFormID(Record *Rec) {
150 unsigned &Entry = NodeXFormMap[Rec];
152 NodeXForms.push_back(Rec);
153 Entry = NodeXForms.size();
159 } // end anonymous namespace.
161 static std::string GetPatFromTreePatternNode(const TreePatternNode *N) {
163 raw_string_ostream Stream(str);
169 static unsigned GetVBRSize(unsigned Val) {
170 if (Val <= 127) return 1;
172 unsigned NumBytes = 0;
180 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
182 static uint64_t EmitVBRValue(uint64_t Val, raw_ostream &OS) {
188 uint64_t InVal = Val;
189 unsigned NumBytes = 0;
191 OS << (Val&127) << "|128,";
197 OS << "/*" << InVal << "*/";
202 // This is expensive and slow.
203 static std::string getIncludePath(const Record *R) {
205 raw_string_ostream Stream(str);
206 auto Locs = R->getLoc();
208 if (Locs.size() > 1) {
209 // Get where the pattern prototype was instantiated
211 } else if (Locs.size() == 1) {
214 unsigned CurBuf = SrcMgr.FindBufferContainingLoc(L);
215 assert(CurBuf && "Invalid or unspecified location!");
217 Stream << SrcMgr.getBufferInfo(CurBuf).Buffer->getBufferIdentifier() << ":"
218 << SrcMgr.FindLineNumber(L, CurBuf);
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;
231 "#if defined(GET_DAGISEL_BODY) || DAGISEL_INLINE\n";
232 OS << RetType << " DAGISEL_CLASS_COLONCOLON " << Decl << "\n";
234 OS << "#if DAGISEL_INLINE\n"
240 static void EndEmitFunction(raw_ostream &OS) {
241 OS << "#endif // GET_DAGISEL_BODY\n\n";
244 void MatcherTableEmitter::EmitPatternMatchTable(raw_ostream &OS) {
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");
251 BeginEmitFunction(OS, "StringRef", "getPatternForIndex(unsigned Index)",
252 true/*AddOverride*/);
254 OS << "static const char * PATTERN_MATCH_TABLE[] = {\n";
256 for (const auto &It : VecPatterns) {
257 OS << "\"" << It.first << "\",\n";
261 OS << "\nreturn StringRef(PATTERN_MATCH_TABLE[Index]);";
265 BeginEmitFunction(OS, "StringRef", "getIncludePathForIndex(unsigned Index)",
266 true/*AddOverride*/);
268 OS << "static const char * INCLUDE_PATH_TABLE[] = {\n";
270 for (const auto &It : VecIncludeStrings) {
271 OS << "\"" << It << "\",\n";
275 OS << "\nreturn StringRef(INCLUDE_PATH_TABLE[Index]);";
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,
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");
292 unsigned StartIdx = CurrentIdx;
294 // Emit all of the children.
295 for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
301 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
302 OS.indent(Indent*2) << "/*Scope*/ ";
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;
316 VBRSize = GetVBRSize(ChildSize);
319 raw_svector_ostream OS(TmpBuf);
320 ChildSize = EmitMatcherList(SM->getChild(i), Indent+1,
321 CurrentIdx+VBRSize, OS);
322 } while (GetVBRSize(ChildSize) != VBRSize);
324 assert(ChildSize != 0 && "Should not have a zero-sized child!");
326 CurrentIdx += EmitVBRValue(ChildSize, OS);
328 OS << "/*->" << CurrentIdx+ChildSize << "*/";
331 OS << " // " << SM->getNumChildren() << " children in Scope";
334 OS << '\n' << TmpBuf;
335 CurrentIdx += ChildSize;
338 // Emit a zero as a sentinel indicating end of 'Scope'.
340 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
341 OS.indent(Indent*2) << "0, ";
343 OS << "/*End of Scope*/";
345 return CurrentIdx - StartIdx + 1;
348 case Matcher::RecordNode:
349 OS << "OPC_RecordNode,";
352 << cast<RecordMatcher>(N)->getResultNo() << " = "
353 << cast<RecordMatcher>(N)->getWhatFor();
357 case Matcher::RecordChild:
358 OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo()
362 << cast<RecordChildMatcher>(N)->getResultNo() << " = "
363 << cast<RecordChildMatcher>(N)->getWhatFor();
367 case Matcher::RecordMemRef:
368 OS << "OPC_RecordMemRef,\n";
371 case Matcher::CaptureGlueInput:
372 OS << "OPC_CaptureGlueInput,\n";
375 case Matcher::MoveChild: {
376 const auto *MCM = cast<MoveChildMatcher>(N);
378 OS << "OPC_MoveChild";
379 // Handle the specialized forms.
380 if (MCM->getChildNo() >= 8)
382 OS << MCM->getChildNo() << ",\n";
383 return (MCM->getChildNo() >= 8) ? 2 : 1;
386 case Matcher::MoveParent:
387 OS << "OPC_MoveParent,\n";
390 case Matcher::CheckSame:
391 OS << "OPC_CheckSame, "
392 << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n";
395 case Matcher::CheckChildSame:
396 OS << "OPC_CheckChild"
397 << cast<CheckChildSameMatcher>(N)->getChildNo() << "Same, "
398 << cast<CheckChildSameMatcher>(N)->getMatchNumber() << ",\n";
401 case Matcher::CheckPatternPredicate: {
402 StringRef Pred =cast<CheckPatternPredicateMatcher>(N)->getPredicate();
403 OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
405 OS << " // " << Pred;
409 case Matcher::CheckPredicate: {
410 TreePredicateFn Pred = cast<CheckPredicateMatcher>(N)->getPredicate();
411 unsigned OperandBytes = 0;
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;
420 OS << "OPC_CheckPredicate, ";
423 OS << getNodePredicate(Pred) << ',';
425 OS << " // " << Pred.getFnName();
427 return 2 + OperandBytes;
430 case Matcher::CheckOpcode:
431 OS << "OPC_CheckOpcode, TARGET_VAL("
432 << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << "),\n";
435 case Matcher::SwitchOpcode:
436 case Matcher::SwitchType: {
437 unsigned StartIdx = CurrentIdx;
440 if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
441 OS << "OPC_SwitchOpcode ";
442 NumCases = SOM->getNumCases();
444 OS << "OPC_SwitchType ";
445 NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
449 OS << "/*" << NumCases << " cases */";
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;
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.
461 Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
462 IdxSize = 1; // size of type in table is 1 byte.
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;
474 VBRSize = GetVBRSize(ChildSize);
477 raw_svector_ostream OS(TmpBuf);
478 ChildSize = EmitMatcherList(Child, Indent+1, CurrentIdx+VBRSize+IdxSize,
480 } while (GetVBRSize(ChildSize) != VBRSize);
482 assert(ChildSize != 0 && "Should not have a zero-sized child!");
486 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
489 OS << (isa<SwitchOpcodeMatcher>(N) ?
490 "/*SwitchOpcode*/ " : "/*SwitchType*/ ");
494 CurrentIdx += EmitVBRValue(ChildSize, OS);
496 if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
497 OS << "TARGET_VAL(" << SOM->getCaseOpcode(i).getEnumName() << "),";
499 OS << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i)) << ',';
501 CurrentIdx += IdxSize;
504 OS << "// ->" << CurrentIdx+ChildSize;
507 CurrentIdx += ChildSize;
510 // Emit the final zero to terminate the switch.
512 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
513 OS.indent(Indent*2) << "0,";
515 OS << (isa<SwitchOpcodeMatcher>(N) ?
516 " // EndSwitchOpcode" : " // EndSwitchType");
520 return CurrentIdx-StartIdx;
523 case Matcher::CheckType:
524 if (cast<CheckTypeMatcher>(N)->getResNo() == 0) {
525 OS << "OPC_CheckType, "
526 << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
529 OS << "OPC_CheckTypeRes, " << cast<CheckTypeMatcher>(N)->getResNo()
530 << ", " << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
533 case Matcher::CheckChildType:
534 OS << "OPC_CheckChild"
535 << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, "
536 << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n";
539 case Matcher::CheckInteger: {
540 OS << "OPC_CheckInteger, ";
541 unsigned Bytes=1+EmitVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
545 case Matcher::CheckChildInteger: {
546 OS << "OPC_CheckChild" << cast<CheckChildIntegerMatcher>(N)->getChildNo()
548 unsigned Bytes=1+EmitVBRValue(cast<CheckChildIntegerMatcher>(N)->getValue(),
553 case Matcher::CheckCondCode:
554 OS << "OPC_CheckCondCode, ISD::"
555 << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
558 case Matcher::CheckValueType:
559 OS << "OPC_CheckValueType, MVT::"
560 << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
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() << ',';
570 OS << " // " << Pattern.getSelectFunc();
571 OS << ":$" << CCPM->getName();
572 for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i)
573 OS << " #" << CCPM->getFirstResult()+i;
575 if (Pattern.hasProperty(SDNPHasChain))
576 OS << " + chain result";
582 case Matcher::CheckAndImm: {
583 OS << "OPC_CheckAndImm, ";
584 unsigned Bytes=1+EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
589 case Matcher::CheckOrImm: {
590 OS << "OPC_CheckOrImm, ";
591 unsigned Bytes = 1+EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
596 case Matcher::CheckFoldableChainNode:
597 OS << "OPC_CheckFoldableChainNode,\n";
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);
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()) << ", "
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";
627 OS << "OPC_EmitRegister, " << getEnumName(Matcher->getVT()) << ", ";
629 OS << getQualifiedName(Reg->TheDef) << ",\n";
633 OS << "/*zero_reg*/";
640 case Matcher::EmitConvertToTarget:
641 OS << "OPC_EmitConvertToTarget, "
642 << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
645 case Matcher::EmitMergeInputChains: {
646 const EmitMergeInputChainsMatcher *MN =
647 cast<EmitMergeInputChainsMatcher>(N);
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";
655 OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
656 for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
657 OS << MN->getNode(i) << ", ";
659 return 2+MN->getNumNodes();
661 case Matcher::EmitCopyToReg:
662 OS << "OPC_EmitCopyToReg, "
663 << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
664 << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
667 case Matcher::EmitNodeXForm: {
668 const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
669 OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
670 << XF->getSlot() << ',';
672 OS << " // "<<XF->getNodeXForm()->getName();
677 case Matcher::EmitNode:
678 case Matcher::MorphNodeTo: {
679 auto NumCoveredBytes = 0;
680 if (InstrumentCoverage) {
681 if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
683 OS << "OPC_Coverage, ";
685 GetPatFromTreePatternNode(SNT->getPattern().getSrcPattern());
687 GetPatFromTreePatternNode(SNT->getPattern().getDstPattern());
688 Record *PatRecord = SNT->getPattern().getSrcRecord();
689 std::string include_src = getIncludePath(PatRecord);
691 getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
692 OS << "TARGET_VAL(" << Offset << "),\n";
693 OS.indent(FullIndexWidth + Indent * 2);
696 const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
697 OS << (isa<EmitNodeMatcher>(EN) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
698 bool CompressVTs = EN->getNumVTs() < 3;
700 OS << EN->getNumVTs();
702 OS << ", TARGET_VAL(" << EN->getOpcodeName() << "), 0";
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();
712 OS.indent(FullIndexWidth + Indent*2+4);
714 OS << EN->getNumVTs();
719 for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
720 OS << getEnumName(EN->getVT(i)) << ", ";
722 OS << EN->getNumOperands();
726 unsigned NumOperandBytes = 0;
727 for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
728 NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
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;
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';
752 return 5 + !CompressVTs + EN->getNumVTs() + NumOperandBytes +
755 case Matcher::CompleteMatch: {
756 const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
757 auto NumCoveredBytes = 0;
758 if (InstrumentCoverage) {
760 OS << "OPC_Coverage, ";
762 GetPatFromTreePatternNode(CM->getPattern().getSrcPattern());
764 GetPatFromTreePatternNode(CM->getPattern().getDstPattern());
765 Record *PatRecord = CM->getPattern().getSrcRecord();
766 std::string include_src = getIncludePath(PatRecord);
768 getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
769 OS << "TARGET_VAL(" << Offset << "),\n";
770 OS.indent(FullIndexWidth + Indent * 2);
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);
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();
785 return 2 + NumResultBytes + NumCoveredBytes;
788 llvm_unreachable("Unreachable");
791 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
792 unsigned MatcherTableEmitter::
793 EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
798 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
799 unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
801 CurrentIdx += MatcherSize;
803 // If there are other nodes in this list, iterate to them, otherwise we're
810 void MatcherTableEmitter::EmitNodePredicatesFunction(
811 const std::vector<TreePredicateFn> &Preds, StringRef Decl,
816 BeginEmitFunction(OS, "bool", Decl, true/*AddOverride*/);
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];
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';
830 OS << PredFn.getCodeToRunOnSDNode() << "\n }\n";
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*/);
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";
852 // Emit Node predicates.
853 EmitNodePredicatesFunction(
854 NodePredicates, "CheckNodePredicate(SDNode *Node, unsigned PredNo) const",
856 EmitNodePredicatesFunction(
857 NodePredicatesWithOperands,
858 "CheckNodePredicateWithOperands(SDNode *Node, unsigned PredNo, "
859 "const SmallVectorImpl<SDValue> &Operands) const",
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*/);
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();
878 if (P.hasProperty(SDNPHasChain))
879 ++NumOps; // Get the chained node too.
881 OS << " case " << i << ":\n";
882 if (InstrumentCoverage)
884 OS << " Result.resize(NextRes+" << NumOps << ");\n";
885 if (InstrumentCoverage)
886 OS << " bool Succeeded = " << P.getSelectFunc();
888 OS << " return " << P.getSelectFunc();
891 // If the complex pattern wants the root of the match, pass it in as the
893 if (P.hasProperty(SDNPWantRoot))
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))
902 for (unsigned i = 0; i != NumOps; ++i)
903 OS << ", Result[NextRes+" << i << "].first";
905 if (InstrumentCoverage) {
906 OS << " if (Succeeded)\n";
907 OS << " dbgs() << \"\\nCOMPLEX_PATTERN: " << P.getSelectFunc()
909 OS << " return Succeeded;\n";
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*/);
925 OS << " switch (XFormNo) {\n";
926 OS << " default: llvm_unreachable(\"Invalid xform # in table?\");\n";
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]);
933 Record *SDNode = Entry.first;
934 const std::string &Code = Entry.second;
936 OS << " case " << i << ": { ";
938 OS << "// " << NodeXForms[i]->getName();
941 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
942 if (ClassName == "SDNode")
943 OS << " SDNode *N = V.getNode();\n";
945 OS << " " << ClassName << " *N = cast<" << ClassName
946 << ">(V.getNode());\n";
947 OS << Code << "\n }\n";
955 static void BuildHistogram(const Matcher *M, std::vector<unsigned> &OpcodeFreq){
956 for (; M != nullptr; M = M->getNext()) {
958 if (unsigned(M->getKind()) >= OpcodeFreq.size())
959 OpcodeFreq.resize(M->getKind()+1);
960 OpcodeFreq[M->getKind()]++;
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);
977 static StringRef getOpcodeString(Matcher::KindTy 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;
1017 llvm_unreachable("Unhandled opcode?");
1020 void MatcherTableEmitter::EmitHistogram(const Matcher *M,
1025 std::vector<unsigned> OpcodeFreq;
1026 BuildHistogram(M, OpcodeFreq);
1028 OS << " // Opcode Histogram:\n";
1029 for (unsigned i = 0, e = OpcodeFreq.size(); i != e; ++i) {
1031 << left_justify(getOpcodeString((Matcher::KindTy)i), HistOpcWidth)
1032 << " = " << OpcodeFreq[i] << '\n';
1038 void llvm::EmitMatcherTable(const Matcher *TheMatcher,
1039 const CodeGenDAGPatterns &CGP,
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";
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,"
1052 OS << " \"GET_DAGISEL_BODY is empty: it should be defined with the class "
1054 OS << "#undef LOCAL_DAGISEL_STRINGIZE_\n";
1055 OS << "#undef LOCAL_DAGISEL_STRINGIZE\n";
1058 OS << "#if !defined(GET_DAGISEL_DECL) && !defined(GET_DAGISEL_BODY)\n";
1059 OS << "#define DAGISEL_INLINE 1\n";
1061 OS << "#define DAGISEL_INLINE 0\n";
1064 OS << "#if !DAGISEL_INLINE\n";
1065 OS << "#define DAGISEL_CLASS_COLONCOLON GET_DAGISEL_BODY ::\n";
1067 OS << "#define DAGISEL_CLASS_COLONCOLON\n";
1070 BeginEmitFunction(OS, "void", "SelectCode(SDNode *N)", false/*AddOverride*/);
1071 MatcherTableEmitter MatcherEmitter(CGP);
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";
1081 MatcherEmitter.EmitHistogram(TheMatcher, OS);
1083 OS << " #undef TARGET_VAL\n";
1084 OS << " SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n";
1086 EndEmitFunction(OS);
1088 // Next up, emit the function for node and pattern predicates:
1089 MatcherEmitter.EmitPredicateFunctions(OS);
1091 if (InstrumentCoverage)
1092 MatcherEmitter.EmitPatternMatchTable(OS);
1094 // Clean up the preprocessor macros.
1096 OS << "#ifdef DAGISEL_INLINE\n";
1097 OS << "#undef DAGISEL_INLINE\n";
1099 OS << "#ifdef DAGISEL_CLASS_COLONCOLON\n";
1100 OS << "#undef DAGISEL_CLASS_COLONCOLON\n";
1102 OS << "#ifdef GET_DAGISEL_DECL\n";
1103 OS << "#undef GET_DAGISEL_DECL\n";
1105 OS << "#ifdef GET_DAGISEL_BODY\n";
1106 OS << "#undef GET_DAGISEL_BODY\n";