DAGISelMatcherEmitter.cpp 39 KB

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