1 //===- DAGISelMatcherEmitter.cpp - Matcher Emitter ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains code to generate C++ code a matcher.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelMatcher.h"
15 #include "CodeGenDAGPatterns.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/Support/FormattedStream.h"
27 /// ClassifyInt - Classify an integer by size, return '1','2','4','8' if this
28 /// fits in 1, 2, 4, or 8 sign extended bytes.
29 static char ClassifyInt(int64_t Val) {
30 if (Val == int8_t(Val)) return '1';
31 if (Val == int16_t(Val)) return '2';
32 if (Val == int32_t(Val)) return '4';
36 /// EmitInt - Emit the specified integer, returning the number of bytes emitted.
37 static unsigned EmitInt(int64_t Val, formatted_raw_ostream &OS) {
38 unsigned BytesEmitted = 1;
39 OS << (int)(unsigned char)Val << ", ";
40 if (Val == int8_t(Val)) {
45 OS << (int)(unsigned char)(Val >> 8) << ", ";
48 if (Val != int16_t(Val)) {
49 OS << (int)(unsigned char)(Val >> 16) << ", "
50 << (int)(unsigned char)(Val >> 24) << ", ";
53 if (Val != int32_t(Val)) {
54 OS << (int)(unsigned char)(Val >> 32) << ", "
55 << (int)(unsigned char)(Val >> 40) << ", "
56 << (int)(unsigned char)(Val >> 48) << ", "
57 << (int)(unsigned char)(Val >> 56) << ", ";
62 OS.PadToColumn(CommentIndent) << "// " << Val << " aka 0x";
63 OS.write_hex(Val) << '\n';
68 class MatcherTableEmitter {
69 StringMap<unsigned> NodePredicateMap, PatternPredicateMap;
70 std::vector<std::string> NodePredicates, PatternPredicates;
72 DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
73 std::vector<const ComplexPattern*> ComplexPatterns;
76 DenseMap<Record*, unsigned> NodeXFormMap;
77 std::vector<const Record*> NodeXForms;
79 // Per opcode frequence count.
80 std::vector<unsigned> Histogram;
82 MatcherTableEmitter() {}
84 unsigned EmitMatcherList(const Matcher *N, unsigned Indent,
85 unsigned StartIdx, formatted_raw_ostream &OS);
87 void EmitPredicateFunctions(formatted_raw_ostream &OS);
89 void EmitHistogram(formatted_raw_ostream &OS);
91 unsigned EmitMatcher(const Matcher *N, unsigned Indent,
92 formatted_raw_ostream &OS);
94 unsigned getNodePredicate(StringRef PredName) {
95 unsigned &Entry = NodePredicateMap[PredName];
97 NodePredicates.push_back(PredName.str());
98 Entry = NodePredicates.size();
102 unsigned getPatternPredicate(StringRef PredName) {
103 unsigned &Entry = PatternPredicateMap[PredName];
105 PatternPredicates.push_back(PredName.str());
106 Entry = PatternPredicates.size();
111 unsigned getComplexPat(const ComplexPattern &P) {
112 unsigned &Entry = ComplexPatternMap[&P];
114 ComplexPatterns.push_back(&P);
115 Entry = ComplexPatterns.size();
120 unsigned getNodeXFormID(Record *Rec) {
121 unsigned &Entry = NodeXFormMap[Rec];
123 NodeXForms.push_back(Rec);
124 Entry = NodeXForms.size();
130 } // end anonymous namespace.
132 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
134 static unsigned EmitVBRValue(unsigned Val, raw_ostream &OS) {
140 unsigned InVal = Val;
141 unsigned NumBytes = 0;
143 OS << (Val&127) << "|128,";
147 OS << Val << "/*" << InVal << "*/, ";
151 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
152 /// the number of bytes emitted.
153 unsigned MatcherTableEmitter::
154 EmitMatcher(const Matcher *N, unsigned Indent, formatted_raw_ostream &OS) {
155 OS.PadToColumn(Indent*2);
157 switch (N->getKind()) {
158 case Matcher::Scope: assert(0 && "Should be handled by caller");
159 case Matcher::RecordNode:
160 OS << "OPC_RecordNode,";
161 OS.PadToColumn(CommentIndent) << "// "
162 << cast<RecordMatcher>(N)->getWhatFor() << '\n';
165 case Matcher::RecordChild:
166 OS << "OPC_RecordChild" << cast<RecordChildMatcher>(N)->getChildNo()
168 OS.PadToColumn(CommentIndent) << "// "
169 << cast<RecordChildMatcher>(N)->getWhatFor() << '\n';
172 case Matcher::RecordMemRef:
173 OS << "OPC_RecordMemRef,\n";
176 case Matcher::CaptureFlagInput:
177 OS << "OPC_CaptureFlagInput,\n";
180 case Matcher::MoveChild:
181 OS << "OPC_MoveChild, " << cast<MoveChildMatcher>(N)->getChildNo() << ",\n";
184 case Matcher::MoveParent:
185 OS << "OPC_MoveParent,\n";
188 case Matcher::CheckSame:
189 OS << "OPC_CheckSame, "
190 << cast<CheckSameMatcher>(N)->getMatchNumber() << ",\n";
193 case Matcher::CheckPatternPredicate: {
194 StringRef Pred = cast<CheckPatternPredicateMatcher>(N)->getPredicate();
195 OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
196 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
199 case Matcher::CheckPredicate: {
200 StringRef Pred = cast<CheckPredicateMatcher>(N)->getPredicateName();
201 OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
202 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
206 case Matcher::CheckOpcode:
207 OS << "OPC_CheckOpcode, "
208 << cast<CheckOpcodeMatcher>(N)->getOpcodeName() << ",\n";
211 case Matcher::CheckMultiOpcode: {
212 const CheckMultiOpcodeMatcher *CMO = cast<CheckMultiOpcodeMatcher>(N);
213 OS << "OPC_CheckMultiOpcode, " << CMO->getNumOpcodeNames() << ", ";
214 for (unsigned i = 0, e = CMO->getNumOpcodeNames(); i != e; ++i)
215 OS << CMO->getOpcodeName(i) << ", ";
217 return 2 + CMO->getNumOpcodeNames();
220 case Matcher::CheckType:
221 OS << "OPC_CheckType, "
222 << getEnumName(cast<CheckTypeMatcher>(N)->getType()) << ",\n";
224 case Matcher::CheckChildType:
225 OS << "OPC_CheckChild"
226 << cast<CheckChildTypeMatcher>(N)->getChildNo() << "Type, "
227 << getEnumName(cast<CheckChildTypeMatcher>(N)->getType()) << ",\n";
230 case Matcher::CheckInteger: {
231 int64_t Val = cast<CheckIntegerMatcher>(N)->getValue();
232 OS << "OPC_CheckInteger" << ClassifyInt(Val) << ", ";
233 return EmitInt(Val, OS)+1;
235 case Matcher::CheckCondCode:
236 OS << "OPC_CheckCondCode, ISD::"
237 << cast<CheckCondCodeMatcher>(N)->getCondCodeName() << ",\n";
240 case Matcher::CheckValueType:
241 OS << "OPC_CheckValueType, MVT::"
242 << cast<CheckValueTypeMatcher>(N)->getTypeName() << ",\n";
245 case Matcher::CheckComplexPat: {
246 const ComplexPattern &Pattern =
247 cast<CheckComplexPatMatcher>(N)->getPattern();
248 OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
249 OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
250 OS << ": " << Pattern.getNumOperands() << " operands";
251 if (Pattern.hasProperty(SDNPHasChain))
252 OS << " + chain result and input";
257 case Matcher::CheckAndImm: {
258 int64_t Val = cast<CheckAndImmMatcher>(N)->getValue();
259 OS << "OPC_CheckAndImm" << ClassifyInt(Val) << ", ";
260 return EmitInt(Val, OS)+1;
263 case Matcher::CheckOrImm: {
264 int64_t Val = cast<CheckOrImmMatcher>(N)->getValue();
265 OS << "OPC_CheckOrImm" << ClassifyInt(Val) << ", ";
266 return EmitInt(Val, OS)+1;
268 case Matcher::CheckFoldableChainNode:
269 OS << "OPC_CheckFoldableChainNode,\n";
271 case Matcher::CheckChainCompatible:
272 OS << "OPC_CheckChainCompatible, "
273 << cast<CheckChainCompatibleMatcher>(N)->getPreviousOp() << ",\n";
276 case Matcher::EmitInteger: {
277 int64_t Val = cast<EmitIntegerMatcher>(N)->getValue();
278 OS << "OPC_EmitInteger" << ClassifyInt(Val) << ", "
279 << getEnumName(cast<EmitIntegerMatcher>(N)->getVT()) << ", ";
280 return EmitInt(Val, OS)+2;
282 case Matcher::EmitStringInteger: {
283 const std::string &Val = cast<EmitStringIntegerMatcher>(N)->getValue();
284 // These should always fit into one byte.
285 OS << "OPC_EmitInteger1, "
286 << getEnumName(cast<EmitStringIntegerMatcher>(N)->getVT()) << ", "
291 case Matcher::EmitRegister:
292 OS << "OPC_EmitRegister, "
293 << getEnumName(cast<EmitRegisterMatcher>(N)->getVT()) << ", ";
294 if (Record *R = cast<EmitRegisterMatcher>(N)->getReg())
295 OS << getQualifiedName(R) << ",\n";
297 OS << "0 /*zero_reg*/,\n";
300 case Matcher::EmitConvertToTarget:
301 OS << "OPC_EmitConvertToTarget, "
302 << cast<EmitConvertToTargetMatcher>(N)->getSlot() << ",\n";
305 case Matcher::EmitMergeInputChains: {
306 const EmitMergeInputChainsMatcher *MN =
307 cast<EmitMergeInputChainsMatcher>(N);
308 OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
309 for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
310 OS << MN->getNode(i) << ", ";
312 return 2+MN->getNumNodes();
314 case Matcher::EmitCopyToReg:
315 OS << "OPC_EmitCopyToReg, "
316 << cast<EmitCopyToRegMatcher>(N)->getSrcSlot() << ", "
317 << getQualifiedName(cast<EmitCopyToRegMatcher>(N)->getDestPhysReg())
320 case Matcher::EmitNodeXForm: {
321 const EmitNodeXFormMatcher *XF = cast<EmitNodeXFormMatcher>(N);
322 OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
323 << XF->getSlot() << ',';
324 OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName()<<'\n';
328 case Matcher::EmitNode: {
329 const EmitNodeMatcher *EN = cast<EmitNodeMatcher>(N);
330 OS << "OPC_EmitNode, TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
332 if (EN->hasChain()) OS << "|OPFL_Chain";
333 if (EN->hasFlag()) OS << "|OPFL_Flag";
334 if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
335 if (EN->getNumFixedArityOperands() != -1)
336 OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
339 OS.PadToColumn(Indent*2+4) << EN->getNumVTs() << "/*#VTs*/, ";
340 for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
341 OS << getEnumName(EN->getVT(i)) << ", ";
343 OS << EN->getNumOperands() << "/*#Ops*/, ";
344 unsigned NumOperandBytes = 0;
345 for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i) {
346 // We emit the operand numbers in VBR encoded format, in case the number
347 // is too large to represent with a byte.
348 NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
351 return 6+EN->getNumVTs()+NumOperandBytes;
353 case Matcher::MarkFlagResults: {
354 const MarkFlagResultsMatcher *CFR = cast<MarkFlagResultsMatcher>(N);
355 OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
356 unsigned NumOperandBytes = 0;
357 for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
358 NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
360 return 2+NumOperandBytes;
362 case Matcher::CompleteMatch: {
363 const CompleteMatchMatcher *CM = cast<CompleteMatchMatcher>(N);
364 OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
365 unsigned NumResultBytes = 0;
366 for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
367 NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
369 OS.PadToColumn(Indent*2) << "// Src: "
370 << *CM->getPattern().getSrcPattern() << '\n';
371 OS.PadToColumn(Indent*2) << "// Dst: "
372 << *CM->getPattern().getDstPattern() << '\n';
373 return 2 + NumResultBytes;
376 assert(0 && "Unreachable");
380 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
381 unsigned MatcherTableEmitter::
382 EmitMatcherList(const Matcher *N, unsigned Indent, unsigned CurrentIdx,
383 formatted_raw_ostream &OS) {
386 if (unsigned(N->getKind()) >= Histogram.size())
387 Histogram.resize(N->getKind()+1);
388 Histogram[N->getKind()]++;
390 // Scope is a special case since it is binary.
391 if (const ScopeMatcher *SMN = dyn_cast<ScopeMatcher>(N)) {
392 // We need to encode the child and the offset of the failure code before
393 // emitting either of them. Handle this by buffering the output into a
394 // string while we get the size.
395 SmallString<128> TmpBuf;
398 raw_svector_ostream OS(TmpBuf);
399 formatted_raw_ostream FOS(OS);
400 NextSize = EmitMatcherList(cast<ScopeMatcher>(N)->getCheck(),
401 Indent+1, CurrentIdx+2, FOS);
404 // In the unlikely event that we have something too big to emit with a
405 // one byte offset, regenerate it with a two-byte one.
406 if (NextSize > 255) {
408 raw_svector_ostream OS(TmpBuf);
409 formatted_raw_ostream FOS(OS);
410 NextSize = EmitMatcherList(cast<ScopeMatcher>(N)->getCheck(),
411 Indent+1, CurrentIdx+3, FOS);
412 if (NextSize > 65535) {
414 "Tblgen internal error: can't handle pattern this complex yet\n";
419 OS << "/*" << CurrentIdx << "*/";
420 OS.PadToColumn(Indent*2);
423 OS << "OPC_Scope, " << NextSize << ",\n";
425 OS << "OPC_Scope2, " << (NextSize&255) << ", " << (NextSize>>8) <<",\n";
429 CurrentIdx += 2+NextSize;
434 OS << "/*" << CurrentIdx << "*/";
435 unsigned MatcherSize = EmitMatcher(N, Indent, OS);
437 CurrentIdx += MatcherSize;
439 // If there are other nodes in this list, iterate to them, otherwise we're
446 void MatcherTableEmitter::EmitPredicateFunctions(formatted_raw_ostream &OS) {
447 // FIXME: Don't build off the DAGISelEmitter's predicates, emit them directly
448 // here into the case stmts.
450 // Emit pattern predicates.
451 OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
452 OS << " switch (PredNo) {\n";
453 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
454 for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
455 OS << " case " << i << ": return " << PatternPredicates[i] << ";\n";
459 // Emit Node predicates.
460 OS << "bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {\n";
461 OS << " switch (PredNo) {\n";
462 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
463 for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i)
464 OS << " case " << i << ": return " << NodePredicates[i] << "(N);\n";
468 // Emit CompletePattern matchers.
469 // FIXME: This should be const.
470 OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
471 OS << " unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
472 OS << " switch (PatternNo) {\n";
473 OS << " default: assert(0 && \"Invalid pattern # in table?\");\n";
474 for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
475 const ComplexPattern &P = *ComplexPatterns[i];
476 unsigned NumOps = P.getNumOperands();
478 if (P.hasProperty(SDNPHasChain))
479 ++NumOps; // Get the chained node too.
481 OS << " case " << i << ":\n";
482 OS << " Result.resize(Result.size()+" << NumOps << ");\n";
483 OS << " return " << P.getSelectFunc();
485 // FIXME: Temporary hack until old isel dies.
486 if (P.hasProperty(SDNPHasChain))
490 for (unsigned i = 0; i != NumOps; ++i)
491 OS << ", Result[Result.size()-" << (NumOps-i) << ']';
497 // Emit SDNodeXForm handlers.
498 // FIXME: This should be const.
499 OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
500 OS << " switch (XFormNo) {\n";
501 OS << " default: assert(0 && \"Invalid xform # in table?\");\n";
503 // FIXME: The node xform could take SDValue's instead of SDNode*'s.
504 for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i)
505 OS << " case " << i << ": return Transform_" << NodeXForms[i]->getName()
506 << "(V.getNode());\n";
511 void MatcherTableEmitter::EmitHistogram(formatted_raw_ostream &OS) {
512 OS << " // Opcode Histogram:\n";
513 for (unsigned i = 0, e = Histogram.size(); i != e; ++i) {
515 switch ((Matcher::KindTy)i) {
516 case Matcher::Scope: OS << "OPC_Scope"; break;
517 case Matcher::RecordNode: OS << "OPC_RecordNode"; break;
518 case Matcher::RecordChild: OS << "OPC_RecordChild"; break;
519 case Matcher::RecordMemRef: OS << "OPC_RecordMemRef"; break;
520 case Matcher::CaptureFlagInput: OS << "OPC_CaptureFlagInput"; break;
521 case Matcher::MoveChild: OS << "OPC_MoveChild"; break;
522 case Matcher::MoveParent: OS << "OPC_MoveParent"; break;
523 case Matcher::CheckSame: OS << "OPC_CheckSame"; break;
524 case Matcher::CheckPatternPredicate:
525 OS << "OPC_CheckPatternPredicate"; break;
526 case Matcher::CheckPredicate: OS << "OPC_CheckPredicate"; break;
527 case Matcher::CheckOpcode: OS << "OPC_CheckOpcode"; break;
528 case Matcher::CheckMultiOpcode: OS << "OPC_CheckMultiOpcode"; break;
529 case Matcher::CheckType: OS << "OPC_CheckType"; break;
530 case Matcher::CheckChildType: OS << "OPC_CheckChildType"; break;
531 case Matcher::CheckInteger: OS << "OPC_CheckInteger"; break;
532 case Matcher::CheckCondCode: OS << "OPC_CheckCondCode"; break;
533 case Matcher::CheckValueType: OS << "OPC_CheckValueType"; break;
534 case Matcher::CheckComplexPat: OS << "OPC_CheckComplexPat"; break;
535 case Matcher::CheckAndImm: OS << "OPC_CheckAndImm"; break;
536 case Matcher::CheckOrImm: OS << "OPC_CheckOrImm"; break;
537 case Matcher::CheckFoldableChainNode:
538 OS << "OPC_CheckFoldableChainNode"; break;
539 case Matcher::CheckChainCompatible:
540 OS << "OPC_CheckChainCompatible"; break;
541 case Matcher::EmitInteger: OS << "OPC_EmitInteger"; break;
542 case Matcher::EmitStringInteger: OS << "OPC_EmitStringInteger"; break;
543 case Matcher::EmitRegister: OS << "OPC_EmitRegister"; break;
544 case Matcher::EmitConvertToTarget:
545 OS << "OPC_EmitConvertToTarget"; break;
546 case Matcher::EmitMergeInputChains:
547 OS << "OPC_EmitMergeInputChains"; break;
548 case Matcher::EmitCopyToReg: OS << "OPC_EmitCopyToReg"; break;
549 case Matcher::EmitNode: OS << "OPC_EmitNode"; break;
550 case Matcher::EmitNodeXForm: OS << "OPC_EmitNodeXForm"; break;
551 case Matcher::MarkFlagResults: OS << "OPC_MarkFlagResults"; break;
552 case Matcher::CompleteMatch: OS << "OPC_CompleteMatch"; break;
555 OS.PadToColumn(40) << " = " << Histogram[i] << '\n';
561 void llvm::EmitMatcherTable(const Matcher *TheMatcher, raw_ostream &O) {
562 formatted_raw_ostream OS(O);
564 OS << "// The main instruction selector code.\n";
565 OS << "SDNode *SelectCode(SDNode *N) {\n";
567 MatcherTableEmitter MatcherEmitter;
569 OS << " // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
570 OS << " #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
571 OS << " static const unsigned char MatcherTable[] = {\n";
572 unsigned TotalSize = MatcherEmitter.EmitMatcherList(TheMatcher, 5, 0, OS);
573 OS << " 0\n }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
575 MatcherEmitter.EmitHistogram(OS);
577 OS << " #undef TARGET_OPCODE\n";
578 OS << " return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
581 // Next up, emit the function for node and pattern predicates:
582 MatcherEmitter.EmitPredicateFunctions(OS);