[RISCV] Rename Mips instruction records to start with MIPS_. NFC (#125170)
[llvm-project.git] / llvm / utils / TableGen / DAGISelMatcherEmitter.cpp
blobf056306b2f8571defd981739e65f268399380aa0
1 //===- DAGISelMatcherEmitter.cpp - Matcher Emitter ------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains code to generate C++ code for a matcher.
11 //===----------------------------------------------------------------------===//
13 #include "Basic/SDNodeProperties.h"
14 #include "Common/CodeGenDAGPatterns.h"
15 #include "Common/CodeGenInstruction.h"
16 #include "Common/CodeGenRegisters.h"
17 #include "Common/CodeGenTarget.h"
18 #include "Common/DAGISelMatcher.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"
29 using namespace llvm;
31 enum {
32 IndexWidth = 6,
33 FullIndexWidth = IndexWidth + 4,
34 HistOpcWidth = 40,
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));
49 namespace {
50 class MatcherTableEmitter {
51 const CodeGenDAGPatterns &CGP;
53 SmallVector<unsigned, Matcher::HighestKind + 1> OpcodeCounts;
55 std::vector<TreePattern *> NodePredicates;
56 std::vector<TreePattern *> NodePredicatesWithOperands;
58 // We de-duplicate the predicates by code string, and use this map to track
59 // all the patterns with "identical" predicates.
60 MapVector<std::string, TinyPtrVector<TreePattern *>, StringMap<unsigned>>
61 NodePredicatesByCodeToRun;
63 std::vector<std::string> PatternPredicates;
65 std::vector<const ComplexPattern *> ComplexPatterns;
67 DenseMap<const Record *, unsigned> NodeXFormMap;
68 std::vector<const Record *> NodeXForms;
70 std::vector<std::string> VecIncludeStrings;
71 MapVector<std::string, unsigned, StringMap<unsigned>> VecPatterns;
73 unsigned getPatternIdxFromTable(std::string &&P, std::string &&include_loc) {
74 const auto [It, Inserted] =
75 VecPatterns.try_emplace(std::move(P), VecPatterns.size());
76 if (Inserted) {
77 VecIncludeStrings.push_back(std::move(include_loc));
78 return VecIncludeStrings.size() - 1;
80 return It->second;
83 public:
84 MatcherTableEmitter(const Matcher *TheMatcher, const CodeGenDAGPatterns &cgp)
85 : CGP(cgp), OpcodeCounts(Matcher::HighestKind + 1, 0) {
86 // Record the usage of ComplexPattern.
87 MapVector<const ComplexPattern *, unsigned> ComplexPatternUsage;
88 // Record the usage of PatternPredicate.
89 MapVector<StringRef, unsigned> PatternPredicateUsage;
90 // Record the usage of Predicate.
91 MapVector<TreePattern *, unsigned> PredicateUsage;
93 // Iterate the whole MatcherTable once and do some statistics.
94 std::function<void(const Matcher *)> Statistic = [&](const Matcher *N) {
95 while (N) {
96 if (auto *SM = dyn_cast<ScopeMatcher>(N))
97 for (unsigned I = 0; I < SM->getNumChildren(); I++)
98 Statistic(SM->getChild(I));
99 else if (auto *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
100 for (unsigned I = 0; I < SOM->getNumCases(); I++)
101 Statistic(SOM->getCaseMatcher(I));
102 else if (auto *STM = dyn_cast<SwitchTypeMatcher>(N))
103 for (unsigned I = 0; I < STM->getNumCases(); I++)
104 Statistic(STM->getCaseMatcher(I));
105 else if (auto *CPM = dyn_cast<CheckComplexPatMatcher>(N))
106 ++ComplexPatternUsage[&CPM->getPattern()];
107 else if (auto *CPPM = dyn_cast<CheckPatternPredicateMatcher>(N))
108 ++PatternPredicateUsage[CPPM->getPredicate()];
109 else if (auto *PM = dyn_cast<CheckPredicateMatcher>(N))
110 ++PredicateUsage[PM->getPredicate().getOrigPatFragRecord()];
111 N = N->getNext();
114 Statistic(TheMatcher);
116 // Sort ComplexPatterns by usage.
117 std::vector<std::pair<const ComplexPattern *, unsigned>> ComplexPatternList(
118 ComplexPatternUsage.begin(), ComplexPatternUsage.end());
119 stable_sort(ComplexPatternList, [](const auto &A, const auto &B) {
120 return A.second > B.second;
122 for (const auto &ComplexPattern : ComplexPatternList)
123 ComplexPatterns.push_back(ComplexPattern.first);
125 // Sort PatternPredicates by usage.
126 std::vector<std::pair<std::string, unsigned>> PatternPredicateList(
127 PatternPredicateUsage.begin(), PatternPredicateUsage.end());
128 stable_sort(PatternPredicateList, [](const auto &A, const auto &B) {
129 return A.second > B.second;
131 for (const auto &PatternPredicate : PatternPredicateList)
132 PatternPredicates.push_back(PatternPredicate.first);
134 // Sort Predicates by usage.
135 // Merge predicates with same code.
136 for (const auto &Usage : PredicateUsage) {
137 TreePattern *TP = Usage.first;
138 TreePredicateFn Pred(TP);
139 NodePredicatesByCodeToRun[Pred.getCodeToRunOnSDNode()].push_back(TP);
142 std::vector<std::pair<TreePattern *, unsigned>> PredicateList;
143 // Sum the usage.
144 for (auto &Predicate : NodePredicatesByCodeToRun) {
145 TinyPtrVector<TreePattern *> &TPs = Predicate.second;
146 stable_sort(TPs, [](const auto *A, const auto *B) {
147 return A->getRecord()->getName() < B->getRecord()->getName();
149 unsigned Uses = 0;
150 for (TreePattern *TP : TPs)
151 Uses += PredicateUsage[TP];
153 // We only add the first predicate here since they are with the same code.
154 PredicateList.push_back({TPs[0], Uses});
157 stable_sort(PredicateList, [](const auto &A, const auto &B) {
158 return A.second > B.second;
160 for (const auto &Predicate : PredicateList) {
161 TreePattern *TP = Predicate.first;
162 if (TreePredicateFn(TP).usesOperands())
163 NodePredicatesWithOperands.push_back(TP);
164 else
165 NodePredicates.push_back(TP);
169 unsigned EmitMatcherList(const Matcher *N, const unsigned Indent,
170 unsigned StartIdx, raw_ostream &OS);
172 unsigned SizeMatcherList(Matcher *N, raw_ostream &OS);
174 void EmitPredicateFunctions(raw_ostream &OS);
176 void EmitHistogram(const Matcher *N, raw_ostream &OS);
178 void EmitPatternMatchTable(raw_ostream &OS);
180 private:
181 void EmitNodePredicatesFunction(const std::vector<TreePattern *> &Preds,
182 StringRef Decl, raw_ostream &OS);
184 unsigned SizeMatcher(Matcher *N, raw_ostream &OS);
186 unsigned EmitMatcher(const Matcher *N, const unsigned Indent,
187 unsigned CurrentIdx, raw_ostream &OS);
189 unsigned getNodePredicate(TreePredicateFn Pred) {
190 // We use the first predicate.
191 TreePattern *PredPat =
192 NodePredicatesByCodeToRun[Pred.getCodeToRunOnSDNode()][0];
193 return Pred.usesOperands()
194 ? llvm::find(NodePredicatesWithOperands, PredPat) -
195 NodePredicatesWithOperands.begin()
196 : llvm::find(NodePredicates, PredPat) - NodePredicates.begin();
199 unsigned getPatternPredicate(StringRef PredName) {
200 return llvm::find(PatternPredicates, PredName) - PatternPredicates.begin();
202 unsigned getComplexPat(const ComplexPattern &P) {
203 return llvm::find(ComplexPatterns, &P) - ComplexPatterns.begin();
206 unsigned getNodeXFormID(const Record *Rec) {
207 unsigned &Entry = NodeXFormMap[Rec];
208 if (Entry == 0) {
209 NodeXForms.push_back(Rec);
210 Entry = NodeXForms.size();
212 return Entry - 1;
215 } // end anonymous namespace.
217 static std::string GetPatFromTreePatternNode(const TreePatternNode &N) {
218 std::string str;
219 raw_string_ostream Stream(str);
220 Stream << N;
221 return str;
224 static unsigned GetVBRSize(unsigned Val) {
225 if (Val <= 127)
226 return 1;
228 unsigned NumBytes = 0;
229 while (Val >= 128) {
230 Val >>= 7;
231 ++NumBytes;
233 return NumBytes + 1;
236 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
237 /// bytes emitted.
238 static unsigned EmitVBRValue(uint64_t Val, raw_ostream &OS) {
239 if (Val <= 127) {
240 OS << Val << ", ";
241 return 1;
244 uint64_t InVal = Val;
245 unsigned NumBytes = 0;
246 while (Val >= 128) {
247 OS << (Val & 127) << "|128,";
248 Val >>= 7;
249 ++NumBytes;
251 OS << Val;
252 if (!OmitComments)
253 OS << "/*" << InVal << "*/";
254 OS << ", ";
255 return NumBytes + 1;
258 /// Emit the specified signed value as a VBR. To improve compression we encode
259 /// positive numbers shifted left by 1 and negative numbers negated and shifted
260 /// left by 1 with bit 0 set.
261 static unsigned EmitSignedVBRValue(uint64_t Val, raw_ostream &OS) {
262 if ((int64_t)Val >= 0)
263 Val = Val << 1;
264 else
265 Val = (-Val << 1) | 1;
267 return EmitVBRValue(Val, OS);
270 // This is expensive and slow.
271 static std::string getIncludePath(const Record *R) {
272 std::string str;
273 raw_string_ostream Stream(str);
274 auto Locs = R->getLoc();
275 SMLoc L;
276 if (Locs.size() > 1) {
277 // Get where the pattern prototype was instantiated
278 L = Locs[1];
279 } else if (Locs.size() == 1) {
280 L = Locs[0];
282 unsigned CurBuf = SrcMgr.FindBufferContainingLoc(L);
283 assert(CurBuf && "Invalid or unspecified location!");
285 Stream << SrcMgr.getBufferInfo(CurBuf).Buffer->getBufferIdentifier() << ":"
286 << SrcMgr.FindLineNumber(L, CurBuf);
287 return str;
290 /// This function traverses the matcher tree and sizes all the nodes
291 /// that are children of the three kinds of nodes that have them.
292 unsigned MatcherTableEmitter::SizeMatcherList(Matcher *N, raw_ostream &OS) {
293 unsigned Size = 0;
294 while (N) {
295 Size += SizeMatcher(N, OS);
296 N = N->getNext();
298 return Size;
301 /// This function sizes the children of the three kinds of nodes that
302 /// have them. It does so by using special cases for those three
303 /// nodes, but sharing the code in EmitMatcher() for the other kinds.
304 unsigned MatcherTableEmitter::SizeMatcher(Matcher *N, raw_ostream &OS) {
305 unsigned Idx = 0;
307 ++OpcodeCounts[N->getKind()];
308 switch (N->getKind()) {
309 // The Scope matcher has its kind, a series of child size + child,
310 // and a trailing zero.
311 case Matcher::Scope: {
312 ScopeMatcher *SM = cast<ScopeMatcher>(N);
313 assert(SM->getNext() == nullptr && "Scope matcher should not have next");
314 unsigned Size = 1; // Count the kind.
315 for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
316 const unsigned ChildSize = SizeMatcherList(SM->getChild(i), OS);
317 assert(ChildSize != 0 && "Matcher cannot have child of size 0");
318 SM->getChild(i)->setSize(ChildSize);
319 Size += GetVBRSize(ChildSize) + ChildSize; // Count VBR and child size.
321 ++Size; // Count the zero sentinel.
322 return Size;
325 // SwitchOpcode and SwitchType have their kind, a series of child size +
326 // opcode/type + child, and a trailing zero.
327 case Matcher::SwitchOpcode:
328 case Matcher::SwitchType: {
329 unsigned Size = 1; // Count the kind.
330 unsigned NumCases;
331 if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
332 NumCases = SOM->getNumCases();
333 else
334 NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
335 for (unsigned i = 0, e = NumCases; i != e; ++i) {
336 Matcher *Child;
337 if (SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
338 Child = SOM->getCaseMatcher(i);
339 Size += 2; // Count the child's opcode.
340 } else {
341 Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
342 Size += GetVBRSize(cast<SwitchTypeMatcher>(N)->getCaseType(
343 i)); // Count the child's type.
345 const unsigned ChildSize = SizeMatcherList(Child, OS);
346 assert(ChildSize != 0 && "Matcher cannot have child of size 0");
347 Child->setSize(ChildSize);
348 Size += GetVBRSize(ChildSize) + ChildSize; // Count VBR and child size.
350 ++Size; // Count the zero sentinel.
351 return Size;
354 default:
355 // Employ the matcher emitter to size other matchers.
356 return EmitMatcher(N, 0, Idx, OS);
358 llvm_unreachable("Unreachable");
361 static void BeginEmitFunction(raw_ostream &OS, StringRef RetType,
362 StringRef Decl, bool AddOverride) {
363 OS << "#ifdef GET_DAGISEL_DECL\n";
364 OS << RetType << ' ' << Decl;
365 if (AddOverride)
366 OS << " override";
367 OS << ";\n"
368 "#endif\n"
369 "#if defined(GET_DAGISEL_BODY) || DAGISEL_INLINE\n";
370 OS << RetType << " DAGISEL_CLASS_COLONCOLON " << Decl << "\n";
371 if (AddOverride) {
372 OS << "#if DAGISEL_INLINE\n"
373 " override\n"
374 "#endif\n";
378 static void EndEmitFunction(raw_ostream &OS) {
379 OS << "#endif // GET_DAGISEL_BODY\n\n";
382 void MatcherTableEmitter::EmitPatternMatchTable(raw_ostream &OS) {
384 if (!isUInt<32>(VecPatterns.size()))
385 report_fatal_error("More patterns defined that can fit into 32-bit Pattern "
386 "Table index encoding");
388 assert(VecPatterns.size() == VecIncludeStrings.size() &&
389 "The sizes of Pattern and include vectors should be the same");
391 BeginEmitFunction(OS, "StringRef", "getPatternForIndex(unsigned Index)",
392 true /*AddOverride*/);
393 OS << "{\n";
394 OS << "static const char *PATTERN_MATCH_TABLE[] = {\n";
396 for (const auto &It : VecPatterns) {
397 OS << "\"" << It.first << "\",\n";
400 OS << "\n};";
401 OS << "\nreturn StringRef(PATTERN_MATCH_TABLE[Index]);";
402 OS << "\n}\n";
403 EndEmitFunction(OS);
405 BeginEmitFunction(OS, "StringRef", "getIncludePathForIndex(unsigned Index)",
406 true /*AddOverride*/);
407 OS << "{\n";
408 OS << "static const char *INCLUDE_PATH_TABLE[] = {\n";
410 for (const auto &It : VecIncludeStrings) {
411 OS << "\"" << It << "\",\n";
414 OS << "\n};";
415 OS << "\nreturn StringRef(INCLUDE_PATH_TABLE[Index]);";
416 OS << "\n}\n";
417 EndEmitFunction(OS);
420 /// EmitMatcher - Emit bytes for the specified matcher and return
421 /// the number of bytes emitted.
422 unsigned MatcherTableEmitter::EmitMatcher(const Matcher *N,
423 const unsigned Indent,
424 unsigned CurrentIdx,
425 raw_ostream &OS) {
426 OS.indent(Indent);
428 switch (N->getKind()) {
429 case Matcher::Scope: {
430 const ScopeMatcher *SM = cast<ScopeMatcher>(N);
431 unsigned StartIdx = CurrentIdx;
433 // Emit all of the children.
434 for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
435 if (i == 0) {
436 OS << "OPC_Scope, ";
437 ++CurrentIdx;
438 } else {
439 if (!OmitComments) {
440 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
441 OS.indent(Indent) << "/*Scope*/ ";
442 } else
443 OS.indent(Indent);
446 unsigned ChildSize = SM->getChild(i)->getSize();
447 unsigned VBRSize = EmitVBRValue(ChildSize, OS);
448 if (!OmitComments) {
449 OS << "/*->" << CurrentIdx + VBRSize + ChildSize << "*/";
450 if (i == 0)
451 OS << " // " << SM->getNumChildren() << " children in Scope";
453 OS << '\n';
455 ChildSize = EmitMatcherList(SM->getChild(i), Indent + 1,
456 CurrentIdx + VBRSize, OS);
457 assert(ChildSize == SM->getChild(i)->getSize() &&
458 "Emitted child size does not match calculated size");
459 CurrentIdx += VBRSize + ChildSize;
462 // Emit a zero as a sentinel indicating end of 'Scope'.
463 if (!OmitComments)
464 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
465 OS.indent(Indent) << "0, ";
466 if (!OmitComments)
467 OS << "/*End of Scope*/";
468 OS << '\n';
469 return CurrentIdx - StartIdx + 1;
472 case Matcher::RecordNode:
473 OS << "OPC_RecordNode,";
474 if (!OmitComments)
475 OS << " // #" << cast<RecordMatcher>(N)->getResultNo() << " = "
476 << cast<RecordMatcher>(N)->getWhatFor();
477 OS << '\n';
478 return 1;
480 case Matcher::RecordChild:
481 OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo() << ',';
482 if (!OmitComments)
483 OS << " // #" << cast<RecordChildMatcher>(N)->getResultNo() << " = "
484 << cast<RecordChildMatcher>(N)->getWhatFor();
485 OS << '\n';
486 return 1;
488 case Matcher::RecordMemRef:
489 OS << "OPC_RecordMemRef,\n";
490 return 1;
492 case Matcher::CaptureGlueInput:
493 OS << "OPC_CaptureGlueInput,\n";
494 return 1;
496 case Matcher::MoveChild: {
497 const auto *MCM = cast<MoveChildMatcher>(N);
499 OS << "OPC_MoveChild";
500 // Handle the specialized forms.
501 if (MCM->getChildNo() >= 8)
502 OS << ", ";
503 OS << MCM->getChildNo() << ",\n";
504 return (MCM->getChildNo() >= 8) ? 2 : 1;
507 case Matcher::MoveSibling: {
508 const auto *MSM = cast<MoveSiblingMatcher>(N);
510 OS << "OPC_MoveSibling";
511 // Handle the specialized forms.
512 if (MSM->getSiblingNo() >= 8)
513 OS << ", ";
514 OS << MSM->getSiblingNo() << ",\n";
515 return (MSM->getSiblingNo() >= 8) ? 2 : 1;
518 case Matcher::MoveParent:
519 OS << "OPC_MoveParent,\n";
520 return 1;
522 case Matcher::CheckSame:
523 OS << "OPC_CheckSame, " << cast<CheckSameMatcher>(N)->getMatchNumber()
524 << ",\n";
525 return 2;
527 case Matcher::CheckChildSame:
528 OS << "OPC_CheckChild" << cast<CheckChildSameMatcher>(N)->getChildNo()
529 << "Same, " << cast<CheckChildSameMatcher>(N)->getMatchNumber() << ",\n";
530 return 2;
532 case Matcher::CheckPatternPredicate: {
533 StringRef Pred = cast<CheckPatternPredicateMatcher>(N)->getPredicate();
534 unsigned PredNo = getPatternPredicate(Pred);
535 if (PredNo > 255)
536 OS << "OPC_CheckPatternPredicateTwoByte, TARGET_VAL(" << PredNo << "),";
537 else if (PredNo < 8)
538 OS << "OPC_CheckPatternPredicate" << PredNo << ',';
539 else
540 OS << "OPC_CheckPatternPredicate, " << PredNo << ',';
541 if (!OmitComments)
542 OS << " // " << Pred;
543 OS << '\n';
544 return 2 + (PredNo > 255) - (PredNo < 8);
546 case Matcher::CheckPredicate: {
547 TreePredicateFn Pred = cast<CheckPredicateMatcher>(N)->getPredicate();
548 unsigned OperandBytes = 0;
549 unsigned PredNo = getNodePredicate(Pred);
551 if (Pred.usesOperands()) {
552 unsigned NumOps = cast<CheckPredicateMatcher>(N)->getNumOperands();
553 OS << "OPC_CheckPredicateWithOperands, " << NumOps << "/*#Ops*/, ";
554 for (unsigned i = 0; i < NumOps; ++i)
555 OS << cast<CheckPredicateMatcher>(N)->getOperandNo(i) << ", ";
556 OperandBytes = 1 + NumOps;
557 } else {
558 if (PredNo < 8) {
559 OperandBytes = -1;
560 OS << "OPC_CheckPredicate" << PredNo << ", ";
561 } else
562 OS << "OPC_CheckPredicate, ";
565 if (PredNo >= 8 || Pred.usesOperands())
566 OS << PredNo << ',';
567 if (!OmitComments)
568 OS << " // " << Pred.getFnName();
569 OS << '\n';
570 return 2 + OperandBytes;
573 case Matcher::CheckOpcode:
574 OS << "OPC_CheckOpcode, TARGET_VAL("
575 << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << "),\n";
576 return 3;
578 case Matcher::SwitchOpcode:
579 case Matcher::SwitchType: {
580 unsigned StartIdx = CurrentIdx;
582 unsigned NumCases;
583 if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
584 OS << "OPC_SwitchOpcode ";
585 NumCases = SOM->getNumCases();
586 } else {
587 OS << "OPC_SwitchType ";
588 NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
591 if (!OmitComments)
592 OS << "/*" << NumCases << " cases */";
593 OS << ", ";
594 ++CurrentIdx;
596 // For each case we emit the size, then the opcode, then the matcher.
597 for (unsigned i = 0, e = NumCases; i != e; ++i) {
598 const Matcher *Child;
599 unsigned IdxSize;
600 if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
601 Child = SOM->getCaseMatcher(i);
602 IdxSize = 2; // size of opcode in table is 2 bytes.
603 } else {
604 Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
605 IdxSize = GetVBRSize(cast<SwitchTypeMatcher>(N)->getCaseType(
606 i)); // size of type in table is sizeof(VBR(MVT)) byte.
609 if (i != 0) {
610 if (!OmitComments)
611 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
612 OS.indent(Indent);
613 if (!OmitComments)
614 OS << (isa<SwitchOpcodeMatcher>(N) ? "/*SwitchOpcode*/ "
615 : "/*SwitchType*/ ");
618 unsigned ChildSize = Child->getSize();
619 CurrentIdx += EmitVBRValue(ChildSize, OS) + IdxSize;
620 if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
621 OS << "TARGET_VAL(" << SOM->getCaseOpcode(i).getEnumName() << "),";
622 else {
623 if (!OmitComments)
624 OS << "/*" << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i))
625 << "*/";
626 EmitVBRValue(cast<SwitchTypeMatcher>(N)->getCaseType(i),
627 OS);
629 if (!OmitComments)
630 OS << "// ->" << CurrentIdx + ChildSize;
631 OS << '\n';
633 ChildSize = EmitMatcherList(Child, Indent + 1, CurrentIdx, OS);
634 assert(ChildSize == Child->getSize() &&
635 "Emitted child size does not match calculated size");
636 CurrentIdx += ChildSize;
639 // Emit the final zero to terminate the switch.
640 if (!OmitComments)
641 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
642 OS.indent(Indent) << "0,";
643 if (!OmitComments)
644 OS << (isa<SwitchOpcodeMatcher>(N) ? " // EndSwitchOpcode"
645 : " // EndSwitchType");
647 OS << '\n';
648 return CurrentIdx - StartIdx + 1;
651 case Matcher::CheckType: {
652 if (cast<CheckTypeMatcher>(N)->getResNo() == 0) {
653 MVT::SimpleValueType VT = cast<CheckTypeMatcher>(N)->getType();
654 switch (VT) {
655 case MVT::i32:
656 case MVT::i64:
657 OS << "OPC_CheckTypeI" << MVT(VT).getSizeInBits() << ",\n";
658 return 1;
659 default:
660 OS << "OPC_CheckType, ";
661 if (!OmitComments)
662 OS << "/*" << getEnumName(VT) << "*/";
663 unsigned NumBytes = EmitVBRValue(VT, OS);
664 OS << "\n";
665 return NumBytes + 1;
668 OS << "OPC_CheckTypeRes, " << cast<CheckTypeMatcher>(N)->getResNo() << ", ";
669 if (!OmitComments)
670 OS << "/*" << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << "*/";
671 unsigned NumBytes = EmitVBRValue(cast<CheckTypeMatcher>(N)->getType(), OS);
672 OS << "\n";
673 return NumBytes + 2;
676 case Matcher::CheckChildType: {
677 MVT::SimpleValueType VT = cast<CheckChildTypeMatcher>(N)->getType();
678 switch (VT) {
679 case MVT::i32:
680 case MVT::i64:
681 OS << "OPC_CheckChild" << cast<CheckChildTypeMatcher>(N)->getChildNo()
682 << "TypeI" << MVT(VT).getSizeInBits() << ",\n";
683 return 1;
684 default:
685 OS << "OPC_CheckChild" << cast<CheckChildTypeMatcher>(N)->getChildNo()
686 << "Type, ";
687 if (!OmitComments)
688 OS << "/*" << getEnumName(VT) << "*/";
689 unsigned NumBytes = EmitVBRValue(VT, OS);
690 OS << "\n";
691 return NumBytes + 1;
695 case Matcher::CheckInteger: {
696 OS << "OPC_CheckInteger, ";
697 unsigned Bytes =
698 1 + EmitSignedVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
699 OS << '\n';
700 return Bytes;
702 case Matcher::CheckChildInteger: {
703 OS << "OPC_CheckChild" << cast<CheckChildIntegerMatcher>(N)->getChildNo()
704 << "Integer, ";
705 unsigned Bytes = 1 + EmitSignedVBRValue(
706 cast<CheckChildIntegerMatcher>(N)->getValue(), OS);
707 OS << '\n';
708 return Bytes;
710 case Matcher::CheckCondCode:
711 OS << "OPC_CheckCondCode, ISD::"
712 << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
713 return 2;
715 case Matcher::CheckChild2CondCode:
716 OS << "OPC_CheckChild2CondCode, ISD::"
717 << cast<CheckChild2CondCodeMatcher>(N)->getCondCodeName() << ",\n";
718 return 2;
720 case Matcher::CheckValueType: {
721 OS << "OPC_CheckValueType, ";
722 if (!OmitComments)
723 OS << "/*" << getEnumName(cast<CheckValueTypeMatcher>(N)->getVT())
724 << "*/";
725 unsigned NumBytes =
726 EmitVBRValue(cast<CheckValueTypeMatcher>(N)->getVT(), OS);
727 OS << "\n";
728 return NumBytes + 1;
731 case Matcher::CheckComplexPat: {
732 const CheckComplexPatMatcher *CCPM = cast<CheckComplexPatMatcher>(N);
733 const ComplexPattern &Pattern = CCPM->getPattern();
734 unsigned PatternNo = getComplexPat(Pattern);
735 if (PatternNo < 8)
736 OS << "OPC_CheckComplexPat" << PatternNo << ", /*#*/"
737 << CCPM->getMatchNumber() << ',';
738 else
739 OS << "OPC_CheckComplexPat, /*CP*/" << PatternNo << ", /*#*/"
740 << CCPM->getMatchNumber() << ',';
742 if (!OmitComments) {
743 OS << " // " << Pattern.getSelectFunc();
744 OS << ":$" << CCPM->getName();
745 for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i)
746 OS << " #" << CCPM->getFirstResult() + i;
748 if (Pattern.hasProperty(SDNPHasChain))
749 OS << " + chain result";
751 OS << '\n';
752 return PatternNo < 8 ? 2 : 3;
755 case Matcher::CheckAndImm: {
756 OS << "OPC_CheckAndImm, ";
757 unsigned Bytes =
758 1 + EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
759 OS << '\n';
760 return Bytes;
763 case Matcher::CheckOrImm: {
764 OS << "OPC_CheckOrImm, ";
765 unsigned Bytes =
766 1 + EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
767 OS << '\n';
768 return Bytes;
771 case Matcher::CheckFoldableChainNode:
772 OS << "OPC_CheckFoldableChainNode,\n";
773 return 1;
775 case Matcher::CheckImmAllOnesV:
776 OS << "OPC_CheckImmAllOnesV,\n";
777 return 1;
779 case Matcher::CheckImmAllZerosV:
780 OS << "OPC_CheckImmAllZerosV,\n";
781 return 1;
783 case Matcher::EmitInteger: {
784 int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
785 MVT::SimpleValueType VT = cast<EmitIntegerMatcher>(N)->getVT();
786 unsigned OpBytes;
787 switch (VT) {
788 case MVT::i8:
789 case MVT::i16:
790 case MVT::i32:
791 case MVT::i64:
792 OpBytes = 1;
793 OS << "OPC_EmitInteger" << MVT(VT).getSizeInBits() << ", ";
794 break;
795 default:
796 OS << "OPC_EmitInteger, ";
797 if (!OmitComments)
798 OS << "/*" << getEnumName(VT) << "*/";
799 OpBytes = EmitVBRValue(VT, OS) + 1;
800 break;
802 unsigned Bytes = OpBytes + EmitSignedVBRValue(Val, OS);
803 if (!OmitComments)
804 OS << " // " << Val << " #" << cast<EmitIntegerMatcher>(N)->getResultNo();
805 OS << '\n';
806 return Bytes;
808 case Matcher::EmitStringInteger: {
809 const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
810 MVT::SimpleValueType VT = cast<EmitStringIntegerMatcher>(N)->getVT();
811 // These should always fit into 7 bits.
812 unsigned OpBytes;
813 switch (VT) {
814 case MVT::i32:
815 OpBytes = 1;
816 OS << "OPC_EmitStringInteger" << MVT(VT).getSizeInBits() << ", ";
817 break;
818 default:
819 OS << "OPC_EmitStringInteger, ";
820 if (!OmitComments)
821 OS << "/*" << getEnumName(VT) << "*/";
822 OpBytes = EmitVBRValue(VT, OS) + 1;
823 break;
825 OS << Val << ',';
826 if (!OmitComments)
827 OS << " // #" << cast<EmitStringIntegerMatcher>(N)->getResultNo();
828 OS << '\n';
829 return OpBytes + 1;
832 case Matcher::EmitRegister: {
833 const EmitRegisterMatcher *Matcher = cast<EmitRegisterMatcher>(N);
834 const CodeGenRegister *Reg = Matcher->getReg();
835 MVT::SimpleValueType VT = Matcher->getVT();
836 unsigned OpBytes;
837 // If the enum value of the register is larger than one byte can handle,
838 // use EmitRegister2.
839 if (Reg && Reg->EnumValue > 255) {
840 OS << "OPC_EmitRegister2, ";
841 if (!OmitComments)
842 OS << "/*" << getEnumName(VT) << "*/";
843 OpBytes = EmitVBRValue(VT, OS);
844 OS << "TARGET_VAL(" << getQualifiedName(Reg->TheDef) << "),\n";
845 return OpBytes + 3;
847 switch (VT) {
848 case MVT::i32:
849 case MVT::i64:
850 OpBytes = 1;
851 OS << "OPC_EmitRegisterI" << MVT(VT).getSizeInBits() << ", ";
852 break;
853 default:
854 OS << "OPC_EmitRegister, ";
855 if (!OmitComments)
856 OS << "/*" << getEnumName(VT) << "*/";
857 OpBytes = EmitVBRValue(VT, OS) + 1;
858 break;
860 if (Reg) {
861 OS << getQualifiedName(Reg->TheDef);
862 } else {
863 OS << "0 ";
864 if (!OmitComments)
865 OS << "/*zero_reg*/";
868 OS << ',';
869 if (!OmitComments)
870 OS << " // #" << Matcher->getResultNo();
871 OS << '\n';
872 return OpBytes + 1;
875 case Matcher::EmitConvertToTarget: {
876 const auto *CTTM = cast<EmitConvertToTargetMatcher>(N);
877 unsigned Slot = CTTM->getSlot();
878 OS << "OPC_EmitConvertToTarget";
879 if (Slot >= 8)
880 OS << ", ";
881 OS << Slot << ',';
882 if (!OmitComments)
883 OS << " // #" << CTTM->getResultNo();
884 OS << '\n';
885 return 1 + (Slot >= 8);
888 case Matcher::EmitMergeInputChains: {
889 const EmitMergeInputChainsMatcher *MN =
890 cast<EmitMergeInputChainsMatcher>(N);
892 // Handle the specialized forms OPC_EmitMergeInputChains1_0, 1_1, and 1_2.
893 if (MN->getNumNodes() == 1 && MN->getNode(0) < 3) {
894 OS << "OPC_EmitMergeInputChains1_" << MN->getNode(0) << ",\n";
895 return 1;
898 OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
899 for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
900 OS << MN->getNode(i) << ", ";
901 OS << '\n';
902 return 2 + MN->getNumNodes();
904 case Matcher::EmitCopyToReg: {
905 const auto *C2RMatcher = cast<EmitCopyToRegMatcher>(N);
906 int Bytes = 3;
907 const CodeGenRegister *Reg = C2RMatcher->getDestPhysReg();
908 unsigned Slot = C2RMatcher->getSrcSlot();
909 if (Reg->EnumValue > 255) {
910 assert(isUInt<16>(Reg->EnumValue) && "not handled");
911 OS << "OPC_EmitCopyToRegTwoByte, " << Slot << ", "
912 << "TARGET_VAL(" << getQualifiedName(Reg->TheDef) << "),\n";
913 ++Bytes;
914 } else {
915 if (Slot < 8) {
916 OS << "OPC_EmitCopyToReg" << Slot << ", "
917 << getQualifiedName(Reg->TheDef) << ",\n";
918 --Bytes;
919 } else
920 OS << "OPC_EmitCopyToReg, " << Slot << ", "
921 << getQualifiedName(Reg->TheDef) << ",\n";
924 return Bytes;
926 case Matcher::EmitNodeXForm: {
927 const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
928 OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
929 << XF->getSlot() << ',';
930 if (!OmitComments)
931 OS << " // " << XF->getNodeXForm()->getName() << " #"
932 << XF->getResultNo();
933 OS << '\n';
934 return 3;
937 case Matcher::EmitNode:
938 case Matcher::MorphNodeTo: {
939 auto NumCoveredBytes = 0;
940 if (InstrumentCoverage) {
941 if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
942 NumCoveredBytes = 3;
943 OS << "OPC_Coverage, ";
944 std::string src =
945 GetPatFromTreePatternNode(SNT->getPattern().getSrcPattern());
946 std::string dst =
947 GetPatFromTreePatternNode(SNT->getPattern().getDstPattern());
948 const Record *PatRecord = SNT->getPattern().getSrcRecord();
949 std::string include_src = getIncludePath(PatRecord);
950 unsigned Offset =
951 getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
952 OS << "COVERAGE_IDX_VAL(" << Offset << "),\n";
953 OS.indent(FullIndexWidth + Indent);
956 const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
957 bool IsEmitNode = isa<EmitNodeMatcher>(EN);
958 OS << (IsEmitNode ? "OPC_EmitNode" : "OPC_MorphNodeTo");
959 bool CompressVTs = EN->getNumVTs() < 3;
960 bool CompressNodeInfo = false;
961 if (CompressVTs) {
962 OS << EN->getNumVTs();
963 if (!EN->hasChain() && !EN->hasInGlue() && !EN->hasOutGlue() &&
964 !EN->hasMemRefs() && EN->getNumFixedArityOperands() == -1) {
965 CompressNodeInfo = true;
966 OS << "None";
967 } else if (EN->hasChain() && !EN->hasInGlue() && !EN->hasOutGlue() &&
968 !EN->hasMemRefs() && EN->getNumFixedArityOperands() == -1) {
969 CompressNodeInfo = true;
970 OS << "Chain";
971 } else if (!IsEmitNode && !EN->hasChain() && EN->hasInGlue() &&
972 !EN->hasOutGlue() && !EN->hasMemRefs() &&
973 EN->getNumFixedArityOperands() == -1) {
974 CompressNodeInfo = true;
975 OS << "GlueInput";
976 } else if (!IsEmitNode && !EN->hasChain() && !EN->hasInGlue() &&
977 EN->hasOutGlue() && !EN->hasMemRefs() &&
978 EN->getNumFixedArityOperands() == -1) {
979 CompressNodeInfo = true;
980 OS << "GlueOutput";
984 const CodeGenInstruction &CGI = EN->getInstruction();
985 OS << ", TARGET_VAL(" << CGI.Namespace << "::" << CGI.TheDef->getName()
986 << ")";
988 if (!CompressNodeInfo) {
989 OS << ", 0";
990 if (EN->hasChain())
991 OS << "|OPFL_Chain";
992 if (EN->hasInGlue())
993 OS << "|OPFL_GlueInput";
994 if (EN->hasOutGlue())
995 OS << "|OPFL_GlueOutput";
996 if (EN->hasMemRefs())
997 OS << "|OPFL_MemRefs";
998 if (EN->getNumFixedArityOperands() != -1)
999 OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
1001 OS << ",\n";
1003 OS.indent(FullIndexWidth + Indent + 4);
1004 if (!CompressVTs) {
1005 OS << EN->getNumVTs();
1006 if (!OmitComments)
1007 OS << "/*#VTs*/";
1008 OS << ", ";
1010 unsigned NumTypeBytes = 0;
1011 for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i) {
1012 if (!OmitComments)
1013 OS << "/*" << getEnumName(EN->getVT(i)) << "*/";
1014 NumTypeBytes += EmitVBRValue(EN->getVT(i), OS);
1017 OS << EN->getNumOperands();
1018 if (!OmitComments)
1019 OS << "/*#Ops*/";
1020 OS << ", ";
1021 unsigned NumOperandBytes = 0;
1022 for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
1023 NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
1025 if (!OmitComments) {
1026 // Print the result #'s for EmitNode.
1027 if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
1028 if (unsigned NumResults = EN->getNumVTs()) {
1029 OS << " // Results =";
1030 unsigned First = E->getFirstResultSlot();
1031 for (unsigned i = 0; i != NumResults; ++i)
1032 OS << " #" << First + i;
1035 OS << '\n';
1037 if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
1038 OS.indent(FullIndexWidth + Indent)
1039 << "// Src: " << SNT->getPattern().getSrcPattern()
1040 << " - Complexity = " << SNT->getPattern().getPatternComplexity(CGP)
1041 << '\n';
1042 OS.indent(FullIndexWidth + Indent)
1043 << "// Dst: " << SNT->getPattern().getDstPattern() << '\n';
1045 } else
1046 OS << '\n';
1048 return 4 + !CompressVTs + !CompressNodeInfo + NumTypeBytes +
1049 NumOperandBytes + NumCoveredBytes;
1051 case Matcher::CompleteMatch: {
1052 const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
1053 auto NumCoveredBytes = 0;
1054 if (InstrumentCoverage) {
1055 NumCoveredBytes = 3;
1056 OS << "OPC_Coverage, ";
1057 std::string src =
1058 GetPatFromTreePatternNode(CM->getPattern().getSrcPattern());
1059 std::string dst =
1060 GetPatFromTreePatternNode(CM->getPattern().getDstPattern());
1061 const Record *PatRecord = CM->getPattern().getSrcRecord();
1062 std::string include_src = getIncludePath(PatRecord);
1063 unsigned Offset =
1064 getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
1065 OS << "COVERAGE_IDX_VAL(" << Offset << "),\n";
1066 OS.indent(FullIndexWidth + Indent);
1068 OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
1069 unsigned NumResultBytes = 0;
1070 for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
1071 NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
1072 OS << '\n';
1073 if (!OmitComments) {
1074 OS.indent(FullIndexWidth + Indent)
1075 << " // Src: " << CM->getPattern().getSrcPattern()
1076 << " - Complexity = " << CM->getPattern().getPatternComplexity(CGP)
1077 << '\n';
1078 OS.indent(FullIndexWidth + Indent)
1079 << " // Dst: " << CM->getPattern().getDstPattern();
1081 OS << '\n';
1082 return 2 + NumResultBytes + NumCoveredBytes;
1085 llvm_unreachable("Unreachable");
1088 /// This function traverses the matcher tree and emits all the nodes.
1089 /// The nodes have already been sized.
1090 unsigned MatcherTableEmitter::EmitMatcherList(const Matcher *N,
1091 const unsigned Indent,
1092 unsigned CurrentIdx,
1093 raw_ostream &OS) {
1094 unsigned Size = 0;
1095 while (N) {
1096 if (!OmitComments)
1097 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
1098 unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
1099 Size += MatcherSize;
1100 CurrentIdx += MatcherSize;
1102 // If there are other nodes in this list, iterate to them, otherwise we're
1103 // done.
1104 N = N->getNext();
1106 return Size;
1109 void MatcherTableEmitter::EmitNodePredicatesFunction(
1110 const std::vector<TreePattern *> &Preds, StringRef Decl, raw_ostream &OS) {
1111 if (Preds.empty())
1112 return;
1114 BeginEmitFunction(OS, "bool", Decl, true /*AddOverride*/);
1115 OS << "{\n";
1116 OS << " switch (PredNo) {\n";
1117 OS << " default: llvm_unreachable(\"Invalid predicate in table?\");\n";
1118 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1119 // Emit the predicate code corresponding to this pattern.
1120 TreePredicateFn PredFn(Preds[i]);
1121 assert(!PredFn.isAlwaysTrue() && "No code in this predicate");
1122 std::string PredFnCodeStr = PredFn.getCodeToRunOnSDNode();
1124 OS << " case " << i << ": {\n";
1125 for (auto *SimilarPred : NodePredicatesByCodeToRun[PredFnCodeStr])
1126 OS << " // " << TreePredicateFn(SimilarPred).getFnName() << '\n';
1127 OS << PredFnCodeStr << "\n }\n";
1129 OS << " }\n";
1130 OS << "}\n";
1131 EndEmitFunction(OS);
1134 void MatcherTableEmitter::EmitPredicateFunctions(raw_ostream &OS) {
1135 // Emit pattern predicates.
1136 if (!PatternPredicates.empty()) {
1137 BeginEmitFunction(OS, "bool",
1138 "CheckPatternPredicate(unsigned PredNo) const",
1139 true /*AddOverride*/);
1140 OS << "{\n";
1141 OS << " switch (PredNo) {\n";
1142 OS << " default: llvm_unreachable(\"Invalid predicate in table?\");\n";
1143 for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
1144 OS << " case " << i << ": return " << PatternPredicates[i] << ";\n";
1145 OS << " }\n";
1146 OS << "}\n";
1147 EndEmitFunction(OS);
1150 // Emit Node predicates.
1151 EmitNodePredicatesFunction(
1152 NodePredicates, "CheckNodePredicate(SDNode *Node, unsigned PredNo) const",
1153 OS);
1154 EmitNodePredicatesFunction(
1155 NodePredicatesWithOperands,
1156 "CheckNodePredicateWithOperands(SDNode *Node, unsigned PredNo, "
1157 "const SmallVectorImpl<SDValue> &Operands) const",
1158 OS);
1160 // Emit CompletePattern matchers.
1161 // FIXME: This should be const.
1162 if (!ComplexPatterns.empty()) {
1163 BeginEmitFunction(
1164 OS, "bool",
1165 "CheckComplexPattern(SDNode *Root, SDNode *Parent,\n"
1166 " SDValue N, unsigned PatternNo,\n"
1167 " SmallVectorImpl<std::pair<SDValue, SDNode *>> &Result)",
1168 true /*AddOverride*/);
1169 OS << "{\n";
1170 OS << " unsigned NextRes = Result.size();\n";
1171 OS << " switch (PatternNo) {\n";
1172 OS << " default: llvm_unreachable(\"Invalid pattern # in table?\");\n";
1173 for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
1174 const ComplexPattern &P = *ComplexPatterns[i];
1175 unsigned NumOps = P.getNumOperands();
1177 if (P.hasProperty(SDNPHasChain))
1178 ++NumOps; // Get the chained node too.
1180 OS << " case " << i << ":\n";
1181 if (InstrumentCoverage)
1182 OS << " {\n";
1183 OS << " Result.resize(NextRes+" << NumOps << ");\n";
1184 if (InstrumentCoverage)
1185 OS << " bool Succeeded = " << P.getSelectFunc();
1186 else
1187 OS << " return " << P.getSelectFunc();
1189 OS << "(";
1190 // If the complex pattern wants the root of the match, pass it in as the
1191 // first argument.
1192 if (P.wantsRoot())
1193 OS << "Root, ";
1195 // If the complex pattern wants the parent of the operand being matched,
1196 // pass it in as the next argument.
1197 if (P.wantsParent())
1198 OS << "Parent, ";
1200 OS << "N";
1201 for (unsigned i = 0; i != NumOps; ++i)
1202 OS << ", Result[NextRes+" << i << "].first";
1203 OS << ");\n";
1204 if (InstrumentCoverage) {
1205 OS << " if (Succeeded)\n";
1206 OS << " dbgs() << \"\\nCOMPLEX_PATTERN: " << P.getSelectFunc()
1207 << "\\n\" ;\n";
1208 OS << " return Succeeded;\n";
1209 OS << " }\n";
1212 OS << " }\n";
1213 OS << "}\n";
1214 EndEmitFunction(OS);
1217 // Emit SDNodeXForm handlers.
1218 // FIXME: This should be const.
1219 if (!NodeXForms.empty()) {
1220 BeginEmitFunction(OS, "SDValue",
1221 "RunSDNodeXForm(SDValue V, unsigned XFormNo)",
1222 true /*AddOverride*/);
1223 OS << "{\n";
1224 OS << " switch (XFormNo) {\n";
1225 OS << " default: llvm_unreachable(\"Invalid xform # in table?\");\n";
1227 // FIXME: The node xform could take SDValue's instead of SDNode*'s.
1228 for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) {
1229 const CodeGenDAGPatterns::NodeXForm &Entry =
1230 CGP.getSDNodeTransform(NodeXForms[i]);
1232 const Record *SDNode = Entry.first;
1233 const std::string &Code = Entry.second;
1235 OS << " case " << i << ": { ";
1236 if (!OmitComments)
1237 OS << "// " << NodeXForms[i]->getName();
1238 OS << '\n';
1240 std::string ClassName =
1241 std::string(CGP.getSDNodeInfo(SDNode).getSDClassName());
1242 if (ClassName == "SDNode")
1243 OS << " SDNode *N = V.getNode();\n";
1244 else
1245 OS << " " << ClassName << " *N = cast<" << ClassName
1246 << ">(V.getNode());\n";
1247 OS << Code << "\n }\n";
1249 OS << " }\n";
1250 OS << "}\n";
1251 EndEmitFunction(OS);
1255 static StringRef getOpcodeString(Matcher::KindTy Kind) {
1256 switch (Kind) {
1257 case Matcher::Scope:
1258 return "OPC_Scope";
1259 case Matcher::RecordNode:
1260 return "OPC_RecordNode";
1261 case Matcher::RecordChild:
1262 return "OPC_RecordChild";
1263 case Matcher::RecordMemRef:
1264 return "OPC_RecordMemRef";
1265 case Matcher::CaptureGlueInput:
1266 return "OPC_CaptureGlueInput";
1267 case Matcher::MoveChild:
1268 return "OPC_MoveChild";
1269 case Matcher::MoveSibling:
1270 return "OPC_MoveSibling";
1271 case Matcher::MoveParent:
1272 return "OPC_MoveParent";
1273 case Matcher::CheckSame:
1274 return "OPC_CheckSame";
1275 case Matcher::CheckChildSame:
1276 return "OPC_CheckChildSame";
1277 case Matcher::CheckPatternPredicate:
1278 return "OPC_CheckPatternPredicate";
1279 case Matcher::CheckPredicate:
1280 return "OPC_CheckPredicate";
1281 case Matcher::CheckOpcode:
1282 return "OPC_CheckOpcode";
1283 case Matcher::SwitchOpcode:
1284 return "OPC_SwitchOpcode";
1285 case Matcher::CheckType:
1286 return "OPC_CheckType";
1287 case Matcher::SwitchType:
1288 return "OPC_SwitchType";
1289 case Matcher::CheckChildType:
1290 return "OPC_CheckChildType";
1291 case Matcher::CheckInteger:
1292 return "OPC_CheckInteger";
1293 case Matcher::CheckChildInteger:
1294 return "OPC_CheckChildInteger";
1295 case Matcher::CheckCondCode:
1296 return "OPC_CheckCondCode";
1297 case Matcher::CheckChild2CondCode:
1298 return "OPC_CheckChild2CondCode";
1299 case Matcher::CheckValueType:
1300 return "OPC_CheckValueType";
1301 case Matcher::CheckComplexPat:
1302 return "OPC_CheckComplexPat";
1303 case Matcher::CheckAndImm:
1304 return "OPC_CheckAndImm";
1305 case Matcher::CheckOrImm:
1306 return "OPC_CheckOrImm";
1307 case Matcher::CheckFoldableChainNode:
1308 return "OPC_CheckFoldableChainNode";
1309 case Matcher::CheckImmAllOnesV:
1310 return "OPC_CheckImmAllOnesV";
1311 case Matcher::CheckImmAllZerosV:
1312 return "OPC_CheckImmAllZerosV";
1313 case Matcher::EmitInteger:
1314 return "OPC_EmitInteger";
1315 case Matcher::EmitStringInteger:
1316 return "OPC_EmitStringInteger";
1317 case Matcher::EmitRegister:
1318 return "OPC_EmitRegister";
1319 case Matcher::EmitConvertToTarget:
1320 return "OPC_EmitConvertToTarget";
1321 case Matcher::EmitMergeInputChains:
1322 return "OPC_EmitMergeInputChains";
1323 case Matcher::EmitCopyToReg:
1324 return "OPC_EmitCopyToReg";
1325 case Matcher::EmitNode:
1326 return "OPC_EmitNode";
1327 case Matcher::MorphNodeTo:
1328 return "OPC_MorphNodeTo";
1329 case Matcher::EmitNodeXForm:
1330 return "OPC_EmitNodeXForm";
1331 case Matcher::CompleteMatch:
1332 return "OPC_CompleteMatch";
1335 llvm_unreachable("Unhandled opcode?");
1338 void MatcherTableEmitter::EmitHistogram(const Matcher *M, raw_ostream &OS) {
1339 if (OmitComments)
1340 return;
1342 OS << " // Opcode Histogram:\n";
1343 for (unsigned i = 0, e = OpcodeCounts.size(); i != e; ++i) {
1344 OS << " // #"
1345 << left_justify(getOpcodeString((Matcher::KindTy)i), HistOpcWidth)
1346 << " = " << OpcodeCounts[i] << '\n';
1348 OS << '\n';
1351 void llvm::EmitMatcherTable(Matcher *TheMatcher, const CodeGenDAGPatterns &CGP,
1352 raw_ostream &OS) {
1353 OS << "#if defined(GET_DAGISEL_DECL) && defined(GET_DAGISEL_BODY)\n";
1354 OS << "#error GET_DAGISEL_DECL and GET_DAGISEL_BODY cannot be both defined, ";
1355 OS << "undef both for inline definitions\n";
1356 OS << "#endif\n\n";
1358 // Emit a check for omitted class name.
1359 OS << "#ifdef GET_DAGISEL_BODY\n";
1360 OS << "#define LOCAL_DAGISEL_STRINGIZE(X) LOCAL_DAGISEL_STRINGIZE_(X)\n";
1361 OS << "#define LOCAL_DAGISEL_STRINGIZE_(X) #X\n";
1362 OS << "static_assert(sizeof(LOCAL_DAGISEL_STRINGIZE(GET_DAGISEL_BODY)) > 1,"
1363 "\n";
1364 OS << " \"GET_DAGISEL_BODY is empty: it should be defined with the class "
1365 "name\");\n";
1366 OS << "#undef LOCAL_DAGISEL_STRINGIZE_\n";
1367 OS << "#undef LOCAL_DAGISEL_STRINGIZE\n";
1368 OS << "#endif\n\n";
1370 OS << "#if !defined(GET_DAGISEL_DECL) && !defined(GET_DAGISEL_BODY)\n";
1371 OS << "#define DAGISEL_INLINE 1\n";
1372 OS << "#else\n";
1373 OS << "#define DAGISEL_INLINE 0\n";
1374 OS << "#endif\n\n";
1376 OS << "#if !DAGISEL_INLINE\n";
1377 OS << "#define DAGISEL_CLASS_COLONCOLON GET_DAGISEL_BODY ::\n";
1378 OS << "#else\n";
1379 OS << "#define DAGISEL_CLASS_COLONCOLON\n";
1380 OS << "#endif\n\n";
1382 BeginEmitFunction(OS, "void", "SelectCode(SDNode *N)", false /*AddOverride*/);
1383 MatcherTableEmitter MatcherEmitter(TheMatcher, CGP);
1385 // First we size all the children of the three kinds of matchers that have
1386 // them. This is done by sharing the code in EmitMatcher(). but we don't
1387 // want to emit anything, so we turn off comments and use a null stream.
1388 bool SaveOmitComments = OmitComments;
1389 OmitComments = true;
1390 raw_null_ostream NullOS;
1391 unsigned TotalSize = MatcherEmitter.SizeMatcherList(TheMatcher, NullOS);
1392 OmitComments = SaveOmitComments;
1394 // Now that the matchers are sized, we can emit the code for them to the
1395 // final stream.
1396 OS << "{\n";
1397 OS << " // Some target values are emitted as 2 bytes, TARGET_VAL handles\n";
1398 OS << " // this. Coverage indexes are emitted as 4 bytes,\n";
1399 OS << " // COVERAGE_IDX_VAL handles this.\n";
1400 OS << " #define TARGET_VAL(X) X & 255, unsigned(X) >> 8\n";
1401 OS << " #define COVERAGE_IDX_VAL(X) X & 255, (unsigned(X) >> 8) & 255, ";
1402 OS << "(unsigned(X) >> 16) & 255, (unsigned(X) >> 24) & 255\n";
1403 OS << " static const unsigned char MatcherTable[] = {\n";
1404 TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 1, 0, OS);
1405 OS << " 0\n }; // Total Array size is " << (TotalSize + 1)
1406 << " bytes\n\n";
1408 MatcherEmitter.EmitHistogram(TheMatcher, OS);
1410 OS << " #undef COVERAGE_IDX_VAL\n";
1411 OS << " #undef TARGET_VAL\n";
1412 OS << " SelectCodeCommon(N, MatcherTable, sizeof(MatcherTable));\n";
1413 OS << "}\n";
1414 EndEmitFunction(OS);
1416 // Next up, emit the function for node and pattern predicates:
1417 MatcherEmitter.EmitPredicateFunctions(OS);
1419 if (InstrumentCoverage)
1420 MatcherEmitter.EmitPatternMatchTable(OS);
1422 // Clean up the preprocessor macros.
1423 OS << "\n";
1424 OS << "#ifdef DAGISEL_INLINE\n";
1425 OS << "#undef DAGISEL_INLINE\n";
1426 OS << "#endif\n";
1427 OS << "#ifdef DAGISEL_CLASS_COLONCOLON\n";
1428 OS << "#undef DAGISEL_CLASS_COLONCOLON\n";
1429 OS << "#endif\n";
1430 OS << "#ifdef GET_DAGISEL_DECL\n";
1431 OS << "#undef GET_DAGISEL_DECL\n";
1432 OS << "#endif\n";
1433 OS << "#ifdef GET_DAGISEL_BODY\n";
1434 OS << "#undef GET_DAGISEL_BODY\n";
1435 OS << "#endif\n";