1 //===- DAGISelMatcherEmitter.cpp - Matcher Emitter ------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains code to generate C++ code for a matcher.
11 //===----------------------------------------------------------------------===//
13 #include "CodeGenDAGPatterns.h"
14 #include "CodeGenInstruction.h"
15 #include "CodeGenRegisters.h"
16 #include "CodeGenTarget.h"
17 #include "DAGISelMatcher.h"
18 #include "SDNodeProperties.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/TinyPtrVector.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/TableGen/Error.h"
27 #include "llvm/TableGen/Record.h"
33 FullIndexWidth
= IndexWidth
+ 4,
37 cl::OptionCategory
DAGISelCat("Options for -gen-dag-isel");
39 // To reduce generated source code size.
40 static cl::opt
<bool> OmitComments("omit-comments",
41 cl::desc("Do not generate comments"),
42 cl::init(false), cl::cat(DAGISelCat
));
44 static cl::opt
<bool> InstrumentCoverage(
45 "instrument-coverage",
46 cl::desc("Generates tables to help identify patterns matched"),
47 cl::init(false), cl::cat(DAGISelCat
));
50 class MatcherTableEmitter
{
51 const CodeGenDAGPatterns
&CGP
;
53 SmallVector
<unsigned, Matcher::HighestKind
+1> OpcodeCounts
;
55 DenseMap
<TreePattern
*, unsigned> NodePredicateMap
;
56 std::vector
<TreePredicateFn
> NodePredicates
;
57 std::vector
<TreePredicateFn
> NodePredicatesWithOperands
;
59 // We de-duplicate the predicates by code string, and use this map to track
60 // all the patterns with "identical" predicates.
61 StringMap
<TinyPtrVector
<TreePattern
*>> NodePredicatesByCodeToRun
;
63 StringMap
<unsigned> PatternPredicateMap
;
64 std::vector
<std::string
> PatternPredicates
;
66 DenseMap
<const ComplexPattern
*, unsigned> ComplexPatternMap
;
67 std::vector
<const ComplexPattern
*> ComplexPatterns
;
70 DenseMap
<Record
*, unsigned> NodeXFormMap
;
71 std::vector
<Record
*> NodeXForms
;
73 std::vector
<std::string
> VecIncludeStrings
;
74 MapVector
<std::string
, unsigned, StringMap
<unsigned> > VecPatterns
;
76 unsigned getPatternIdxFromTable(std::string
&&P
, std::string
&&include_loc
) {
77 const auto It
= VecPatterns
.find(P
);
78 if (It
== VecPatterns
.end()) {
79 VecPatterns
.insert(make_pair(std::move(P
), VecPatterns
.size()));
80 VecIncludeStrings
.push_back(std::move(include_loc
));
81 return VecIncludeStrings
.size() - 1;
87 MatcherTableEmitter(const CodeGenDAGPatterns
&cgp
)
88 : CGP(cgp
), OpcodeCounts(Matcher::HighestKind
+ 1, 0) {}
90 unsigned EmitMatcherList(const Matcher
*N
, const unsigned Indent
,
91 unsigned StartIdx
, raw_ostream
&OS
);
93 unsigned SizeMatcherList(Matcher
*N
, raw_ostream
&OS
);
95 void EmitPredicateFunctions(raw_ostream
&OS
);
97 void EmitHistogram(const Matcher
*N
, raw_ostream
&OS
);
99 void EmitPatternMatchTable(raw_ostream
&OS
);
102 void EmitNodePredicatesFunction(const std::vector
<TreePredicateFn
> &Preds
,
103 StringRef Decl
, raw_ostream
&OS
);
105 unsigned SizeMatcher(Matcher
*N
, raw_ostream
&OS
);
107 unsigned EmitMatcher(const Matcher
*N
, const unsigned Indent
, unsigned CurrentIdx
,
110 unsigned getNodePredicate(TreePredicateFn Pred
) {
111 TreePattern
*TP
= Pred
.getOrigPatFragRecord();
112 unsigned &Entry
= NodePredicateMap
[TP
];
114 TinyPtrVector
<TreePattern
*> &SameCodePreds
=
115 NodePredicatesByCodeToRun
[Pred
.getCodeToRunOnSDNode()];
116 if (SameCodePreds
.empty()) {
117 // We've never seen a predicate with the same code: allocate an entry.
118 if (Pred
.usesOperands()) {
119 NodePredicatesWithOperands
.push_back(Pred
);
120 Entry
= NodePredicatesWithOperands
.size();
122 NodePredicates
.push_back(Pred
);
123 Entry
= NodePredicates
.size();
126 // We did see an identical predicate: re-use it.
127 Entry
= NodePredicateMap
[SameCodePreds
.front()];
129 assert(TreePredicateFn(SameCodePreds
.front()).usesOperands() ==
130 Pred
.usesOperands() &&
131 "PatFrags with some code must have same usesOperands setting");
133 // In both cases, we've never seen this particular predicate before, so
134 // mark it in the list of predicates sharing the same code.
135 SameCodePreds
.push_back(TP
);
140 unsigned getPatternPredicate(StringRef PredName
) {
141 unsigned &Entry
= PatternPredicateMap
[PredName
];
143 PatternPredicates
.push_back(PredName
.str());
144 Entry
= PatternPredicates
.size();
148 unsigned getComplexPat(const ComplexPattern
&P
) {
149 unsigned &Entry
= ComplexPatternMap
[&P
];
151 ComplexPatterns
.push_back(&P
);
152 Entry
= ComplexPatterns
.size();
157 unsigned getNodeXFormID(Record
*Rec
) {
158 unsigned &Entry
= NodeXFormMap
[Rec
];
160 NodeXForms
.push_back(Rec
);
161 Entry
= NodeXForms
.size();
167 } // end anonymous namespace.
169 static std::string
GetPatFromTreePatternNode(const TreePatternNode
*N
) {
171 raw_string_ostream
Stream(str
);
176 static unsigned GetVBRSize(unsigned Val
) {
177 if (Val
<= 127) return 1;
179 unsigned NumBytes
= 0;
187 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
189 static unsigned EmitVBRValue(uint64_t Val
, raw_ostream
&OS
) {
195 uint64_t InVal
= Val
;
196 unsigned NumBytes
= 0;
198 OS
<< (Val
&127) << "|128,";
204 OS
<< "/*" << InVal
<< "*/";
209 /// Emit the specified signed value as a VBR. To improve compression we encode
210 /// positive numbers shifted left by 1 and negative numbers negated and shifted
211 /// left by 1 with bit 0 set.
212 static unsigned EmitSignedVBRValue(uint64_t Val
, raw_ostream
&OS
) {
213 if ((int64_t)Val
>= 0)
216 Val
= (-Val
<< 1) | 1;
218 return EmitVBRValue(Val
, OS
);
221 // This is expensive and slow.
222 static std::string
getIncludePath(const Record
*R
) {
224 raw_string_ostream
Stream(str
);
225 auto Locs
= R
->getLoc();
227 if (Locs
.size() > 1) {
228 // Get where the pattern prototype was instantiated
230 } else if (Locs
.size() == 1) {
233 unsigned CurBuf
= SrcMgr
.FindBufferContainingLoc(L
);
234 assert(CurBuf
&& "Invalid or unspecified location!");
236 Stream
<< SrcMgr
.getBufferInfo(CurBuf
).Buffer
->getBufferIdentifier() << ":"
237 << SrcMgr
.FindLineNumber(L
, CurBuf
);
241 /// This function traverses the matcher tree and sizes all the nodes
242 /// that are children of the three kinds of nodes that have them.
243 unsigned MatcherTableEmitter::
244 SizeMatcherList(Matcher
*N
, raw_ostream
&OS
) {
247 Size
+= SizeMatcher(N
, OS
);
253 /// This function sizes the children of the three kinds of nodes that
254 /// have them. It does so by using special cases for those three
255 /// nodes, but sharing the code in EmitMatcher() for the other kinds.
256 unsigned MatcherTableEmitter::
257 SizeMatcher(Matcher
*N
, raw_ostream
&OS
) {
260 ++OpcodeCounts
[N
->getKind()];
261 switch (N
->getKind()) {
262 // The Scope matcher has its kind, a series of child size + child,
263 // and a trailing zero.
264 case Matcher::Scope
: {
265 ScopeMatcher
*SM
= cast
<ScopeMatcher
>(N
);
266 assert(SM
->getNext() == nullptr && "Scope matcher should not have next");
267 unsigned Size
= 1; // Count the kind.
268 for (unsigned i
= 0, e
= SM
->getNumChildren(); i
!= e
; ++i
) {
269 const unsigned ChildSize
= SizeMatcherList(SM
->getChild(i
), OS
);
270 assert(ChildSize
!= 0 && "Matcher cannot have child of size 0");
271 SM
->getChild(i
)->setSize(ChildSize
);
272 Size
+= GetVBRSize(ChildSize
) + ChildSize
; // Count VBR and child size.
274 ++Size
; // Count the zero sentinel.
278 // SwitchOpcode and SwitchType have their kind, a series of child size +
279 // opcode/type + child, and a trailing zero.
280 case Matcher::SwitchOpcode
:
281 case Matcher::SwitchType
: {
282 unsigned Size
= 1; // Count the kind.
284 if (const SwitchOpcodeMatcher
*SOM
= dyn_cast
<SwitchOpcodeMatcher
>(N
))
285 NumCases
= SOM
->getNumCases();
287 NumCases
= cast
<SwitchTypeMatcher
>(N
)->getNumCases();
288 for (unsigned i
= 0, e
= NumCases
; i
!= e
; ++i
) {
290 if (SwitchOpcodeMatcher
*SOM
= dyn_cast
<SwitchOpcodeMatcher
>(N
)) {
291 Child
= SOM
->getCaseMatcher(i
);
292 Size
+= 2; // Count the child's opcode.
294 Child
= cast
<SwitchTypeMatcher
>(N
)->getCaseMatcher(i
);
295 ++Size
; // Count the child's type.
297 const unsigned ChildSize
= SizeMatcherList(Child
, OS
);
298 assert(ChildSize
!= 0 && "Matcher cannot have child of size 0");
299 Child
->setSize(ChildSize
);
300 Size
+= GetVBRSize(ChildSize
) + ChildSize
; // Count VBR and child size.
302 ++Size
; // Count the zero sentinel.
307 // Employ the matcher emitter to size other matchers.
308 return EmitMatcher(N
, 0, Idx
, OS
);
310 llvm_unreachable("Unreachable");
313 static void BeginEmitFunction(raw_ostream
&OS
, StringRef RetType
,
314 StringRef Decl
, bool AddOverride
) {
315 OS
<< "#ifdef GET_DAGISEL_DECL\n";
316 OS
<< RetType
<< ' ' << Decl
;
321 "#if defined(GET_DAGISEL_BODY) || DAGISEL_INLINE\n";
322 OS
<< RetType
<< " DAGISEL_CLASS_COLONCOLON " << Decl
<< "\n";
324 OS
<< "#if DAGISEL_INLINE\n"
330 static void EndEmitFunction(raw_ostream
&OS
) {
331 OS
<< "#endif // GET_DAGISEL_BODY\n\n";
334 void MatcherTableEmitter::EmitPatternMatchTable(raw_ostream
&OS
) {
336 assert(isUInt
<16>(VecPatterns
.size()) &&
337 "Using only 16 bits to encode offset into Pattern Table");
338 assert(VecPatterns
.size() == VecIncludeStrings
.size() &&
339 "The sizes of Pattern and include vectors should be the same");
341 BeginEmitFunction(OS
, "StringRef", "getPatternForIndex(unsigned Index)",
342 true/*AddOverride*/);
344 OS
<< "static const char *PATTERN_MATCH_TABLE[] = {\n";
346 for (const auto &It
: VecPatterns
) {
347 OS
<< "\"" << It
.first
<< "\",\n";
351 OS
<< "\nreturn StringRef(PATTERN_MATCH_TABLE[Index]);";
355 BeginEmitFunction(OS
, "StringRef", "getIncludePathForIndex(unsigned Index)",
356 true/*AddOverride*/);
358 OS
<< "static const char *INCLUDE_PATH_TABLE[] = {\n";
360 for (const auto &It
: VecIncludeStrings
) {
361 OS
<< "\"" << It
<< "\",\n";
365 OS
<< "\nreturn StringRef(INCLUDE_PATH_TABLE[Index]);";
370 /// EmitMatcher - Emit bytes for the specified matcher and return
371 /// the number of bytes emitted.
372 unsigned MatcherTableEmitter::
373 EmitMatcher(const Matcher
*N
, const unsigned Indent
, unsigned CurrentIdx
,
377 switch (N
->getKind()) {
378 case Matcher::Scope
: {
379 const ScopeMatcher
*SM
= cast
<ScopeMatcher
>(N
);
380 unsigned StartIdx
= CurrentIdx
;
382 // Emit all of the children.
383 for (unsigned i
= 0, e
= SM
->getNumChildren(); i
!= e
; ++i
) {
389 OS
<< "/*" << format_decimal(CurrentIdx
, IndexWidth
) << "*/";
390 OS
.indent(Indent
) << "/*Scope*/ ";
395 unsigned ChildSize
= SM
->getChild(i
)->getSize();
396 unsigned VBRSize
= EmitVBRValue(ChildSize
, OS
);
398 OS
<< "/*->" << CurrentIdx
+ VBRSize
+ ChildSize
<< "*/";
400 OS
<< " // " << SM
->getNumChildren() << " children in Scope";
404 ChildSize
= EmitMatcherList(SM
->getChild(i
), Indent
+1,
405 CurrentIdx
+ VBRSize
, OS
);
406 assert(ChildSize
== SM
->getChild(i
)->getSize() &&
407 "Emitted child size does not match calculated size");
408 CurrentIdx
+= VBRSize
+ ChildSize
;
411 // Emit a zero as a sentinel indicating end of 'Scope'.
413 OS
<< "/*" << format_decimal(CurrentIdx
, IndexWidth
) << "*/";
414 OS
.indent(Indent
) << "0, ";
416 OS
<< "/*End of Scope*/";
418 return CurrentIdx
- StartIdx
+ 1;
421 case Matcher::RecordNode
:
422 OS
<< "OPC_RecordNode,";
425 << cast
<RecordMatcher
>(N
)->getResultNo() << " = "
426 << cast
<RecordMatcher
>(N
)->getWhatFor();
430 case Matcher::RecordChild
:
431 OS
<< "OPC_RecordChild" << cast
<RecordChildMatcher
>(N
)->getChildNo()
435 << cast
<RecordChildMatcher
>(N
)->getResultNo() << " = "
436 << cast
<RecordChildMatcher
>(N
)->getWhatFor();
440 case Matcher::RecordMemRef
:
441 OS
<< "OPC_RecordMemRef,\n";
444 case Matcher::CaptureGlueInput
:
445 OS
<< "OPC_CaptureGlueInput,\n";
448 case Matcher::MoveChild
: {
449 const auto *MCM
= cast
<MoveChildMatcher
>(N
);
451 OS
<< "OPC_MoveChild";
452 // Handle the specialized forms.
453 if (MCM
->getChildNo() >= 8)
455 OS
<< MCM
->getChildNo() << ",\n";
456 return (MCM
->getChildNo() >= 8) ? 2 : 1;
459 case Matcher::MoveParent
:
460 OS
<< "OPC_MoveParent,\n";
463 case Matcher::CheckSame
:
464 OS
<< "OPC_CheckSame, "
465 << cast
<CheckSameMatcher
>(N
)->getMatchNumber() << ",\n";
468 case Matcher::CheckChildSame
:
469 OS
<< "OPC_CheckChild"
470 << cast
<CheckChildSameMatcher
>(N
)->getChildNo() << "Same, "
471 << cast
<CheckChildSameMatcher
>(N
)->getMatchNumber() << ",\n";
474 case Matcher::CheckPatternPredicate
: {
475 StringRef Pred
= cast
<CheckPatternPredicateMatcher
>(N
)->getPredicate();
476 unsigned PredNo
= getPatternPredicate(Pred
);
478 OS
<< "OPC_CheckPatternPredicate2, TARGET_VAL(" << PredNo
<< "),";
480 OS
<< "OPC_CheckPatternPredicate, " << PredNo
<< ',';
482 OS
<< " // " << Pred
;
484 return 2 + (PredNo
> 255);
486 case Matcher::CheckPredicate
: {
487 TreePredicateFn Pred
= cast
<CheckPredicateMatcher
>(N
)->getPredicate();
488 unsigned OperandBytes
= 0;
490 if (Pred
.usesOperands()) {
491 unsigned NumOps
= cast
<CheckPredicateMatcher
>(N
)->getNumOperands();
492 OS
<< "OPC_CheckPredicateWithOperands, " << NumOps
<< "/*#Ops*/, ";
493 for (unsigned i
= 0; i
< NumOps
; ++i
)
494 OS
<< cast
<CheckPredicateMatcher
>(N
)->getOperandNo(i
) << ", ";
495 OperandBytes
= 1 + NumOps
;
497 OS
<< "OPC_CheckPredicate, ";
500 OS
<< getNodePredicate(Pred
) << ',';
502 OS
<< " // " << Pred
.getFnName();
504 return 2 + OperandBytes
;
507 case Matcher::CheckOpcode
:
508 OS
<< "OPC_CheckOpcode, TARGET_VAL("
509 << cast
<CheckOpcodeMatcher
>(N
)->getOpcode().getEnumName() << "),\n";
512 case Matcher::SwitchOpcode
:
513 case Matcher::SwitchType
: {
514 unsigned StartIdx
= CurrentIdx
;
517 if (const SwitchOpcodeMatcher
*SOM
= dyn_cast
<SwitchOpcodeMatcher
>(N
)) {
518 OS
<< "OPC_SwitchOpcode ";
519 NumCases
= SOM
->getNumCases();
521 OS
<< "OPC_SwitchType ";
522 NumCases
= cast
<SwitchTypeMatcher
>(N
)->getNumCases();
526 OS
<< "/*" << NumCases
<< " cases */";
530 // For each case we emit the size, then the opcode, then the matcher.
531 for (unsigned i
= 0, e
= NumCases
; i
!= e
; ++i
) {
532 const Matcher
*Child
;
534 if (const SwitchOpcodeMatcher
*SOM
= dyn_cast
<SwitchOpcodeMatcher
>(N
)) {
535 Child
= SOM
->getCaseMatcher(i
);
536 IdxSize
= 2; // size of opcode in table is 2 bytes.
538 Child
= cast
<SwitchTypeMatcher
>(N
)->getCaseMatcher(i
);
539 IdxSize
= 1; // size of type in table is 1 byte.
544 OS
<< "/*" << format_decimal(CurrentIdx
, IndexWidth
) << "*/";
547 OS
<< (isa
<SwitchOpcodeMatcher
>(N
) ?
548 "/*SwitchOpcode*/ " : "/*SwitchType*/ ");
551 unsigned ChildSize
= Child
->getSize();
552 CurrentIdx
+= EmitVBRValue(ChildSize
, OS
) + IdxSize
;
553 if (const SwitchOpcodeMatcher
*SOM
= dyn_cast
<SwitchOpcodeMatcher
>(N
))
554 OS
<< "TARGET_VAL(" << SOM
->getCaseOpcode(i
).getEnumName() << "),";
556 OS
<< getEnumName(cast
<SwitchTypeMatcher
>(N
)->getCaseType(i
)) << ',';
558 OS
<< "// ->" << CurrentIdx
+ ChildSize
;
561 ChildSize
= EmitMatcherList(Child
, Indent
+1, CurrentIdx
, OS
);
562 assert(ChildSize
== Child
->getSize() &&
563 "Emitted child size does not match calculated size");
564 CurrentIdx
+= ChildSize
;
567 // Emit the final zero to terminate the switch.
569 OS
<< "/*" << format_decimal(CurrentIdx
, IndexWidth
) << "*/";
570 OS
.indent(Indent
) << "0,";
572 OS
<< (isa
<SwitchOpcodeMatcher
>(N
) ?
573 " // EndSwitchOpcode" : " // EndSwitchType");
576 return CurrentIdx
- StartIdx
+ 1;
579 case Matcher::CheckType
:
580 if (cast
<CheckTypeMatcher
>(N
)->getResNo() == 0) {
581 OS
<< "OPC_CheckType, "
582 << getEnumName(cast
<CheckTypeMatcher
>(N
)->getType()) << ",\n";
585 OS
<< "OPC_CheckTypeRes, " << cast
<CheckTypeMatcher
>(N
)->getResNo()
586 << ", " << getEnumName(cast
<CheckTypeMatcher
>(N
)->getType()) << ",\n";
589 case Matcher::CheckChildType
:
590 OS
<< "OPC_CheckChild"
591 << cast
<CheckChildTypeMatcher
>(N
)->getChildNo() << "Type, "
592 << getEnumName(cast
<CheckChildTypeMatcher
>(N
)->getType()) << ",\n";
595 case Matcher::CheckInteger
: {
596 OS
<< "OPC_CheckInteger, ";
598 1 + EmitSignedVBRValue(cast
<CheckIntegerMatcher
>(N
)->getValue(), OS
);
602 case Matcher::CheckChildInteger
: {
603 OS
<< "OPC_CheckChild" << cast
<CheckChildIntegerMatcher
>(N
)->getChildNo()
605 unsigned Bytes
= 1 + EmitSignedVBRValue(
606 cast
<CheckChildIntegerMatcher
>(N
)->getValue(), OS
);
610 case Matcher::CheckCondCode
:
611 OS
<< "OPC_CheckCondCode, ISD::"
612 << cast
<CheckCondCodeMatcher
>(N
)->getCondCodeName() << ",\n";
615 case Matcher::CheckChild2CondCode
:
616 OS
<< "OPC_CheckChild2CondCode, ISD::"
617 << cast
<CheckChild2CondCodeMatcher
>(N
)->getCondCodeName() << ",\n";
620 case Matcher::CheckValueType
:
621 OS
<< "OPC_CheckValueType, MVT::"
622 << cast
<CheckValueTypeMatcher
>(N
)->getTypeName() << ",\n";
625 case Matcher::CheckComplexPat
: {
626 const CheckComplexPatMatcher
*CCPM
= cast
<CheckComplexPatMatcher
>(N
);
627 const ComplexPattern
&Pattern
= CCPM
->getPattern();
628 OS
<< "OPC_CheckComplexPat, /*CP*/" << getComplexPat(Pattern
) << ", /*#*/"
629 << CCPM
->getMatchNumber() << ',';
632 OS
<< " // " << Pattern
.getSelectFunc();
633 OS
<< ":$" << CCPM
->getName();
634 for (unsigned i
= 0, e
= Pattern
.getNumOperands(); i
!= e
; ++i
)
635 OS
<< " #" << CCPM
->getFirstResult()+i
;
637 if (Pattern
.hasProperty(SDNPHasChain
))
638 OS
<< " + chain result";
644 case Matcher::CheckAndImm
: {
645 OS
<< "OPC_CheckAndImm, ";
646 unsigned Bytes
=1+EmitVBRValue(cast
<CheckAndImmMatcher
>(N
)->getValue(), OS
);
651 case Matcher::CheckOrImm
: {
652 OS
<< "OPC_CheckOrImm, ";
653 unsigned Bytes
= 1+EmitVBRValue(cast
<CheckOrImmMatcher
>(N
)->getValue(), OS
);
658 case Matcher::CheckFoldableChainNode
:
659 OS
<< "OPC_CheckFoldableChainNode,\n";
662 case Matcher::CheckImmAllOnesV
:
663 OS
<< "OPC_CheckImmAllOnesV,\n";
666 case Matcher::CheckImmAllZerosV
:
667 OS
<< "OPC_CheckImmAllZerosV,\n";
670 case Matcher::EmitInteger
: {
671 int64_t Val
= cast
<EmitIntegerMatcher
>(N
)->getValue();
672 OS
<< "OPC_EmitInteger, "
673 << getEnumName(cast
<EmitIntegerMatcher
>(N
)->getVT()) << ", ";
674 unsigned Bytes
= 2 + EmitSignedVBRValue(Val
, OS
);
678 case Matcher::EmitStringInteger
: {
679 const std::string
&Val
= cast
<EmitStringIntegerMatcher
>(N
)->getValue();
680 // These should always fit into 7 bits.
681 OS
<< "OPC_EmitStringInteger, "
682 << getEnumName(cast
<EmitStringIntegerMatcher
>(N
)->getVT()) << ", " << Val
687 case Matcher::EmitRegister
: {
688 const EmitRegisterMatcher
*Matcher
= cast
<EmitRegisterMatcher
>(N
);
689 const CodeGenRegister
*Reg
= Matcher
->getReg();
690 // If the enum value of the register is larger than one byte can handle,
691 // use EmitRegister2.
692 if (Reg
&& Reg
->EnumValue
> 255) {
693 OS
<< "OPC_EmitRegister2, " << getEnumName(Matcher
->getVT()) << ", ";
694 OS
<< "TARGET_VAL(" << getQualifiedName(Reg
->TheDef
) << "),\n";
697 OS
<< "OPC_EmitRegister, " << getEnumName(Matcher
->getVT()) << ", ";
699 OS
<< getQualifiedName(Reg
->TheDef
) << ",\n";
703 OS
<< "/*zero_reg*/";
710 case Matcher::EmitConvertToTarget
:
711 OS
<< "OPC_EmitConvertToTarget, "
712 << cast
<EmitConvertToTargetMatcher
>(N
)->getSlot() << ",\n";
715 case Matcher::EmitMergeInputChains
: {
716 const EmitMergeInputChainsMatcher
*MN
=
717 cast
<EmitMergeInputChainsMatcher
>(N
);
719 // Handle the specialized forms OPC_EmitMergeInputChains1_0, 1_1, and 1_2.
720 if (MN
->getNumNodes() == 1 && MN
->getNode(0) < 3) {
721 OS
<< "OPC_EmitMergeInputChains1_" << MN
->getNode(0) << ",\n";
725 OS
<< "OPC_EmitMergeInputChains, " << MN
->getNumNodes() << ", ";
726 for (unsigned i
= 0, e
= MN
->getNumNodes(); i
!= e
; ++i
)
727 OS
<< MN
->getNode(i
) << ", ";
729 return 2+MN
->getNumNodes();
731 case Matcher::EmitCopyToReg
: {
732 const auto *C2RMatcher
= cast
<EmitCopyToRegMatcher
>(N
);
734 const CodeGenRegister
*Reg
= C2RMatcher
->getDestPhysReg();
735 if (Reg
->EnumValue
> 255) {
736 assert(isUInt
<16>(Reg
->EnumValue
) && "not handled");
737 OS
<< "OPC_EmitCopyToReg2, " << C2RMatcher
->getSrcSlot() << ", "
738 << "TARGET_VAL(" << getQualifiedName(Reg
->TheDef
) << "),\n";
741 OS
<< "OPC_EmitCopyToReg, " << C2RMatcher
->getSrcSlot() << ", "
742 << getQualifiedName(Reg
->TheDef
) << ",\n";
747 case Matcher::EmitNodeXForm
: {
748 const EmitNodeXFormMatcher
*XF
= cast
<EmitNodeXFormMatcher
>(N
);
749 OS
<< "OPC_EmitNodeXForm, " << getNodeXFormID(XF
->getNodeXForm()) << ", "
750 << XF
->getSlot() << ',';
752 OS
<< " // "<<XF
->getNodeXForm()->getName();
757 case Matcher::EmitNode
:
758 case Matcher::MorphNodeTo
: {
759 auto NumCoveredBytes
= 0;
760 if (InstrumentCoverage
) {
761 if (const MorphNodeToMatcher
*SNT
= dyn_cast
<MorphNodeToMatcher
>(N
)) {
763 OS
<< "OPC_Coverage, ";
765 GetPatFromTreePatternNode(SNT
->getPattern().getSrcPattern());
767 GetPatFromTreePatternNode(SNT
->getPattern().getDstPattern());
768 Record
*PatRecord
= SNT
->getPattern().getSrcRecord();
769 std::string include_src
= getIncludePath(PatRecord
);
771 getPatternIdxFromTable(src
+ " -> " + dst
, std::move(include_src
));
772 OS
<< "TARGET_VAL(" << Offset
<< "),\n";
773 OS
.indent(FullIndexWidth
+ Indent
);
776 const EmitNodeMatcherCommon
*EN
= cast
<EmitNodeMatcherCommon
>(N
);
777 OS
<< (isa
<EmitNodeMatcher
>(EN
) ? "OPC_EmitNode" : "OPC_MorphNodeTo");
778 bool CompressVTs
= EN
->getNumVTs() < 3;
780 OS
<< EN
->getNumVTs();
782 const CodeGenInstruction
&CGI
= EN
->getInstruction();
783 OS
<< ", TARGET_VAL(" << CGI
.Namespace
<< "::" << CGI
.TheDef
->getName()
786 if (EN
->hasChain()) OS
<< "|OPFL_Chain";
787 if (EN
->hasInGlue()) OS
<< "|OPFL_GlueInput";
788 if (EN
->hasOutGlue()) OS
<< "|OPFL_GlueOutput";
789 if (EN
->hasMemRefs()) OS
<< "|OPFL_MemRefs";
790 if (EN
->getNumFixedArityOperands() != -1)
791 OS
<< "|OPFL_Variadic" << EN
->getNumFixedArityOperands();
794 OS
.indent(FullIndexWidth
+ Indent
+4);
796 OS
<< EN
->getNumVTs();
801 for (unsigned i
= 0, e
= EN
->getNumVTs(); i
!= e
; ++i
)
802 OS
<< getEnumName(EN
->getVT(i
)) << ", ";
804 OS
<< EN
->getNumOperands();
808 unsigned NumOperandBytes
= 0;
809 for (unsigned i
= 0, e
= EN
->getNumOperands(); i
!= e
; ++i
)
810 NumOperandBytes
+= EmitVBRValue(EN
->getOperand(i
), OS
);
813 // Print the result #'s for EmitNode.
814 if (const EmitNodeMatcher
*E
= dyn_cast
<EmitNodeMatcher
>(EN
)) {
815 if (unsigned NumResults
= EN
->getNumVTs()) {
816 OS
<< " // Results =";
817 unsigned First
= E
->getFirstResultSlot();
818 for (unsigned i
= 0; i
!= NumResults
; ++i
)
819 OS
<< " #" << First
+i
;
824 if (const MorphNodeToMatcher
*SNT
= dyn_cast
<MorphNodeToMatcher
>(N
)) {
825 OS
.indent(FullIndexWidth
+ Indent
) << "// Src: "
826 << *SNT
->getPattern().getSrcPattern() << " - Complexity = "
827 << SNT
->getPattern().getPatternComplexity(CGP
) << '\n';
828 OS
.indent(FullIndexWidth
+ Indent
) << "// Dst: "
829 << *SNT
->getPattern().getDstPattern() << '\n';
834 return 5 + !CompressVTs
+ EN
->getNumVTs() + NumOperandBytes
+
837 case Matcher::CompleteMatch
: {
838 const CompleteMatchMatcher
*CM
= cast
<CompleteMatchMatcher
>(N
);
839 auto NumCoveredBytes
= 0;
840 if (InstrumentCoverage
) {
842 OS
<< "OPC_Coverage, ";
844 GetPatFromTreePatternNode(CM
->getPattern().getSrcPattern());
846 GetPatFromTreePatternNode(CM
->getPattern().getDstPattern());
847 Record
*PatRecord
= CM
->getPattern().getSrcRecord();
848 std::string include_src
= getIncludePath(PatRecord
);
850 getPatternIdxFromTable(src
+ " -> " + dst
, std::move(include_src
));
851 OS
<< "TARGET_VAL(" << Offset
<< "),\n";
852 OS
.indent(FullIndexWidth
+ Indent
);
854 OS
<< "OPC_CompleteMatch, " << CM
->getNumResults() << ", ";
855 unsigned NumResultBytes
= 0;
856 for (unsigned i
= 0, e
= CM
->getNumResults(); i
!= e
; ++i
)
857 NumResultBytes
+= EmitVBRValue(CM
->getResult(i
), OS
);
860 OS
.indent(FullIndexWidth
+ Indent
) << " // Src: "
861 << *CM
->getPattern().getSrcPattern() << " - Complexity = "
862 << CM
->getPattern().getPatternComplexity(CGP
) << '\n';
863 OS
.indent(FullIndexWidth
+ Indent
) << " // Dst: "
864 << *CM
->getPattern().getDstPattern();
867 return 2 + NumResultBytes
+ NumCoveredBytes
;
870 llvm_unreachable("Unreachable");
873 /// This function traverses the matcher tree and emits all the nodes.
874 /// The nodes have already been sized.
875 unsigned MatcherTableEmitter::
876 EmitMatcherList(const Matcher
*N
, const unsigned Indent
, unsigned CurrentIdx
,
881 OS
<< "/*" << format_decimal(CurrentIdx
, IndexWidth
) << "*/";
882 unsigned MatcherSize
= EmitMatcher(N
, Indent
, CurrentIdx
, OS
);
884 CurrentIdx
+= MatcherSize
;
886 // If there are other nodes in this list, iterate to them, otherwise we're
893 void MatcherTableEmitter::EmitNodePredicatesFunction(
894 const std::vector
<TreePredicateFn
> &Preds
, StringRef Decl
,
899 BeginEmitFunction(OS
, "bool", Decl
, true/*AddOverride*/);
901 OS
<< " switch (PredNo) {\n";
902 OS
<< " default: llvm_unreachable(\"Invalid predicate in table?\");\n";
903 for (unsigned i
= 0, e
= Preds
.size(); i
!= e
; ++i
) {
904 // Emit the predicate code corresponding to this pattern.
905 const TreePredicateFn PredFn
= Preds
[i
];
906 assert(!PredFn
.isAlwaysTrue() && "No code in this predicate");
907 std::string PredFnCodeStr
= PredFn
.getCodeToRunOnSDNode();
909 OS
<< " case " << i
<< ": {\n";
910 for (auto *SimilarPred
: NodePredicatesByCodeToRun
[PredFnCodeStr
])
911 OS
<< " // " << TreePredicateFn(SimilarPred
).getFnName() << '\n';
912 OS
<< PredFnCodeStr
<< "\n }\n";
919 void MatcherTableEmitter::EmitPredicateFunctions(raw_ostream
&OS
) {
920 // Emit pattern predicates.
921 if (!PatternPredicates
.empty()) {
922 BeginEmitFunction(OS
, "bool",
923 "CheckPatternPredicate(unsigned PredNo) const", true/*AddOverride*/);
925 OS
<< " switch (PredNo) {\n";
926 OS
<< " default: llvm_unreachable(\"Invalid predicate in table?\");\n";
927 for (unsigned i
= 0, e
= PatternPredicates
.size(); i
!= e
; ++i
)
928 OS
<< " case " << i
<< ": return " << PatternPredicates
[i
] << ";\n";
934 // Emit Node predicates.
935 EmitNodePredicatesFunction(
936 NodePredicates
, "CheckNodePredicate(SDNode *Node, unsigned PredNo) const",
938 EmitNodePredicatesFunction(
939 NodePredicatesWithOperands
,
940 "CheckNodePredicateWithOperands(SDNode *Node, unsigned PredNo, "
941 "const SmallVectorImpl<SDValue> &Operands) const",
944 // Emit CompletePattern matchers.
945 // FIXME: This should be const.
946 if (!ComplexPatterns
.empty()) {
947 BeginEmitFunction(OS
, "bool",
948 "CheckComplexPattern(SDNode *Root, SDNode *Parent,\n"
949 " SDValue N, unsigned PatternNo,\n"
950 " SmallVectorImpl<std::pair<SDValue, SDNode *>> &Result)",
951 true/*AddOverride*/);
953 OS
<< " unsigned NextRes = Result.size();\n";
954 OS
<< " switch (PatternNo) {\n";
955 OS
<< " default: llvm_unreachable(\"Invalid pattern # in table?\");\n";
956 for (unsigned i
= 0, e
= ComplexPatterns
.size(); i
!= e
; ++i
) {
957 const ComplexPattern
&P
= *ComplexPatterns
[i
];
958 unsigned NumOps
= P
.getNumOperands();
960 if (P
.hasProperty(SDNPHasChain
))
961 ++NumOps
; // Get the chained node too.
963 OS
<< " case " << i
<< ":\n";
964 if (InstrumentCoverage
)
966 OS
<< " Result.resize(NextRes+" << NumOps
<< ");\n";
967 if (InstrumentCoverage
)
968 OS
<< " bool Succeeded = " << P
.getSelectFunc();
970 OS
<< " return " << P
.getSelectFunc();
973 // If the complex pattern wants the root of the match, pass it in as the
975 if (P
.hasProperty(SDNPWantRoot
))
978 // If the complex pattern wants the parent of the operand being matched,
979 // pass it in as the next argument.
980 if (P
.hasProperty(SDNPWantParent
))
984 for (unsigned i
= 0; i
!= NumOps
; ++i
)
985 OS
<< ", Result[NextRes+" << i
<< "].first";
987 if (InstrumentCoverage
) {
988 OS
<< " if (Succeeded)\n";
989 OS
<< " dbgs() << \"\\nCOMPLEX_PATTERN: " << P
.getSelectFunc()
991 OS
<< " return Succeeded;\n";
1001 // Emit SDNodeXForm handlers.
1002 // FIXME: This should be const.
1003 if (!NodeXForms
.empty()) {
1004 BeginEmitFunction(OS
, "SDValue",
1005 "RunSDNodeXForm(SDValue V, unsigned XFormNo)", true/*AddOverride*/);
1007 OS
<< " switch (XFormNo) {\n";
1008 OS
<< " default: llvm_unreachable(\"Invalid xform # in table?\");\n";
1010 // FIXME: The node xform could take SDValue's instead of SDNode*'s.
1011 for (unsigned i
= 0, e
= NodeXForms
.size(); i
!= e
; ++i
) {
1012 const CodeGenDAGPatterns::NodeXForm
&Entry
=
1013 CGP
.getSDNodeTransform(NodeXForms
[i
]);
1015 Record
*SDNode
= Entry
.first
;
1016 const std::string
&Code
= Entry
.second
;
1018 OS
<< " case " << i
<< ": { ";
1020 OS
<< "// " << NodeXForms
[i
]->getName();
1023 std::string ClassName
=
1024 std::string(CGP
.getSDNodeInfo(SDNode
).getSDClassName());
1025 if (ClassName
== "SDNode")
1026 OS
<< " SDNode *N = V.getNode();\n";
1028 OS
<< " " << ClassName
<< " *N = cast<" << ClassName
1029 << ">(V.getNode());\n";
1030 OS
<< Code
<< "\n }\n";
1034 EndEmitFunction(OS
);
1038 static StringRef
getOpcodeString(Matcher::KindTy Kind
) {
1040 case Matcher::Scope
: return "OPC_Scope"; break;
1041 case Matcher::RecordNode
: return "OPC_RecordNode"; break;
1042 case Matcher::RecordChild
: return "OPC_RecordChild"; break;
1043 case Matcher::RecordMemRef
: return "OPC_RecordMemRef"; break;
1044 case Matcher::CaptureGlueInput
: return "OPC_CaptureGlueInput"; break;
1045 case Matcher::MoveChild
: return "OPC_MoveChild"; break;
1046 case Matcher::MoveParent
: return "OPC_MoveParent"; break;
1047 case Matcher::CheckSame
: return "OPC_CheckSame"; break;
1048 case Matcher::CheckChildSame
: return "OPC_CheckChildSame"; break;
1049 case Matcher::CheckPatternPredicate
:
1050 return "OPC_CheckPatternPredicate"; break;
1051 case Matcher::CheckPredicate
: return "OPC_CheckPredicate"; break;
1052 case Matcher::CheckOpcode
: return "OPC_CheckOpcode"; break;
1053 case Matcher::SwitchOpcode
: return "OPC_SwitchOpcode"; break;
1054 case Matcher::CheckType
: return "OPC_CheckType"; break;
1055 case Matcher::SwitchType
: return "OPC_SwitchType"; break;
1056 case Matcher::CheckChildType
: return "OPC_CheckChildType"; break;
1057 case Matcher::CheckInteger
: return "OPC_CheckInteger"; break;
1058 case Matcher::CheckChildInteger
: return "OPC_CheckChildInteger"; break;
1059 case Matcher::CheckCondCode
: return "OPC_CheckCondCode"; break;
1060 case Matcher::CheckChild2CondCode
: return "OPC_CheckChild2CondCode"; break;
1061 case Matcher::CheckValueType
: return "OPC_CheckValueType"; break;
1062 case Matcher::CheckComplexPat
: return "OPC_CheckComplexPat"; break;
1063 case Matcher::CheckAndImm
: return "OPC_CheckAndImm"; break;
1064 case Matcher::CheckOrImm
: return "OPC_CheckOrImm"; break;
1065 case Matcher::CheckFoldableChainNode
:
1066 return "OPC_CheckFoldableChainNode"; break;
1067 case Matcher::CheckImmAllOnesV
: return "OPC_CheckImmAllOnesV"; break;
1068 case Matcher::CheckImmAllZerosV
: return "OPC_CheckImmAllZerosV"; break;
1069 case Matcher::EmitInteger
: return "OPC_EmitInteger"; break;
1070 case Matcher::EmitStringInteger
: return "OPC_EmitStringInteger"; break;
1071 case Matcher::EmitRegister
: return "OPC_EmitRegister"; break;
1072 case Matcher::EmitConvertToTarget
: return "OPC_EmitConvertToTarget"; break;
1073 case Matcher::EmitMergeInputChains
: return "OPC_EmitMergeInputChains"; break;
1074 case Matcher::EmitCopyToReg
: return "OPC_EmitCopyToReg"; break;
1075 case Matcher::EmitNode
: return "OPC_EmitNode"; break;
1076 case Matcher::MorphNodeTo
: return "OPC_MorphNodeTo"; break;
1077 case Matcher::EmitNodeXForm
: return "OPC_EmitNodeXForm"; break;
1078 case Matcher::CompleteMatch
: return "OPC_CompleteMatch"; break;
1081 llvm_unreachable("Unhandled opcode?");
1084 void MatcherTableEmitter::EmitHistogram(const Matcher
*M
,
1089 OS
<< " // Opcode Histogram:\n";
1090 for (unsigned i
= 0, e
= OpcodeCounts
.size(); i
!= e
; ++i
) {
1092 << left_justify(getOpcodeString((Matcher::KindTy
)i
), HistOpcWidth
)
1093 << " = " << OpcodeCounts
[i
] << '\n';
1099 void llvm::EmitMatcherTable(Matcher
*TheMatcher
,
1100 const CodeGenDAGPatterns
&CGP
,
1102 OS
<< "#if defined(GET_DAGISEL_DECL) && defined(GET_DAGISEL_BODY)\n";
1103 OS
<< "#error GET_DAGISEL_DECL and GET_DAGISEL_BODY cannot be both defined, ";
1104 OS
<< "undef both for inline definitions\n";
1107 // Emit a check for omitted class name.
1108 OS
<< "#ifdef GET_DAGISEL_BODY\n";
1109 OS
<< "#define LOCAL_DAGISEL_STRINGIZE(X) LOCAL_DAGISEL_STRINGIZE_(X)\n";
1110 OS
<< "#define LOCAL_DAGISEL_STRINGIZE_(X) #X\n";
1111 OS
<< "static_assert(sizeof(LOCAL_DAGISEL_STRINGIZE(GET_DAGISEL_BODY)) > 1,"
1113 OS
<< " \"GET_DAGISEL_BODY is empty: it should be defined with the class "
1115 OS
<< "#undef LOCAL_DAGISEL_STRINGIZE_\n";
1116 OS
<< "#undef LOCAL_DAGISEL_STRINGIZE\n";
1119 OS
<< "#if !defined(GET_DAGISEL_DECL) && !defined(GET_DAGISEL_BODY)\n";
1120 OS
<< "#define DAGISEL_INLINE 1\n";
1122 OS
<< "#define DAGISEL_INLINE 0\n";
1125 OS
<< "#if !DAGISEL_INLINE\n";
1126 OS
<< "#define DAGISEL_CLASS_COLONCOLON GET_DAGISEL_BODY ::\n";
1128 OS
<< "#define DAGISEL_CLASS_COLONCOLON\n";
1131 BeginEmitFunction(OS
, "void", "SelectCode(SDNode *N)", false/*AddOverride*/);
1132 MatcherTableEmitter
MatcherEmitter(CGP
);
1134 // First we size all the children of the three kinds of matchers that have
1135 // them. This is done by sharing the code in EmitMatcher(). but we don't
1136 // want to emit anything, so we turn off comments and use a null stream.
1137 bool SaveOmitComments
= OmitComments
;
1138 OmitComments
= true;
1139 raw_null_ostream NullOS
;
1140 unsigned TotalSize
= MatcherEmitter
.SizeMatcherList(TheMatcher
, NullOS
);
1141 OmitComments
= SaveOmitComments
;
1143 // Now that the matchers are sized, we can emit the code for them to the
1146 OS
<< " // Some target values are emitted as 2 bytes, TARGET_VAL handles\n";
1147 OS
<< " // this.\n";
1148 OS
<< " #define TARGET_VAL(X) X & 255, unsigned(X) >> 8\n";
1149 OS
<< " static const unsigned char MatcherTable[] = {\n";
1150 TotalSize
= MatcherEmitter
.EmitMatcherList(TheMatcher
, 1, 0, OS
);
1151 OS
<< " 0\n }; // Total Array size is " << (TotalSize
+1) << " bytes\n\n";
1153 MatcherEmitter
.EmitHistogram(TheMatcher
, OS
);
1155 OS
<< " #undef TARGET_VAL\n";
1156 OS
<< " SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n";
1158 EndEmitFunction(OS
);
1160 // Next up, emit the function for node and pattern predicates:
1161 MatcherEmitter
.EmitPredicateFunctions(OS
);
1163 if (InstrumentCoverage
)
1164 MatcherEmitter
.EmitPatternMatchTable(OS
);
1166 // Clean up the preprocessor macros.
1168 OS
<< "#ifdef DAGISEL_INLINE\n";
1169 OS
<< "#undef DAGISEL_INLINE\n";
1171 OS
<< "#ifdef DAGISEL_CLASS_COLONCOLON\n";
1172 OS
<< "#undef DAGISEL_CLASS_COLONCOLON\n";
1174 OS
<< "#ifdef GET_DAGISEL_DECL\n";
1175 OS
<< "#undef GET_DAGISEL_DECL\n";
1177 OS
<< "#ifdef GET_DAGISEL_BODY\n";
1178 OS
<< "#undef GET_DAGISEL_BODY\n";