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"
29 /// ClassifyInt - Classify an integer by size, return '1','2','4','8' if this
30 /// fits in 1, 2, 4, or 8 sign extended bytes.
31 static char ClassifyInt(int64_t Val) {
32 if (Val == int8_t(Val)) return '1';
33 if (Val == int16_t(Val)) return '2';
34 if (Val == int32_t(Val)) return '4';
38 /// EmitInt - Emit the specified integer, returning the number of bytes emitted.
39 static unsigned EmitInt(int64_t Val, formatted_raw_ostream &OS) {
40 unsigned BytesEmitted = 1;
41 OS << (int)(unsigned char)Val << ", ";
42 if (Val == int8_t(Val)) {
47 OS << (int)(unsigned char)(Val >> 8) << ", ";
50 if (Val != int16_t(Val)) {
51 OS << (int)(unsigned char)(Val >> 16) << ", "
52 << (int)(unsigned char)(Val >> 24) << ", ";
55 if (Val != int32_t(Val)) {
56 OS << (int)(unsigned char)(Val >> 32) << ", "
57 << (int)(unsigned char)(Val >> 40) << ", "
58 << (int)(unsigned char)(Val >> 48) << ", "
59 << (int)(unsigned char)(Val >> 56) << ", ";
64 OS.PadToColumn(CommentIndent) << "// " << Val << " aka 0x";
65 OS.write_hex(Val) << '\n';
70 class MatcherTableEmitter {
71 StringMap<unsigned> NodePredicateMap, PatternPredicateMap;
72 std::vector<std::string> NodePredicates, PatternPredicates;
74 DenseMap<const ComplexPattern*, unsigned> ComplexPatternMap;
75 std::vector<const ComplexPattern*> ComplexPatterns;
78 DenseMap<Record*, unsigned> NodeXFormMap;
79 std::vector<const Record*> NodeXForms;
82 MatcherTableEmitter() {}
84 unsigned EmitMatcherList(const MatcherNode *N, unsigned Indent,
85 unsigned StartIdx, formatted_raw_ostream &OS);
87 void EmitPredicateFunctions(formatted_raw_ostream &OS);
89 unsigned EmitMatcher(const MatcherNode *N, unsigned Indent,
90 formatted_raw_ostream &OS);
92 unsigned getNodePredicate(StringRef PredName) {
93 unsigned &Entry = NodePredicateMap[PredName];
95 NodePredicates.push_back(PredName.str());
96 Entry = NodePredicates.size();
100 unsigned getPatternPredicate(StringRef PredName) {
101 unsigned &Entry = PatternPredicateMap[PredName];
103 PatternPredicates.push_back(PredName.str());
104 Entry = PatternPredicates.size();
109 unsigned getComplexPat(const ComplexPattern &P) {
110 unsigned &Entry = ComplexPatternMap[&P];
112 ComplexPatterns.push_back(&P);
113 Entry = ComplexPatterns.size();
118 unsigned getNodeXFormID(Record *Rec) {
119 unsigned &Entry = NodeXFormMap[Rec];
121 NodeXForms.push_back(Rec);
122 Entry = NodeXForms.size();
128 } // end anonymous namespace.
130 /// EmitVBRValue - Emit the specified value as a VBR, returning the number of
132 static unsigned EmitVBRValue(unsigned Val, raw_ostream &OS) {
138 unsigned InVal = Val;
139 unsigned NumBytes = 0;
141 OS << (Val&127) << "|128,";
145 OS << Val << "/*" << InVal << "*/, ";
149 /// EmitMatcherOpcodes - Emit bytes for the specified matcher and return
150 /// the number of bytes emitted.
151 unsigned MatcherTableEmitter::
152 EmitMatcher(const MatcherNode *N, unsigned Indent, formatted_raw_ostream &OS) {
153 OS.PadToColumn(Indent*2);
155 switch (N->getKind()) {
156 case MatcherNode::Push: assert(0 && "Should be handled by caller");
157 case MatcherNode::RecordNode:
158 OS << "OPC_RecordNode,";
159 OS.PadToColumn(CommentIndent) << "// "
160 << cast<RecordMatcherNode>(N)->getWhatFor() << '\n';
163 case MatcherNode::RecordChild:
164 OS << "OPC_RecordChild" << cast<RecordChildMatcherNode>(N)->getChildNo()
166 OS.PadToColumn(CommentIndent) << "// "
167 << cast<RecordChildMatcherNode>(N)->getWhatFor() << '\n';
170 case MatcherNode::RecordMemRef:
171 OS << "OPC_RecordMemRef,\n";
174 case MatcherNode::CaptureFlagInput:
175 OS << "OPC_CaptureFlagInput,\n";
178 case MatcherNode::MoveChild:
179 OS << "OPC_MoveChild, "
180 << cast<MoveChildMatcherNode>(N)->getChildNo() << ",\n";
183 case MatcherNode::MoveParent:
184 OS << "OPC_MoveParent,\n";
187 case MatcherNode::CheckSame:
188 OS << "OPC_CheckSame, "
189 << cast<CheckSameMatcherNode>(N)->getMatchNumber() << ",\n";
192 case MatcherNode::CheckPatternPredicate: {
193 StringRef Pred = cast<CheckPatternPredicateMatcherNode>(N)->getPredicate();
194 OS << "OPC_CheckPatternPredicate, " << getPatternPredicate(Pred) << ',';
195 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
198 case MatcherNode::CheckPredicate: {
199 StringRef Pred = cast<CheckPredicateMatcherNode>(N)->getPredicateName();
200 OS << "OPC_CheckPredicate, " << getNodePredicate(Pred) << ',';
201 OS.PadToColumn(CommentIndent) << "// " << Pred << '\n';
205 case MatcherNode::CheckOpcode:
206 OS << "OPC_CheckOpcode, "
207 << cast<CheckOpcodeMatcherNode>(N)->getOpcodeName() << ",\n";
210 case MatcherNode::CheckMultiOpcode: {
211 const CheckMultiOpcodeMatcherNode *CMO=cast<CheckMultiOpcodeMatcherNode>(N);
212 OS << "OPC_CheckMultiOpcode, " << CMO->getNumOpcodeNames() << ", ";
213 for (unsigned i = 0, e = CMO->getNumOpcodeNames(); i != e; ++i)
214 OS << CMO->getOpcodeName(i) << ", ";
216 return 2 + CMO->getNumOpcodeNames();
219 case MatcherNode::CheckType:
220 OS << "OPC_CheckType, "
221 << getEnumName(cast<CheckTypeMatcherNode>(N)->getType()) << ",\n";
224 case MatcherNode::CheckInteger: {
225 int64_t Val = cast<CheckIntegerMatcherNode>(N)->getValue();
226 OS << "OPC_CheckInteger" << ClassifyInt(Val) << ", ";
227 return EmitInt(Val, OS)+1;
229 case MatcherNode::CheckCondCode:
230 OS << "OPC_CheckCondCode, ISD::"
231 << cast<CheckCondCodeMatcherNode>(N)->getCondCodeName() << ",\n";
234 case MatcherNode::CheckValueType:
235 OS << "OPC_CheckValueType, MVT::"
236 << cast<CheckValueTypeMatcherNode>(N)->getTypeName() << ",\n";
239 case MatcherNode::CheckComplexPat: {
240 const ComplexPattern &Pattern =
241 cast<CheckComplexPatMatcherNode>(N)->getPattern();
242 OS << "OPC_CheckComplexPat, " << getComplexPat(Pattern) << ',';
243 OS.PadToColumn(CommentIndent) << "// " << Pattern.getSelectFunc();
244 OS << ": " << Pattern.getNumOperands() << " operands";
245 if (Pattern.hasProperty(SDNPHasChain))
246 OS << " + chain result and input";
251 case MatcherNode::CheckAndImm: {
252 int64_t Val = cast<CheckAndImmMatcherNode>(N)->getValue();
253 OS << "OPC_CheckAndImm" << ClassifyInt(Val) << ", ";
254 return EmitInt(Val, OS)+1;
257 case MatcherNode::CheckOrImm: {
258 int64_t Val = cast<CheckOrImmMatcherNode>(N)->getValue();
259 OS << "OPC_CheckOrImm" << ClassifyInt(Val) << ", ";
260 return EmitInt(Val, OS)+1;
262 case MatcherNode::CheckFoldableChainNode:
263 OS << "OPC_CheckFoldableChainNode,\n";
265 case MatcherNode::CheckChainCompatible:
266 OS << "OPC_CheckChainCompatible, "
267 << cast<CheckChainCompatibleMatcherNode>(N)->getPreviousOp() << ",\n";
270 case MatcherNode::EmitInteger: {
271 int64_t Val = cast<EmitIntegerMatcherNode>(N)->getValue();
272 OS << "OPC_EmitInteger" << ClassifyInt(Val) << ", "
273 << getEnumName(cast<EmitIntegerMatcherNode>(N)->getVT()) << ", ";
274 return EmitInt(Val, OS)+2;
276 case MatcherNode::EmitStringInteger: {
277 const std::string &Val = cast<EmitStringIntegerMatcherNode>(N)->getValue();
278 // These should always fit into one byte.
279 OS << "OPC_EmitInteger1, "
280 << getEnumName(cast<EmitStringIntegerMatcherNode>(N)->getVT()) << ", "
285 case MatcherNode::EmitRegister:
286 OS << "OPC_EmitRegister, "
287 << getEnumName(cast<EmitRegisterMatcherNode>(N)->getVT()) << ", ";
288 if (Record *R = cast<EmitRegisterMatcherNode>(N)->getReg())
289 OS << getQualifiedName(R) << ",\n";
291 OS << "0 /*zero_reg*/,\n";
294 case MatcherNode::EmitConvertToTarget:
295 OS << "OPC_EmitConvertToTarget, "
296 << cast<EmitConvertToTargetMatcherNode>(N)->getSlot() << ",\n";
299 case MatcherNode::EmitMergeInputChains: {
300 const EmitMergeInputChainsMatcherNode *MN =
301 cast<EmitMergeInputChainsMatcherNode>(N);
302 OS << "OPC_EmitMergeInputChains, " << MN->getNumNodes() << ", ";
303 for (unsigned i = 0, e = MN->getNumNodes(); i != e; ++i)
304 OS << MN->getNode(i) << ", ";
306 return 2+MN->getNumNodes();
308 case MatcherNode::EmitCopyToReg:
309 OS << "OPC_EmitCopyToReg, "
310 << cast<EmitCopyToRegMatcherNode>(N)->getSrcSlot() << ", "
311 << getQualifiedName(cast<EmitCopyToRegMatcherNode>(N)->getDestPhysReg())
314 case MatcherNode::EmitNodeXForm: {
315 const EmitNodeXFormMatcherNode *XF = cast<EmitNodeXFormMatcherNode>(N);
316 OS << "OPC_EmitNodeXForm, " << getNodeXFormID(XF->getNodeXForm()) << ", "
317 << XF->getSlot() << ',';
318 OS.PadToColumn(CommentIndent) << "// "<<XF->getNodeXForm()->getName()<<'\n';
322 case MatcherNode::EmitNode: {
323 const EmitNodeMatcherNode *EN = cast<EmitNodeMatcherNode>(N);
324 OS << "OPC_EmitNode, TARGET_OPCODE(" << EN->getOpcodeName() << "), 0";
326 if (EN->hasChain()) OS << "|OPFL_Chain";
327 if (EN->hasFlag()) OS << "|OPFL_Flag";
328 if (EN->hasMemRefs()) OS << "|OPFL_MemRefs";
329 if (EN->getNumFixedArityOperands() != -1)
330 OS << "|OPFL_Variadic" << EN->getNumFixedArityOperands();
333 OS.PadToColumn(Indent*2+4) << EN->getNumVTs() << "/*#VTs*/, ";
334 for (unsigned i = 0, e = EN->getNumVTs(); i != e; ++i)
335 OS << getEnumName(EN->getVT(i)) << ", ";
337 OS << EN->getNumOperands() << "/*#Ops*/, ";
338 unsigned NumOperandBytes = 0;
339 for (unsigned i = 0, e = EN->getNumOperands(); i != e; ++i) {
340 // We emit the operand numbers in VBR encoded format, in case the number
341 // is too large to represent with a byte.
342 NumOperandBytes += EmitVBRValue(EN->getOperand(i), OS);
345 return 6+EN->getNumVTs()+NumOperandBytes;
347 case MatcherNode::MarkFlagResults: {
348 const MarkFlagResultsMatcherNode *CFR = cast<MarkFlagResultsMatcherNode>(N);
349 OS << "OPC_MarkFlagResults, " << CFR->getNumNodes() << ", ";
350 unsigned NumOperandBytes = 0;
351 for (unsigned i = 0, e = CFR->getNumNodes(); i != e; ++i)
352 NumOperandBytes += EmitVBRValue(CFR->getNode(i), OS);
354 return 2+NumOperandBytes;
356 case MatcherNode::CompleteMatch: {
357 const CompleteMatchMatcherNode *CM = cast<CompleteMatchMatcherNode>(N);
358 OS << "OPC_CompleteMatch, " << CM->getNumResults() << ", ";
359 unsigned NumResultBytes = 0;
360 for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
361 NumResultBytes += EmitVBRValue(CM->getResult(i), OS);
363 OS.PadToColumn(Indent*2) << "// Src: "
364 << *CM->getPattern().getSrcPattern() << '\n';
365 OS.PadToColumn(Indent*2) << "// Dst: "
366 << *CM->getPattern().getDstPattern() << '\n';
367 return 2 + NumResultBytes;
370 assert(0 && "Unreachable");
374 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
375 unsigned MatcherTableEmitter::
376 EmitMatcherList(const MatcherNode *N, unsigned Indent, unsigned CurrentIdx,
377 formatted_raw_ostream &OS) {
380 // Push is a special case since it is binary.
381 if (const PushMatcherNode *PMN = dyn_cast<PushMatcherNode>(N)) {
382 // We need to encode the child and the offset of the failure code before
383 // emitting either of them. Handle this by buffering the output into a
384 // string while we get the size.
385 SmallString<128> TmpBuf;
388 raw_svector_ostream OS(TmpBuf);
389 formatted_raw_ostream FOS(OS);
390 NextSize = EmitMatcherList(cast<PushMatcherNode>(N)->getNext(),
391 Indent+1, CurrentIdx+2, FOS);
394 // In the unlikely event that we have something too big to emit with a
395 // one byte offset, regenerate it with a two-byte one.
396 if (NextSize > 255) {
398 raw_svector_ostream OS(TmpBuf);
399 formatted_raw_ostream FOS(OS);
400 NextSize = EmitMatcherList(cast<PushMatcherNode>(N)->getNext(),
401 Indent+1, CurrentIdx+3, FOS);
402 if (NextSize > 65535) {
404 "Tblgen internal error: can't handle pattern this complex yet\n";
409 OS << "/*" << CurrentIdx << "*/";
410 OS.PadToColumn(Indent*2);
413 OS << "OPC_Push, " << NextSize << ",\n";
415 OS << "OPC_Push2, " << (NextSize&255) << ", " << (NextSize>>8) << ",\n";
419 CurrentIdx += 2+NextSize;
420 N = PMN->getFailure();
424 OS << "/*" << CurrentIdx << "*/";
425 unsigned MatcherSize = EmitMatcher(N, Indent, OS);
427 CurrentIdx += MatcherSize;
429 // If there are other nodes in this list, iterate to them, otherwise we're
436 void MatcherTableEmitter::EmitPredicateFunctions(formatted_raw_ostream &OS) {
437 // FIXME: Don't build off the DAGISelEmitter's predicates, emit them directly
438 // here into the case stmts.
440 // Emit pattern predicates.
441 OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
442 OS << " switch (PredNo) {\n";
443 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
444 for (unsigned i = 0, e = PatternPredicates.size(); i != e; ++i)
445 OS << " case " << i << ": return " << PatternPredicates[i] << ";\n";
449 // Emit Node predicates.
450 OS << "bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {\n";
451 OS << " switch (PredNo) {\n";
452 OS << " default: assert(0 && \"Invalid predicate in table?\");\n";
453 for (unsigned i = 0, e = NodePredicates.size(); i != e; ++i)
454 OS << " case " << i << ": return " << NodePredicates[i] << "(N);\n";
458 // Emit CompletePattern matchers.
459 // FIXME: This should be const.
460 OS << "bool CheckComplexPattern(SDNode *Root, SDValue N,\n";
461 OS << " unsigned PatternNo, SmallVectorImpl<SDValue> &Result) {\n";
462 OS << " switch (PatternNo) {\n";
463 OS << " default: assert(0 && \"Invalid pattern # in table?\");\n";
464 for (unsigned i = 0, e = ComplexPatterns.size(); i != e; ++i) {
465 const ComplexPattern &P = *ComplexPatterns[i];
466 unsigned NumOps = P.getNumOperands();
468 if (P.hasProperty(SDNPHasChain))
469 ++NumOps; // Get the chained node too.
471 OS << " case " << i << ":\n";
472 OS << " Result.resize(Result.size()+" << NumOps << ");\n";
473 OS << " return " << P.getSelectFunc();
475 // FIXME: Temporary hack until old isel dies.
476 if (P.hasProperty(SDNPHasChain))
480 for (unsigned i = 0; i != NumOps; ++i)
481 OS << ", Result[Result.size()-" << (NumOps-i) << ']';
487 // Emit SDNodeXForm handlers.
488 // FIXME: This should be const.
489 OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
490 OS << " switch (XFormNo) {\n";
491 OS << " default: assert(0 && \"Invalid xform # in table?\");\n";
493 // FIXME: The node xform could take SDValue's instead of SDNode*'s.
494 for (unsigned i = 0, e = NodeXForms.size(); i != e; ++i)
495 OS << " case " << i << ": return Transform_" << NodeXForms[i]->getName()
496 << "(V.getNode());\n";
502 void llvm::EmitMatcherTable(const MatcherNode *Matcher, raw_ostream &O) {
503 formatted_raw_ostream OS(O);
505 OS << "// The main instruction selector code.\n";
506 OS << "SDNode *SelectCode2(SDNode *N) {\n";
508 MatcherTableEmitter MatcherEmitter;
510 OS << " // Opcodes are emitted as 2 bytes, TARGET_OPCODE handles this.\n";
511 OS << " #define TARGET_OPCODE(X) X & 255, unsigned(X) >> 8\n";
512 OS << " static const unsigned char MatcherTable[] = {\n";
513 unsigned TotalSize = MatcherEmitter.EmitMatcherList(Matcher, 5, 0, OS);
514 OS << " 0\n }; // Total Array size is " << (TotalSize+1) << " bytes\n\n";
515 OS << " #undef TARGET_OPCODE\n";
516 OS << " return SelectCodeCommon(N, MatcherTable,sizeof(MatcherTable));\n}\n";
519 // Next up, emit the function for node and pattern predicates:
520 MatcherEmitter.EmitPredicateFunctions(OS);