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