DAGISelMatcherEmitter.cpp 39 KB

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