[Frontend] Remove unused includes (NFC) (#116927)
[llvm-project.git] / llvm / utils / TableGen / DAGISelMatcherEmitter.cpp
blob74c399ee4231765745c9c19764883d1b3400a063
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 assert(isUInt<16>(VecPatterns.size()) &&
385 "Using only 16 bits to encode offset into Pattern Table");
386 assert(VecPatterns.size() == VecIncludeStrings.size() &&
387 "The sizes of Pattern and include vectors should be the same");
389 BeginEmitFunction(OS, "StringRef", "getPatternForIndex(unsigned Index)",
390 true /*AddOverride*/);
391 OS << "{\n";
392 OS << "static const char *PATTERN_MATCH_TABLE[] = {\n";
394 for (const auto &It : VecPatterns) {
395 OS << "\"" << It.first << "\",\n";
398 OS << "\n};";
399 OS << "\nreturn StringRef(PATTERN_MATCH_TABLE[Index]);";
400 OS << "\n}\n";
401 EndEmitFunction(OS);
403 BeginEmitFunction(OS, "StringRef", "getIncludePathForIndex(unsigned Index)",
404 true /*AddOverride*/);
405 OS << "{\n";
406 OS << "static const char *INCLUDE_PATH_TABLE[] = {\n";
408 for (const auto &It : VecIncludeStrings) {
409 OS << "\"" << It << "\",\n";
412 OS << "\n};";
413 OS << "\nreturn StringRef(INCLUDE_PATH_TABLE[Index]);";
414 OS << "\n}\n";
415 EndEmitFunction(OS);
418 /// EmitMatcher - Emit bytes for the specified matcher and return
419 /// the number of bytes emitted.
420 unsigned MatcherTableEmitter::EmitMatcher(const Matcher *N,
421 const unsigned Indent,
422 unsigned CurrentIdx,
423 raw_ostream &OS) {
424 OS.indent(Indent);
426 switch (N->getKind()) {
427 case Matcher::Scope: {
428 const ScopeMatcher *SM = cast<ScopeMatcher>(N);
429 unsigned StartIdx = CurrentIdx;
431 // Emit all of the children.
432 for (unsigned i = 0, e = SM->getNumChildren(); i != e; ++i) {
433 if (i == 0) {
434 OS << "OPC_Scope, ";
435 ++CurrentIdx;
436 } else {
437 if (!OmitComments) {
438 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
439 OS.indent(Indent) << "/*Scope*/ ";
440 } else
441 OS.indent(Indent);
444 unsigned ChildSize = SM->getChild(i)->getSize();
445 unsigned VBRSize = EmitVBRValue(ChildSize, OS);
446 if (!OmitComments) {
447 OS << "/*->" << CurrentIdx + VBRSize + ChildSize << "*/";
448 if (i == 0)
449 OS << " // " << SM->getNumChildren() << " children in Scope";
451 OS << '\n';
453 ChildSize = EmitMatcherList(SM->getChild(i), Indent + 1,
454 CurrentIdx + VBRSize, OS);
455 assert(ChildSize == SM->getChild(i)->getSize() &&
456 "Emitted child size does not match calculated size");
457 CurrentIdx += VBRSize + ChildSize;
460 // Emit a zero as a sentinel indicating end of 'Scope'.
461 if (!OmitComments)
462 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
463 OS.indent(Indent) << "0, ";
464 if (!OmitComments)
465 OS << "/*End of Scope*/";
466 OS << '\n';
467 return CurrentIdx - StartIdx + 1;
470 case Matcher::RecordNode:
471 OS << "OPC_RecordNode,";
472 if (!OmitComments)
473 OS << " // #" << cast<RecordMatcher>(N)->getResultNo() << " = "
474 << cast<RecordMatcher>(N)->getWhatFor();
475 OS << '\n';
476 return 1;
478 case Matcher::RecordChild:
479 OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo() << ',';
480 if (!OmitComments)
481 OS << " // #" << cast<RecordChildMatcher>(N)->getResultNo() << " = "
482 << cast<RecordChildMatcher>(N)->getWhatFor();
483 OS << '\n';
484 return 1;
486 case Matcher::RecordMemRef:
487 OS << "OPC_RecordMemRef,\n";
488 return 1;
490 case Matcher::CaptureGlueInput:
491 OS << "OPC_CaptureGlueInput,\n";
492 return 1;
494 case Matcher::MoveChild: {
495 const auto *MCM = cast<MoveChildMatcher>(N);
497 OS << "OPC_MoveChild";
498 // Handle the specialized forms.
499 if (MCM->getChildNo() >= 8)
500 OS << ", ";
501 OS << MCM->getChildNo() << ",\n";
502 return (MCM->getChildNo() >= 8) ? 2 : 1;
505 case Matcher::MoveSibling: {
506 const auto *MSM = cast<MoveSiblingMatcher>(N);
508 OS << "OPC_MoveSibling";
509 // Handle the specialized forms.
510 if (MSM->getSiblingNo() >= 8)
511 OS << ", ";
512 OS << MSM->getSiblingNo() << ",\n";
513 return (MSM->getSiblingNo() >= 8) ? 2 : 1;
516 case Matcher::MoveParent:
517 OS << "OPC_MoveParent,\n";
518 return 1;
520 case Matcher::CheckSame:
521 OS << "OPC_CheckSame, " << cast<CheckSameMatcher>(N)->getMatchNumber()
522 << ",\n";
523 return 2;
525 case Matcher::CheckChildSame:
526 OS << "OPC_CheckChild" << cast<CheckChildSameMatcher>(N)->getChildNo()
527 << "Same, " << cast<CheckChildSameMatcher>(N)->getMatchNumber() << ",\n";
528 return 2;
530 case Matcher::CheckPatternPredicate: {
531 StringRef Pred = cast<CheckPatternPredicateMatcher>(N)->getPredicate();
532 unsigned PredNo = getPatternPredicate(Pred);
533 if (PredNo > 255)
534 OS << "OPC_CheckPatternPredicateTwoByte, TARGET_VAL(" << PredNo << "),";
535 else if (PredNo < 8)
536 OS << "OPC_CheckPatternPredicate" << PredNo << ',';
537 else
538 OS << "OPC_CheckPatternPredicate, " << PredNo << ',';
539 if (!OmitComments)
540 OS << " // " << Pred;
541 OS << '\n';
542 return 2 + (PredNo > 255) - (PredNo < 8);
544 case Matcher::CheckPredicate: {
545 TreePredicateFn Pred = cast<CheckPredicateMatcher>(N)->getPredicate();
546 unsigned OperandBytes = 0;
547 unsigned PredNo = getNodePredicate(Pred);
549 if (Pred.usesOperands()) {
550 unsigned NumOps = cast<CheckPredicateMatcher>(N)->getNumOperands();
551 OS << "OPC_CheckPredicateWithOperands, " << NumOps << "/*#Ops*/, ";
552 for (unsigned i = 0; i < NumOps; ++i)
553 OS << cast<CheckPredicateMatcher>(N)->getOperandNo(i) << ", ";
554 OperandBytes = 1 + NumOps;
555 } else {
556 if (PredNo < 8) {
557 OperandBytes = -1;
558 OS << "OPC_CheckPredicate" << PredNo << ", ";
559 } else
560 OS << "OPC_CheckPredicate, ";
563 if (PredNo >= 8 || Pred.usesOperands())
564 OS << PredNo << ',';
565 if (!OmitComments)
566 OS << " // " << Pred.getFnName();
567 OS << '\n';
568 return 2 + OperandBytes;
571 case Matcher::CheckOpcode:
572 OS << "OPC_CheckOpcode, TARGET_VAL("
573 << cast<CheckOpcodeMatcher>(N)->getOpcode().getEnumName() << "),\n";
574 return 3;
576 case Matcher::SwitchOpcode:
577 case Matcher::SwitchType: {
578 unsigned StartIdx = CurrentIdx;
580 unsigned NumCases;
581 if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
582 OS << "OPC_SwitchOpcode ";
583 NumCases = SOM->getNumCases();
584 } else {
585 OS << "OPC_SwitchType ";
586 NumCases = cast<SwitchTypeMatcher>(N)->getNumCases();
589 if (!OmitComments)
590 OS << "/*" << NumCases << " cases */";
591 OS << ", ";
592 ++CurrentIdx;
594 // For each case we emit the size, then the opcode, then the matcher.
595 for (unsigned i = 0, e = NumCases; i != e; ++i) {
596 const Matcher *Child;
597 unsigned IdxSize;
598 if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N)) {
599 Child = SOM->getCaseMatcher(i);
600 IdxSize = 2; // size of opcode in table is 2 bytes.
601 } else {
602 Child = cast<SwitchTypeMatcher>(N)->getCaseMatcher(i);
603 IdxSize = GetVBRSize(cast<SwitchTypeMatcher>(N)->getCaseType(
604 i)); // size of type in table is sizeof(VBR(MVT)) byte.
607 if (i != 0) {
608 if (!OmitComments)
609 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
610 OS.indent(Indent);
611 if (!OmitComments)
612 OS << (isa<SwitchOpcodeMatcher>(N) ? "/*SwitchOpcode*/ "
613 : "/*SwitchType*/ ");
616 unsigned ChildSize = Child->getSize();
617 CurrentIdx += EmitVBRValue(ChildSize, OS) + IdxSize;
618 if (const SwitchOpcodeMatcher *SOM = dyn_cast<SwitchOpcodeMatcher>(N))
619 OS << "TARGET_VAL(" << SOM->getCaseOpcode(i).getEnumName() << "),";
620 else {
621 if (!OmitComments)
622 OS << "/*" << getEnumName(cast<SwitchTypeMatcher>(N)->getCaseType(i))
623 << "*/";
624 EmitVBRValue(cast<SwitchTypeMatcher>(N)->getCaseType(i),
625 OS);
627 if (!OmitComments)
628 OS << "// ->" << CurrentIdx + ChildSize;
629 OS << '\n';
631 ChildSize = EmitMatcherList(Child, Indent + 1, CurrentIdx, OS);
632 assert(ChildSize == Child->getSize() &&
633 "Emitted child size does not match calculated size");
634 CurrentIdx += ChildSize;
637 // Emit the final zero to terminate the switch.
638 if (!OmitComments)
639 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
640 OS.indent(Indent) << "0,";
641 if (!OmitComments)
642 OS << (isa<SwitchOpcodeMatcher>(N) ? " // EndSwitchOpcode"
643 : " // EndSwitchType");
645 OS << '\n';
646 return CurrentIdx - StartIdx + 1;
649 case Matcher::CheckType: {
650 if (cast<CheckTypeMatcher>(N)->getResNo() == 0) {
651 MVT::SimpleValueType VT = cast<CheckTypeMatcher>(N)->getType();
652 switch (VT) {
653 case MVT::i32:
654 case MVT::i64:
655 OS << "OPC_CheckTypeI" << MVT(VT).getSizeInBits() << ",\n";
656 return 1;
657 default:
658 OS << "OPC_CheckType, ";
659 if (!OmitComments)
660 OS << "/*" << getEnumName(VT) << "*/";
661 unsigned NumBytes = EmitVBRValue(VT, OS);
662 OS << "\n";
663 return NumBytes + 1;
666 OS << "OPC_CheckTypeRes, " << cast<CheckTypeMatcher>(N)->getResNo() << ", ";
667 if (!OmitComments)
668 OS << "/*" << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << "*/";
669 unsigned NumBytes = EmitVBRValue(cast<CheckTypeMatcher>(N)->getType(), OS);
670 OS << "\n";
671 return NumBytes + 2;
674 case Matcher::CheckChildType: {
675 MVT::SimpleValueType VT = cast<CheckChildTypeMatcher>(N)->getType();
676 switch (VT) {
677 case MVT::i32:
678 case MVT::i64:
679 OS << "OPC_CheckChild" << cast<CheckChildTypeMatcher>(N)->getChildNo()
680 << "TypeI" << MVT(VT).getSizeInBits() << ",\n";
681 return 1;
682 default:
683 OS << "OPC_CheckChild" << cast<CheckChildTypeMatcher>(N)->getChildNo()
684 << "Type, ";
685 if (!OmitComments)
686 OS << "/*" << getEnumName(VT) << "*/";
687 unsigned NumBytes = EmitVBRValue(VT, OS);
688 OS << "\n";
689 return NumBytes + 1;
693 case Matcher::CheckInteger: {
694 OS << "OPC_CheckInteger, ";
695 unsigned Bytes =
696 1 + EmitSignedVBRValue(cast<CheckIntegerMatcher>(N)->getValue(), OS);
697 OS << '\n';
698 return Bytes;
700 case Matcher::CheckChildInteger: {
701 OS << "OPC_CheckChild" << cast<CheckChildIntegerMatcher>(N)->getChildNo()
702 << "Integer, ";
703 unsigned Bytes = 1 + EmitSignedVBRValue(
704 cast<CheckChildIntegerMatcher>(N)->getValue(), OS);
705 OS << '\n';
706 return Bytes;
708 case Matcher::CheckCondCode:
709 OS << "OPC_CheckCondCode, ISD::"
710 << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
711 return 2;
713 case Matcher::CheckChild2CondCode:
714 OS << "OPC_CheckChild2CondCode, ISD::"
715 << cast<CheckChild2CondCodeMatcher>(N)->getCondCodeName() << ",\n";
716 return 2;
718 case Matcher::CheckValueType: {
719 OS << "OPC_CheckValueType, ";
720 if (!OmitComments)
721 OS << "/*" << getEnumName(cast<CheckValueTypeMatcher>(N)->getVT())
722 << "*/";
723 unsigned NumBytes =
724 EmitVBRValue(cast<CheckValueTypeMatcher>(N)->getVT(), OS);
725 OS << "\n";
726 return NumBytes + 1;
729 case Matcher::CheckComplexPat: {
730 const CheckComplexPatMatcher *CCPM = cast<CheckComplexPatMatcher>(N);
731 const ComplexPattern &Pattern = CCPM->getPattern();
732 unsigned PatternNo = getComplexPat(Pattern);
733 if (PatternNo < 8)
734 OS << "OPC_CheckComplexPat" << PatternNo << ", /*#*/"
735 << CCPM->getMatchNumber() << ',';
736 else
737 OS << "OPC_CheckComplexPat, /*CP*/" << PatternNo << ", /*#*/"
738 << CCPM->getMatchNumber() << ',';
740 if (!OmitComments) {
741 OS << " // " << Pattern.getSelectFunc();
742 OS << ":$" << CCPM->getName();
743 for (unsigned i = 0, e = Pattern.getNumOperands(); i != e; ++i)
744 OS << " #" << CCPM->getFirstResult() + i;
746 if (Pattern.hasProperty(SDNPHasChain))
747 OS << " + chain result";
749 OS << '\n';
750 return PatternNo < 8 ? 2 : 3;
753 case Matcher::CheckAndImm: {
754 OS << "OPC_CheckAndImm, ";
755 unsigned Bytes =
756 1 + EmitVBRValue(cast<CheckAndImmMatcher>(N)->getValue(), OS);
757 OS << '\n';
758 return Bytes;
761 case Matcher::CheckOrImm: {
762 OS << "OPC_CheckOrImm, ";
763 unsigned Bytes =
764 1 + EmitVBRValue(cast<CheckOrImmMatcher>(N)->getValue(), OS);
765 OS << '\n';
766 return Bytes;
769 case Matcher::CheckFoldableChainNode:
770 OS << "OPC_CheckFoldableChainNode,\n";
771 return 1;
773 case Matcher::CheckImmAllOnesV:
774 OS << "OPC_CheckImmAllOnesV,\n";
775 return 1;
777 case Matcher::CheckImmAllZerosV:
778 OS << "OPC_CheckImmAllZerosV,\n";
779 return 1;
781 case Matcher::EmitInteger: {
782 int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
783 MVT::SimpleValueType VT = cast<EmitIntegerMatcher>(N)->getVT();
784 unsigned OpBytes;
785 switch (VT) {
786 case MVT::i8:
787 case MVT::i16:
788 case MVT::i32:
789 case MVT::i64:
790 OpBytes = 1;
791 OS << "OPC_EmitInteger" << MVT(VT).getSizeInBits() << ", ";
792 break;
793 default:
794 OS << "OPC_EmitInteger, ";
795 if (!OmitComments)
796 OS << "/*" << getEnumName(VT) << "*/";
797 OpBytes = EmitVBRValue(VT, OS) + 1;
798 break;
800 unsigned Bytes = OpBytes + EmitSignedVBRValue(Val, OS);
801 if (!OmitComments)
802 OS << " // " << Val << " #" << cast<EmitIntegerMatcher>(N)->getResultNo();
803 OS << '\n';
804 return Bytes;
806 case Matcher::EmitStringInteger: {
807 const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
808 MVT::SimpleValueType VT = cast<EmitStringIntegerMatcher>(N)->getVT();
809 // These should always fit into 7 bits.
810 unsigned OpBytes;
811 switch (VT) {
812 case MVT::i32:
813 OpBytes = 1;
814 OS << "OPC_EmitStringInteger" << MVT(VT).getSizeInBits() << ", ";
815 break;
816 default:
817 OS << "OPC_EmitStringInteger, ";
818 if (!OmitComments)
819 OS << "/*" << getEnumName(VT) << "*/";
820 OpBytes = EmitVBRValue(VT, OS) + 1;
821 break;
823 OS << Val << ',';
824 if (!OmitComments)
825 OS << " // #" << cast<EmitStringIntegerMatcher>(N)->getResultNo();
826 OS << '\n';
827 return OpBytes + 1;
830 case Matcher::EmitRegister: {
831 const EmitRegisterMatcher *Matcher = cast<EmitRegisterMatcher>(N);
832 const CodeGenRegister *Reg = Matcher->getReg();
833 MVT::SimpleValueType VT = Matcher->getVT();
834 unsigned OpBytes;
835 // If the enum value of the register is larger than one byte can handle,
836 // use EmitRegister2.
837 if (Reg && Reg->EnumValue > 255) {
838 OS << "OPC_EmitRegister2, ";
839 if (!OmitComments)
840 OS << "/*" << getEnumName(VT) << "*/";
841 OpBytes = EmitVBRValue(VT, OS);
842 OS << "TARGET_VAL(" << getQualifiedName(Reg->TheDef) << "),\n";
843 return OpBytes + 3;
845 switch (VT) {
846 case MVT::i32:
847 case MVT::i64:
848 OpBytes = 1;
849 OS << "OPC_EmitRegisterI" << MVT(VT).getSizeInBits() << ", ";
850 break;
851 default:
852 OS << "OPC_EmitRegister, ";
853 if (!OmitComments)
854 OS << "/*" << getEnumName(VT) << "*/";
855 OpBytes = EmitVBRValue(VT, OS) + 1;
856 break;
858 if (Reg) {
859 OS << getQualifiedName(Reg->TheDef);
860 } else {
861 OS << "0 ";
862 if (!OmitComments)
863 OS << "/*zero_reg*/";
866 OS << ',';
867 if (!OmitComments)
868 OS << " // #" << Matcher->getResultNo();
869 OS << '\n';
870 return OpBytes + 1;
873 case Matcher::EmitConvertToTarget: {
874 const auto *CTTM = cast<EmitConvertToTargetMatcher>(N);
875 unsigned Slot = CTTM->getSlot();
876 OS << "OPC_EmitConvertToTarget";
877 if (Slot >= 8)
878 OS << ", ";
879 OS << Slot << ',';
880 if (!OmitComments)
881 OS << " // #" << CTTM->getResultNo();
882 OS << '\n';
883 return 1 + (Slot >= 8);
886 case Matcher::EmitMergeInputChains: {
887 const EmitMergeInputChainsMatcher *MN =
888 cast<EmitMergeInputChainsMatcher>(N);
890 // Handle the specialized forms OPC_EmitMergeInputChains1_0, 1_1, and 1_2.
891 if (MN->getNumNodes() == 1 && MN->getNode(0) < 3) {
892 OS << "OPC_EmitMergeInputChains1_" << MN->getNode(0) << ",\n";
893 return 1;
896 OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
897 for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
898 OS << MN->getNode(i) << ", ";
899 OS << '\n';
900 return 2 + MN->getNumNodes();
902 case Matcher::EmitCopyToReg: {
903 const auto *C2RMatcher = cast<EmitCopyToRegMatcher>(N);
904 int Bytes = 3;
905 const CodeGenRegister *Reg = C2RMatcher->getDestPhysReg();
906 unsigned Slot = C2RMatcher->getSrcSlot();
907 if (Reg->EnumValue > 255) {
908 assert(isUInt<16>(Reg->EnumValue) && "not handled");
909 OS << "OPC_EmitCopyToRegTwoByte, " << Slot << ", "
910 << "TARGET_VAL(" << getQualifiedName(Reg->TheDef) << "),\n";
911 ++Bytes;
912 } else {
913 if (Slot < 8) {
914 OS << "OPC_EmitCopyToReg" << Slot << ", "
915 << getQualifiedName(Reg->TheDef) << ",\n";
916 --Bytes;
917 } else
918 OS << "OPC_EmitCopyToReg, " << Slot << ", "
919 << getQualifiedName(Reg->TheDef) << ",\n";
922 return Bytes;
924 case Matcher::EmitNodeXForm: {
925 const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
926 OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
927 << XF->getSlot() << ',';
928 if (!OmitComments)
929 OS << " // " << XF->getNodeXForm()->getName() << " #"
930 << XF->getResultNo();
931 OS << '\n';
932 return 3;
935 case Matcher::EmitNode:
936 case Matcher::MorphNodeTo: {
937 auto NumCoveredBytes = 0;
938 if (InstrumentCoverage) {
939 if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
940 NumCoveredBytes = 3;
941 OS << "OPC_Coverage, ";
942 std::string src =
943 GetPatFromTreePatternNode(SNT->getPattern().getSrcPattern());
944 std::string dst =
945 GetPatFromTreePatternNode(SNT->getPattern().getDstPattern());
946 const Record *PatRecord = SNT->getPattern().getSrcRecord();
947 std::string include_src = getIncludePath(PatRecord);
948 unsigned Offset =
949 getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
950 OS << "TARGET_VAL(" << Offset << "),\n";
951 OS.indent(FullIndexWidth + Indent);
954 const EmitNodeMatcherCommon *EN = cast<EmitNodeMatcherCommon>(N);
955 bool IsEmitNode = isa<EmitNodeMatcher>(EN);
956 OS << (IsEmitNode ? "OPC_EmitNode" : "OPC_MorphNodeTo");
957 bool CompressVTs = EN->getNumVTs() < 3;
958 bool CompressNodeInfo = false;
959 if (CompressVTs) {
960 OS << EN->getNumVTs();
961 if (!EN->hasChain() && !EN->hasInGlue() && !EN->hasOutGlue() &&
962 !EN->hasMemRefs() && EN->getNumFixedArityOperands() == -1) {
963 CompressNodeInfo = true;
964 OS << "None";
965 } else if (EN->hasChain() && !EN->hasInGlue() && !EN->hasOutGlue() &&
966 !EN->hasMemRefs() && EN->getNumFixedArityOperands() == -1) {
967 CompressNodeInfo = true;
968 OS << "Chain";
969 } else if (!IsEmitNode && !EN->hasChain() && EN->hasInGlue() &&
970 !EN->hasOutGlue() && !EN->hasMemRefs() &&
971 EN->getNumFixedArityOperands() == -1) {
972 CompressNodeInfo = true;
973 OS << "GlueInput";
974 } else if (!IsEmitNode && !EN->hasChain() && !EN->hasInGlue() &&
975 EN->hasOutGlue() && !EN->hasMemRefs() &&
976 EN->getNumFixedArityOperands() == -1) {
977 CompressNodeInfo = true;
978 OS << "GlueOutput";
982 const CodeGenInstruction &CGI = EN->getInstruction();
983 OS << ", TARGET_VAL(" << CGI.Namespace << "::" << CGI.TheDef->getName()
984 << ")";
986 if (!CompressNodeInfo) {
987 OS << ", 0";
988 if (EN->hasChain())
989 OS << "|OPFL_Chain";
990 if (EN->hasInGlue())
991 OS << "|OPFL_GlueInput";
992 if (EN->hasOutGlue())
993 OS << "|OPFL_GlueOutput";
994 if (EN->hasMemRefs())
995 OS << "|OPFL_MemRefs";
996 if (EN->getNumFixedArityOperands() != -1)
997 OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
999 OS << ",\n";
1001 OS.indent(FullIndexWidth + Indent + 4);
1002 if (!CompressVTs) {
1003 OS << EN->getNumVTs();
1004 if (!OmitComments)
1005 OS << "/*#VTs*/";
1006 OS << ", ";
1008 unsigned NumTypeBytes = 0;
1009 for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i) {
1010 if (!OmitComments)
1011 OS << "/*" << getEnumName(EN->getVT(i)) << "*/";
1012 NumTypeBytes += EmitVBRValue(EN->getVT(i), OS);
1015 OS << EN->getNumOperands();
1016 if (!OmitComments)
1017 OS << "/*#Ops*/";
1018 OS << ", ";
1019 unsigned NumOperandBytes = 0;
1020 for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i)
1021 NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
1023 if (!OmitComments) {
1024 // Print the result #'s for EmitNode.
1025 if (const EmitNodeMatcher *E = dyn_cast<EmitNodeMatcher>(EN)) {
1026 if (unsigned NumResults = EN->getNumVTs()) {
1027 OS << " // Results =";
1028 unsigned First = E->getFirstResultSlot();
1029 for (unsigned i = 0; i != NumResults; ++i)
1030 OS << " #" << First + i;
1033 OS << '\n';
1035 if (const MorphNodeToMatcher *SNT = dyn_cast<MorphNodeToMatcher>(N)) {
1036 OS.indent(FullIndexWidth + Indent)
1037 << "// Src: " << SNT->getPattern().getSrcPattern()
1038 << " - Complexity = " << SNT->getPattern().getPatternComplexity(CGP)
1039 << '\n';
1040 OS.indent(FullIndexWidth + Indent)
1041 << "// Dst: " << SNT->getPattern().getDstPattern() << '\n';
1043 } else
1044 OS << '\n';
1046 return 4 + !CompressVTs + !CompressNodeInfo + NumTypeBytes +
1047 NumOperandBytes + NumCoveredBytes;
1049 case Matcher::CompleteMatch: {
1050 const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
1051 auto NumCoveredBytes = 0;
1052 if (InstrumentCoverage) {
1053 NumCoveredBytes = 3;
1054 OS << "OPC_Coverage, ";
1055 std::string src =
1056 GetPatFromTreePatternNode(CM->getPattern().getSrcPattern());
1057 std::string dst =
1058 GetPatFromTreePatternNode(CM->getPattern().getDstPattern());
1059 const Record *PatRecord = CM->getPattern().getSrcRecord();
1060 std::string include_src = getIncludePath(PatRecord);
1061 unsigned Offset =
1062 getPatternIdxFromTable(src + " -> " + dst, std::move(include_src));
1063 OS << "TARGET_VAL(" << Offset << "),\n";
1064 OS.indent(FullIndexWidth + Indent);
1066 OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
1067 unsigned NumResultBytes = 0;
1068 for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
1069 NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
1070 OS << '\n';
1071 if (!OmitComments) {
1072 OS.indent(FullIndexWidth + Indent)
1073 << " // Src: " << CM->getPattern().getSrcPattern()
1074 << " - Complexity = " << CM->getPattern().getPatternComplexity(CGP)
1075 << '\n';
1076 OS.indent(FullIndexWidth + Indent)
1077 << " // Dst: " << CM->getPattern().getDstPattern();
1079 OS << '\n';
1080 return 2 + NumResultBytes + NumCoveredBytes;
1083 llvm_unreachable("Unreachable");
1086 /// This function traverses the matcher tree and emits all the nodes.
1087 /// The nodes have already been sized.
1088 unsigned MatcherTableEmitter::EmitMatcherList(const Matcher *N,
1089 const unsigned Indent,
1090 unsigned CurrentIdx,
1091 raw_ostream &OS) {
1092 unsigned Size = 0;
1093 while (N) {
1094 if (!OmitComments)
1095 OS << "/*" << format_decimal(CurrentIdx, IndexWidth) << "*/";
1096 unsigned MatcherSize = EmitMatcher(N, Indent, CurrentIdx, OS);
1097 Size += MatcherSize;
1098 CurrentIdx += MatcherSize;
1100 // If there are other nodes in this list, iterate to them, otherwise we're
1101 // done.
1102 N = N->getNext();
1104 return Size;
1107 void MatcherTableEmitter::EmitNodePredicatesFunction(
1108 const std::vector<TreePattern *> &Preds, StringRef Decl, raw_ostream &OS) {
1109 if (Preds.empty())
1110 return;
1112 BeginEmitFunction(OS, "bool", Decl, true /*AddOverride*/);
1113 OS << "{\n";
1114 OS << " switch (PredNo) {\n";
1115 OS << " default: llvm_unreachable(\"Invalid predicate in table?\");\n";
1116 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1117 // Emit the predicate code corresponding to this pattern.
1118 TreePredicateFn PredFn(Preds[i]);
1119 assert(!PredFn.isAlwaysTrue() && "No code in this predicate");
1120 std::string PredFnCodeStr = PredFn.getCodeToRunOnSDNode();
1122 OS << " case " << i << ": {\n";
1123 for (auto *SimilarPred : NodePredicatesByCodeToRun[PredFnCodeStr])
1124 OS << " // " << TreePredicateFn(SimilarPred).getFnName() << '\n';
1125 OS << PredFnCodeStr << "\n }\n";
1127 OS << " }\n";
1128 OS << "}\n";
1129 EndEmitFunction(OS);
1132 void MatcherTableEmitter::EmitPredicateFunctions(raw_ostream &OS) {
1133 // Emit pattern predicates.
1134 if (!PatternPredicates.empty()) {
1135 BeginEmitFunction(OS, "bool",
1136 "CheckPatternPredicate(unsigned PredNo) const",
1137 true /*AddOverride*/);
1138 OS << "{\n";
1139 OS << " switch (PredNo) {\n";
1140 OS << " default: llvm_unreachable(\"Invalid predicate in table?\");\n";
1141 for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
1142 OS << " case " << i << ": return " << PatternPredicates[i] << ";\n";
1143 OS << " }\n";
1144 OS << "}\n";
1145 EndEmitFunction(OS);
1148 // Emit Node predicates.
1149 EmitNodePredicatesFunction(
1150 NodePredicates, "CheckNodePredicate(SDNode *Node, unsigned PredNo) const",
1151 OS);
1152 EmitNodePredicatesFunction(
1153 NodePredicatesWithOperands,
1154 "CheckNodePredicateWithOperands(SDNode *Node, unsigned PredNo, "
1155 "const SmallVectorImpl<SDValue> &Operands) const",
1156 OS);
1158 // Emit CompletePattern matchers.
1159 // FIXME: This should be const.
1160 if (!ComplexPatterns.empty()) {
1161 BeginEmitFunction(
1162 OS, "bool",
1163 "CheckComplexPattern(SDNode *Root, SDNode *Parent,\n"
1164 " SDValue N, unsigned PatternNo,\n"
1165 " SmallVectorImpl<std::pair<SDValue, SDNode *>> &Result)",
1166 true /*AddOverride*/);
1167 OS << "{\n";
1168 OS << " unsigned NextRes = Result.size();\n";
1169 OS << " switch (PatternNo) {\n";
1170 OS << " default: llvm_unreachable(\"Invalid pattern # in table?\");\n";
1171 for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
1172 const ComplexPattern &P = *ComplexPatterns[i];
1173 unsigned NumOps = P.getNumOperands();
1175 if (P.hasProperty(SDNPHasChain))
1176 ++NumOps; // Get the chained node too.
1178 OS << " case " << i << ":\n";
1179 if (InstrumentCoverage)
1180 OS << " {\n";
1181 OS << " Result.resize(NextRes+" << NumOps << ");\n";
1182 if (InstrumentCoverage)
1183 OS << " bool Succeeded = " << P.getSelectFunc();
1184 else
1185 OS << " return " << P.getSelectFunc();
1187 OS << "(";
1188 // If the complex pattern wants the root of the match, pass it in as the
1189 // first argument.
1190 if (P.hasProperty(SDNPWantRoot))
1191 OS << "Root, ";
1193 // If the complex pattern wants the parent of the operand being matched,
1194 // pass it in as the next argument.
1195 if (P.hasProperty(SDNPWantParent))
1196 OS << "Parent, ";
1198 OS << "N";
1199 for (unsigned i = 0; i != NumOps; ++i)
1200 OS << ", Result[NextRes+" << i << "].first";
1201 OS << ");\n";
1202 if (InstrumentCoverage) {
1203 OS << " if (Succeeded)\n";
1204 OS << " dbgs() << \"\\nCOMPLEX_PATTERN: " << P.getSelectFunc()
1205 << "\\n\" ;\n";
1206 OS << " return Succeeded;\n";
1207 OS << " }\n";
1210 OS << " }\n";
1211 OS << "}\n";
1212 EndEmitFunction(OS);
1215 // Emit SDNodeXForm handlers.
1216 // FIXME: This should be const.
1217 if (!NodeXForms.empty()) {
1218 BeginEmitFunction(OS, "SDValue",
1219 "RunSDNodeXForm(SDValue V, unsigned XFormNo)",
1220 true /*AddOverride*/);
1221 OS << "{\n";
1222 OS << " switch (XFormNo) {\n";
1223 OS << " default: llvm_unreachable(\"Invalid xform # in table?\");\n";
1225 // FIXME: The node xform could take SDValue's instead of SDNode*'s.
1226 for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i) {
1227 const CodeGenDAGPatterns::NodeXForm &Entry =
1228 CGP.getSDNodeTransform(NodeXForms[i]);
1230 const Record *SDNode = Entry.first;
1231 const std::string &Code = Entry.second;
1233 OS << " case " << i << ": { ";
1234 if (!OmitComments)
1235 OS << "// " << NodeXForms[i]->getName();
1236 OS << '\n';
1238 std::string ClassName =
1239 std::string(CGP.getSDNodeInfo(SDNode).getSDClassName());
1240 if (ClassName == "SDNode")
1241 OS << " SDNode *N = V.getNode();\n";
1242 else
1243 OS << " " << ClassName << " *N = cast<" << ClassName
1244 << ">(V.getNode());\n";
1245 OS << Code << "\n }\n";
1247 OS << " }\n";
1248 OS << "}\n";
1249 EndEmitFunction(OS);
1253 static StringRef getOpcodeString(Matcher::KindTy Kind) {
1254 switch (Kind) {
1255 case Matcher::Scope:
1256 return "OPC_Scope";
1257 case Matcher::RecordNode:
1258 return "OPC_RecordNode";
1259 case Matcher::RecordChild:
1260 return "OPC_RecordChild";
1261 case Matcher::RecordMemRef:
1262 return "OPC_RecordMemRef";
1263 case Matcher::CaptureGlueInput:
1264 return "OPC_CaptureGlueInput";
1265 case Matcher::MoveChild:
1266 return "OPC_MoveChild";
1267 case Matcher::MoveSibling:
1268 return "OPC_MoveSibling";
1269 case Matcher::MoveParent:
1270 return "OPC_MoveParent";
1271 case Matcher::CheckSame:
1272 return "OPC_CheckSame";
1273 case Matcher::CheckChildSame:
1274 return "OPC_CheckChildSame";
1275 case Matcher::CheckPatternPredicate:
1276 return "OPC_CheckPatternPredicate";
1277 case Matcher::CheckPredicate:
1278 return "OPC_CheckPredicate";
1279 case Matcher::CheckOpcode:
1280 return "OPC_CheckOpcode";
1281 case Matcher::SwitchOpcode:
1282 return "OPC_SwitchOpcode";
1283 case Matcher::CheckType:
1284 return "OPC_CheckType";
1285 case Matcher::SwitchType:
1286 return "OPC_SwitchType";
1287 case Matcher::CheckChildType:
1288 return "OPC_CheckChildType";
1289 case Matcher::CheckInteger:
1290 return "OPC_CheckInteger";
1291 case Matcher::CheckChildInteger:
1292 return "OPC_CheckChildInteger";
1293 case Matcher::CheckCondCode:
1294 return "OPC_CheckCondCode";
1295 case Matcher::CheckChild2CondCode:
1296 return "OPC_CheckChild2CondCode";
1297 case Matcher::CheckValueType:
1298 return "OPC_CheckValueType";
1299 case Matcher::CheckComplexPat:
1300 return "OPC_CheckComplexPat";
1301 case Matcher::CheckAndImm:
1302 return "OPC_CheckAndImm";
1303 case Matcher::CheckOrImm:
1304 return "OPC_CheckOrImm";
1305 case Matcher::CheckFoldableChainNode:
1306 return "OPC_CheckFoldableChainNode";
1307 case Matcher::CheckImmAllOnesV:
1308 return "OPC_CheckImmAllOnesV";
1309 case Matcher::CheckImmAllZerosV:
1310 return "OPC_CheckImmAllZerosV";
1311 case Matcher::EmitInteger:
1312 return "OPC_EmitInteger";
1313 case Matcher::EmitStringInteger:
1314 return "OPC_EmitStringInteger";
1315 case Matcher::EmitRegister:
1316 return "OPC_EmitRegister";
1317 case Matcher::EmitConvertToTarget:
1318 return "OPC_EmitConvertToTarget";
1319 case Matcher::EmitMergeInputChains:
1320 return "OPC_EmitMergeInputChains";
1321 case Matcher::EmitCopyToReg:
1322 return "OPC_EmitCopyToReg";
1323 case Matcher::EmitNode:
1324 return "OPC_EmitNode";
1325 case Matcher::MorphNodeTo:
1326 return "OPC_MorphNodeTo";
1327 case Matcher::EmitNodeXForm:
1328 return "OPC_EmitNodeXForm";
1329 case Matcher::CompleteMatch:
1330 return "OPC_CompleteMatch";
1333 llvm_unreachable("Unhandled opcode?");
1336 void MatcherTableEmitter::EmitHistogram(const Matcher *M, raw_ostream &OS) {
1337 if (OmitComments)
1338 return;
1340 OS << " // Opcode Histogram:\n";
1341 for (unsigned i = 0, e = OpcodeCounts.size(); i != e; ++i) {
1342 OS << " // #"
1343 << left_justify(getOpcodeString((Matcher::KindTy)i), HistOpcWidth)
1344 << " = " << OpcodeCounts[i] << '\n';
1346 OS << '\n';
1349 void llvm::EmitMatcherTable(Matcher *TheMatcher, const CodeGenDAGPatterns &CGP,
1350 raw_ostream &OS) {
1351 OS << "#if defined(GET_DAGISEL_DECL) && defined(GET_DAGISEL_BODY)\n";
1352 OS << "#error GET_DAGISEL_DECL and GET_DAGISEL_BODY cannot be both defined, ";
1353 OS << "undef both for inline definitions\n";
1354 OS << "#endif\n\n";
1356 // Emit a check for omitted class name.
1357 OS << "#ifdef GET_DAGISEL_BODY\n";
1358 OS << "#define LOCAL_DAGISEL_STRINGIZE(X) LOCAL_DAGISEL_STRINGIZE_(X)\n";
1359 OS << "#define LOCAL_DAGISEL_STRINGIZE_(X) #X\n";
1360 OS << "static_assert(sizeof(LOCAL_DAGISEL_STRINGIZE(GET_DAGISEL_BODY)) > 1,"
1361 "\n";
1362 OS << " \"GET_DAGISEL_BODY is empty: it should be defined with the class "
1363 "name\");\n";
1364 OS << "#undef LOCAL_DAGISEL_STRINGIZE_\n";
1365 OS << "#undef LOCAL_DAGISEL_STRINGIZE\n";
1366 OS << "#endif\n\n";
1368 OS << "#if !defined(GET_DAGISEL_DECL) && !defined(GET_DAGISEL_BODY)\n";
1369 OS << "#define DAGISEL_INLINE 1\n";
1370 OS << "#else\n";
1371 OS << "#define DAGISEL_INLINE 0\n";
1372 OS << "#endif\n\n";
1374 OS << "#if !DAGISEL_INLINE\n";
1375 OS << "#define DAGISEL_CLASS_COLONCOLON GET_DAGISEL_BODY ::\n";
1376 OS << "#else\n";
1377 OS << "#define DAGISEL_CLASS_COLONCOLON\n";
1378 OS << "#endif\n\n";
1380 BeginEmitFunction(OS, "void", "SelectCode(SDNode *N)", false /*AddOverride*/);
1381 MatcherTableEmitter MatcherEmitter(TheMatcher, CGP);
1383 // First we size all the children of the three kinds of matchers that have
1384 // them. This is done by sharing the code in EmitMatcher(). but we don't
1385 // want to emit anything, so we turn off comments and use a null stream.
1386 bool SaveOmitComments = OmitComments;
1387 OmitComments = true;
1388 raw_null_ostream NullOS;
1389 unsigned TotalSize = MatcherEmitter.SizeMatcherList(TheMatcher, NullOS);
1390 OmitComments = SaveOmitComments;
1392 // Now that the matchers are sized, we can emit the code for them to the
1393 // final stream.
1394 OS << "{\n";
1395 OS << " // Some target values are emitted as 2 bytes, TARGET_VAL handles\n";
1396 OS << " // this.\n";
1397 OS << " #define TARGET_VAL(X) X & 255, unsigned(X) >> 8\n";
1398 OS << " static const unsigned char MatcherTable[] = {\n";
1399 TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 1, 0, OS);
1400 OS << " 0\n }; // Total Array size is " << (TotalSize + 1)
1401 << " bytes\n\n";
1403 MatcherEmitter.EmitHistogram(TheMatcher, OS);
1405 OS << " #undef TARGET_VAL\n";
1406 OS << " SelectCodeCommon(N, MatcherTable, sizeof(MatcherTable));\n";
1407 OS << "}\n";
1408 EndEmitFunction(OS);
1410 // Next up, emit the function for node and pattern predicates:
1411 MatcherEmitter.EmitPredicateFunctions(OS);
1413 if (InstrumentCoverage)
1414 MatcherEmitter.EmitPatternMatchTable(OS);
1416 // Clean up the preprocessor macros.
1417 OS << "\n";
1418 OS << "#ifdef DAGISEL_INLINE\n";
1419 OS << "#undef DAGISEL_INLINE\n";
1420 OS << "#endif\n";
1421 OS << "#ifdef DAGISEL_CLASS_COLONCOLON\n";
1422 OS << "#undef DAGISEL_CLASS_COLONCOLON\n";
1423 OS << "#endif\n";
1424 OS << "#ifdef GET_DAGISEL_DECL\n";
1425 OS << "#undef GET_DAGISEL_DECL\n";
1426 OS << "#endif\n";
1427 OS << "#ifdef GET_DAGISEL_BODY\n";
1428 OS << "#undef GET_DAGISEL_BODY\n";
1429 OS << "#endif\n";