1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===// 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 /// \file 10 /// This tablegen backend emits code for use by the GlobalISel instruction 11 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td. 12 /// 13 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen 14 /// backend, filters out the ones that are unsupported, maps 15 /// SelectionDAG-specific constructs to their GlobalISel counterpart 16 /// (when applicable: MVT to LLT; SDNode to generic Instruction). 17 /// 18 /// Not all patterns are supported: pass the tablegen invocation 19 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped, 20 /// as well as why. 21 /// 22 /// The generated file defines a single method: 23 /// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const; 24 /// intended to be used in InstructionSelector::select as the first-step 25 /// selector for the patterns that don't require complex C++. 26 /// 27 /// FIXME: We'll probably want to eventually define a base 28 /// "TargetGenInstructionSelector" class. 29 /// 30 //===----------------------------------------------------------------------===// 31 32 #include "CodeGenDAGPatterns.h" 33 #include "CodeGenInstruction.h" 34 #include "SubtargetFeatureInfo.h" 35 #include "llvm/ADT/Optional.h" 36 #include "llvm/ADT/Statistic.h" 37 #include "llvm/Support/CodeGenCoverage.h" 38 #include "llvm/Support/CommandLine.h" 39 #include "llvm/Support/Error.h" 40 #include "llvm/Support/LowLevelTypeImpl.h" 41 #include "llvm/Support/MachineValueType.h" 42 #include "llvm/Support/ScopedPrinter.h" 43 #include "llvm/TableGen/Error.h" 44 #include "llvm/TableGen/Record.h" 45 #include "llvm/TableGen/TableGenBackend.h" 46 #include <numeric> 47 #include <string> 48 using namespace llvm; 49 50 #define DEBUG_TYPE "gisel-emitter" 51 52 STATISTIC(NumPatternTotal, "Total number of patterns"); 53 STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG"); 54 STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped"); 55 STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information"); 56 STATISTIC(NumPatternEmitted, "Number of patterns emitted"); 57 58 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel"); 59 60 static cl::opt<bool> WarnOnSkippedPatterns( 61 "warn-on-skipped-patterns", 62 cl::desc("Explain why a pattern was skipped for inclusion " 63 "in the GlobalISel selector"), 64 cl::init(false), cl::cat(GlobalISelEmitterCat)); 65 66 static cl::opt<bool> GenerateCoverage( 67 "instrument-gisel-coverage", 68 cl::desc("Generate coverage instrumentation for GlobalISel"), 69 cl::init(false), cl::cat(GlobalISelEmitterCat)); 70 71 static cl::opt<std::string> UseCoverageFile( 72 "gisel-coverage-file", cl::init(""), 73 cl::desc("Specify file to retrieve coverage information from"), 74 cl::cat(GlobalISelEmitterCat)); 75 76 static cl::opt<bool> OptimizeMatchTable( 77 "optimize-match-table", 78 cl::desc("Generate an optimized version of the match table"), 79 cl::init(true), cl::cat(GlobalISelEmitterCat)); 80 81 namespace { 82 //===- Helper functions ---------------------------------------------------===// 83 84 /// Get the name of the enum value used to number the predicate function. 85 std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) { 86 if (Predicate.hasGISelPredicateCode()) 87 return "GIPFP_MI_" + Predicate.getFnName(); 88 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" + 89 Predicate.getFnName(); 90 } 91 92 /// Get the opcode used to check this predicate. 93 std::string getMatchOpcodeForImmPredicate(const TreePredicateFn &Predicate) { 94 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate"; 95 } 96 97 /// This class stands in for LLT wherever we want to tablegen-erate an 98 /// equivalent at compiler run-time. 99 class LLTCodeGen { 100 private: 101 LLT Ty; 102 103 public: 104 LLTCodeGen() = default; 105 LLTCodeGen(const LLT &Ty) : Ty(Ty) {} 106 107 std::string getCxxEnumValue() const { 108 std::string Str; 109 raw_string_ostream OS(Str); 110 111 emitCxxEnumValue(OS); 112 return Str; 113 } 114 115 void emitCxxEnumValue(raw_ostream &OS) const { 116 if (Ty.isScalar()) { 117 OS << "GILLT_s" << Ty.getSizeInBits(); 118 return; 119 } 120 if (Ty.isVector()) { 121 OS << (Ty.isScalable() ? "GILLT_nxv" : "GILLT_v") 122 << Ty.getElementCount().getKnownMinValue() << "s" 123 << Ty.getScalarSizeInBits(); 124 return; 125 } 126 if (Ty.isPointer()) { 127 OS << "GILLT_p" << Ty.getAddressSpace(); 128 if (Ty.getSizeInBits() > 0) 129 OS << "s" << Ty.getSizeInBits(); 130 return; 131 } 132 llvm_unreachable("Unhandled LLT"); 133 } 134 135 void emitCxxConstructorCall(raw_ostream &OS) const { 136 if (Ty.isScalar()) { 137 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")"; 138 return; 139 } 140 if (Ty.isVector()) { 141 OS << "LLT::vector(" 142 << (Ty.isScalable() ? "ElementCount::getScalable(" 143 : "ElementCount::getFixed(") 144 << Ty.getElementCount().getKnownMinValue() << "), " 145 << Ty.getScalarSizeInBits() << ")"; 146 return; 147 } 148 if (Ty.isPointer() && Ty.getSizeInBits() > 0) { 149 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", " 150 << Ty.getSizeInBits() << ")"; 151 return; 152 } 153 llvm_unreachable("Unhandled LLT"); 154 } 155 156 const LLT &get() const { return Ty; } 157 158 /// This ordering is used for std::unique() and llvm::sort(). There's no 159 /// particular logic behind the order but either A < B or B < A must be 160 /// true if A != B. 161 bool operator<(const LLTCodeGen &Other) const { 162 if (Ty.isValid() != Other.Ty.isValid()) 163 return Ty.isValid() < Other.Ty.isValid(); 164 if (!Ty.isValid()) 165 return false; 166 167 if (Ty.isVector() != Other.Ty.isVector()) 168 return Ty.isVector() < Other.Ty.isVector(); 169 if (Ty.isScalar() != Other.Ty.isScalar()) 170 return Ty.isScalar() < Other.Ty.isScalar(); 171 if (Ty.isPointer() != Other.Ty.isPointer()) 172 return Ty.isPointer() < Other.Ty.isPointer(); 173 174 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace()) 175 return Ty.getAddressSpace() < Other.Ty.getAddressSpace(); 176 177 if (Ty.isVector() && Ty.getElementCount() != Other.Ty.getElementCount()) 178 return std::make_tuple(Ty.isScalable(), 179 Ty.getElementCount().getKnownMinValue()) < 180 std::make_tuple(Other.Ty.isScalable(), 181 Other.Ty.getElementCount().getKnownMinValue()); 182 183 assert((!Ty.isVector() || Ty.isScalable() == Other.Ty.isScalable()) && 184 "Unexpected mismatch of scalable property"); 185 return Ty.isVector() 186 ? std::make_tuple(Ty.isScalable(), 187 Ty.getSizeInBits().getKnownMinSize()) < 188 std::make_tuple(Other.Ty.isScalable(), 189 Other.Ty.getSizeInBits().getKnownMinSize()) 190 : Ty.getSizeInBits().getFixedSize() < 191 Other.Ty.getSizeInBits().getFixedSize(); 192 } 193 194 bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; } 195 }; 196 197 // Track all types that are used so we can emit the corresponding enum. 198 std::set<LLTCodeGen> KnownTypes; 199 200 class InstructionMatcher; 201 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for 202 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...). 203 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) { 204 MVT VT(SVT); 205 206 if (VT.isVector() && !VT.getVectorElementCount().isScalar()) 207 return LLTCodeGen( 208 LLT::vector(VT.getVectorElementCount(), VT.getScalarSizeInBits())); 209 210 if (VT.isInteger() || VT.isFloatingPoint()) 211 return LLTCodeGen(LLT::scalar(VT.getSizeInBits())); 212 213 return None; 214 } 215 216 static std::string explainPredicates(const TreePatternNode *N) { 217 std::string Explanation; 218 StringRef Separator = ""; 219 for (const TreePredicateCall &Call : N->getPredicateCalls()) { 220 const TreePredicateFn &P = Call.Fn; 221 Explanation += 222 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str(); 223 Separator = ", "; 224 225 if (P.isAlwaysTrue()) 226 Explanation += " always-true"; 227 if (P.isImmediatePattern()) 228 Explanation += " immediate"; 229 230 if (P.isUnindexed()) 231 Explanation += " unindexed"; 232 233 if (P.isNonExtLoad()) 234 Explanation += " non-extload"; 235 if (P.isAnyExtLoad()) 236 Explanation += " extload"; 237 if (P.isSignExtLoad()) 238 Explanation += " sextload"; 239 if (P.isZeroExtLoad()) 240 Explanation += " zextload"; 241 242 if (P.isNonTruncStore()) 243 Explanation += " non-truncstore"; 244 if (P.isTruncStore()) 245 Explanation += " truncstore"; 246 247 if (Record *VT = P.getMemoryVT()) 248 Explanation += (" MemVT=" + VT->getName()).str(); 249 if (Record *VT = P.getScalarMemoryVT()) 250 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str(); 251 252 if (ListInit *AddrSpaces = P.getAddressSpaces()) { 253 raw_string_ostream OS(Explanation); 254 OS << " AddressSpaces=["; 255 256 StringRef AddrSpaceSeparator; 257 for (Init *Val : AddrSpaces->getValues()) { 258 IntInit *IntVal = dyn_cast<IntInit>(Val); 259 if (!IntVal) 260 continue; 261 262 OS << AddrSpaceSeparator << IntVal->getValue(); 263 AddrSpaceSeparator = ", "; 264 } 265 266 OS << ']'; 267 } 268 269 int64_t MinAlign = P.getMinAlignment(); 270 if (MinAlign > 0) 271 Explanation += " MinAlign=" + utostr(MinAlign); 272 273 if (P.isAtomicOrderingMonotonic()) 274 Explanation += " monotonic"; 275 if (P.isAtomicOrderingAcquire()) 276 Explanation += " acquire"; 277 if (P.isAtomicOrderingRelease()) 278 Explanation += " release"; 279 if (P.isAtomicOrderingAcquireRelease()) 280 Explanation += " acq_rel"; 281 if (P.isAtomicOrderingSequentiallyConsistent()) 282 Explanation += " seq_cst"; 283 if (P.isAtomicOrderingAcquireOrStronger()) 284 Explanation += " >=acquire"; 285 if (P.isAtomicOrderingWeakerThanAcquire()) 286 Explanation += " <acquire"; 287 if (P.isAtomicOrderingReleaseOrStronger()) 288 Explanation += " >=release"; 289 if (P.isAtomicOrderingWeakerThanRelease()) 290 Explanation += " <release"; 291 } 292 return Explanation; 293 } 294 295 std::string explainOperator(Record *Operator) { 296 if (Operator->isSubClassOf("SDNode")) 297 return (" (" + Operator->getValueAsString("Opcode") + ")").str(); 298 299 if (Operator->isSubClassOf("Intrinsic")) 300 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str(); 301 302 if (Operator->isSubClassOf("ComplexPattern")) 303 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() + 304 ")") 305 .str(); 306 307 if (Operator->isSubClassOf("SDNodeXForm")) 308 return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() + 309 ")") 310 .str(); 311 312 return (" (Operator " + Operator->getName() + " not understood)").str(); 313 } 314 315 /// Helper function to let the emitter report skip reason error messages. 316 static Error failedImport(const Twine &Reason) { 317 return make_error<StringError>(Reason, inconvertibleErrorCode()); 318 } 319 320 static Error isTrivialOperatorNode(const TreePatternNode *N) { 321 std::string Explanation; 322 std::string Separator; 323 324 bool HasUnsupportedPredicate = false; 325 for (const TreePredicateCall &Call : N->getPredicateCalls()) { 326 const TreePredicateFn &Predicate = Call.Fn; 327 328 if (Predicate.isAlwaysTrue()) 329 continue; 330 331 if (Predicate.isImmediatePattern()) 332 continue; 333 334 if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() || 335 Predicate.isSignExtLoad() || Predicate.isZeroExtLoad()) 336 continue; 337 338 if (Predicate.isNonTruncStore() || Predicate.isTruncStore()) 339 continue; 340 341 if (Predicate.isLoad() && Predicate.getMemoryVT()) 342 continue; 343 344 if (Predicate.isLoad() || Predicate.isStore()) { 345 if (Predicate.isUnindexed()) 346 continue; 347 } 348 349 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) { 350 const ListInit *AddrSpaces = Predicate.getAddressSpaces(); 351 if (AddrSpaces && !AddrSpaces->empty()) 352 continue; 353 354 if (Predicate.getMinAlignment() > 0) 355 continue; 356 } 357 358 if (Predicate.isAtomic() && Predicate.getMemoryVT()) 359 continue; 360 361 if (Predicate.isAtomic() && 362 (Predicate.isAtomicOrderingMonotonic() || 363 Predicate.isAtomicOrderingAcquire() || 364 Predicate.isAtomicOrderingRelease() || 365 Predicate.isAtomicOrderingAcquireRelease() || 366 Predicate.isAtomicOrderingSequentiallyConsistent() || 367 Predicate.isAtomicOrderingAcquireOrStronger() || 368 Predicate.isAtomicOrderingWeakerThanAcquire() || 369 Predicate.isAtomicOrderingReleaseOrStronger() || 370 Predicate.isAtomicOrderingWeakerThanRelease())) 371 continue; 372 373 if (Predicate.hasGISelPredicateCode()) 374 continue; 375 376 HasUnsupportedPredicate = true; 377 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")"; 378 Separator = ", "; 379 Explanation += (Separator + "first-failing:" + 380 Predicate.getOrigPatFragRecord()->getRecord()->getName()) 381 .str(); 382 break; 383 } 384 385 if (!HasUnsupportedPredicate) 386 return Error::success(); 387 388 return failedImport(Explanation); 389 } 390 391 static Record *getInitValueAsRegClass(Init *V) { 392 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) { 393 if (VDefInit->getDef()->isSubClassOf("RegisterOperand")) 394 return VDefInit->getDef()->getValueAsDef("RegClass"); 395 if (VDefInit->getDef()->isSubClassOf("RegisterClass")) 396 return VDefInit->getDef(); 397 } 398 return nullptr; 399 } 400 401 std::string 402 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) { 403 std::string Name = "GIFBS"; 404 for (const auto &Feature : FeatureBitset) 405 Name += ("_" + Feature->getName()).str(); 406 return Name; 407 } 408 409 static std::string getScopedName(unsigned Scope, const std::string &Name) { 410 return ("pred:" + Twine(Scope) + ":" + Name).str(); 411 } 412 413 //===- MatchTable Helpers -------------------------------------------------===// 414 415 class MatchTable; 416 417 /// A record to be stored in a MatchTable. 418 /// 419 /// This class represents any and all output that may be required to emit the 420 /// MatchTable. Instances are most often configured to represent an opcode or 421 /// value that will be emitted to the table with some formatting but it can also 422 /// represent commas, comments, and other formatting instructions. 423 struct MatchTableRecord { 424 enum RecordFlagsBits { 425 MTRF_None = 0x0, 426 /// Causes EmitStr to be formatted as comment when emitted. 427 MTRF_Comment = 0x1, 428 /// Causes the record value to be followed by a comma when emitted. 429 MTRF_CommaFollows = 0x2, 430 /// Causes the record value to be followed by a line break when emitted. 431 MTRF_LineBreakFollows = 0x4, 432 /// Indicates that the record defines a label and causes an additional 433 /// comment to be emitted containing the index of the label. 434 MTRF_Label = 0x8, 435 /// Causes the record to be emitted as the index of the label specified by 436 /// LabelID along with a comment indicating where that label is. 437 MTRF_JumpTarget = 0x10, 438 /// Causes the formatter to add a level of indentation before emitting the 439 /// record. 440 MTRF_Indent = 0x20, 441 /// Causes the formatter to remove a level of indentation after emitting the 442 /// record. 443 MTRF_Outdent = 0x40, 444 }; 445 446 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to 447 /// reference or define. 448 unsigned LabelID; 449 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a 450 /// value, a label name. 451 std::string EmitStr; 452 453 private: 454 /// The number of MatchTable elements described by this record. Comments are 0 455 /// while values are typically 1. Values >1 may occur when we need to emit 456 /// values that exceed the size of a MatchTable element. 457 unsigned NumElements; 458 459 public: 460 /// A bitfield of RecordFlagsBits flags. 461 unsigned Flags; 462 463 /// The actual run-time value, if known 464 int64_t RawValue; 465 466 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr, 467 unsigned NumElements, unsigned Flags, 468 int64_t RawValue = std::numeric_limits<int64_t>::min()) 469 : LabelID(LabelID_.getValueOr(~0u)), EmitStr(EmitStr), 470 NumElements(NumElements), Flags(Flags), RawValue(RawValue) { 471 assert((!LabelID_.hasValue() || LabelID != ~0u) && 472 "This value is reserved for non-labels"); 473 } 474 MatchTableRecord(const MatchTableRecord &Other) = default; 475 MatchTableRecord(MatchTableRecord &&Other) = default; 476 477 /// Useful if a Match Table Record gets optimized out 478 void turnIntoComment() { 479 Flags |= MTRF_Comment; 480 Flags &= ~MTRF_CommaFollows; 481 NumElements = 0; 482 } 483 484 /// For Jump Table generation purposes 485 bool operator<(const MatchTableRecord &Other) const { 486 return RawValue < Other.RawValue; 487 } 488 int64_t getRawValue() const { return RawValue; } 489 490 void emit(raw_ostream &OS, bool LineBreakNextAfterThis, 491 const MatchTable &Table) const; 492 unsigned size() const { return NumElements; } 493 }; 494 495 class Matcher; 496 497 /// Holds the contents of a generated MatchTable to enable formatting and the 498 /// necessary index tracking needed to support GIM_Try. 499 class MatchTable { 500 /// An unique identifier for the table. The generated table will be named 501 /// MatchTable${ID}. 502 unsigned ID; 503 /// The records that make up the table. Also includes comments describing the 504 /// values being emitted and line breaks to format it. 505 std::vector<MatchTableRecord> Contents; 506 /// The currently defined labels. 507 DenseMap<unsigned, unsigned> LabelMap; 508 /// Tracks the sum of MatchTableRecord::NumElements as the table is built. 509 unsigned CurrentSize = 0; 510 /// A unique identifier for a MatchTable label. 511 unsigned CurrentLabelID = 0; 512 /// Determines if the table should be instrumented for rule coverage tracking. 513 bool IsWithCoverage; 514 515 public: 516 static MatchTableRecord LineBreak; 517 static MatchTableRecord Comment(StringRef Comment) { 518 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment); 519 } 520 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) { 521 unsigned ExtraFlags = 0; 522 if (IndentAdjust > 0) 523 ExtraFlags |= MatchTableRecord::MTRF_Indent; 524 if (IndentAdjust < 0) 525 ExtraFlags |= MatchTableRecord::MTRF_Outdent; 526 527 return MatchTableRecord(None, Opcode, 1, 528 MatchTableRecord::MTRF_CommaFollows | ExtraFlags); 529 } 530 static MatchTableRecord NamedValue(StringRef NamedValue) { 531 return MatchTableRecord(None, NamedValue, 1, 532 MatchTableRecord::MTRF_CommaFollows); 533 } 534 static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) { 535 return MatchTableRecord(None, NamedValue, 1, 536 MatchTableRecord::MTRF_CommaFollows, RawValue); 537 } 538 static MatchTableRecord NamedValue(StringRef Namespace, 539 StringRef NamedValue) { 540 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1, 541 MatchTableRecord::MTRF_CommaFollows); 542 } 543 static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue, 544 int64_t RawValue) { 545 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1, 546 MatchTableRecord::MTRF_CommaFollows, RawValue); 547 } 548 static MatchTableRecord IntValue(int64_t IntValue) { 549 return MatchTableRecord(None, llvm::to_string(IntValue), 1, 550 MatchTableRecord::MTRF_CommaFollows); 551 } 552 static MatchTableRecord Label(unsigned LabelID) { 553 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0, 554 MatchTableRecord::MTRF_Label | 555 MatchTableRecord::MTRF_Comment | 556 MatchTableRecord::MTRF_LineBreakFollows); 557 } 558 static MatchTableRecord JumpTarget(unsigned LabelID) { 559 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1, 560 MatchTableRecord::MTRF_JumpTarget | 561 MatchTableRecord::MTRF_Comment | 562 MatchTableRecord::MTRF_CommaFollows); 563 } 564 565 static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage); 566 567 MatchTable(bool WithCoverage, unsigned ID = 0) 568 : ID(ID), IsWithCoverage(WithCoverage) {} 569 570 bool isWithCoverage() const { return IsWithCoverage; } 571 572 void push_back(const MatchTableRecord &Value) { 573 if (Value.Flags & MatchTableRecord::MTRF_Label) 574 defineLabel(Value.LabelID); 575 Contents.push_back(Value); 576 CurrentSize += Value.size(); 577 } 578 579 unsigned allocateLabelID() { return CurrentLabelID++; } 580 581 void defineLabel(unsigned LabelID) { 582 LabelMap.insert(std::make_pair(LabelID, CurrentSize)); 583 } 584 585 unsigned getLabelIndex(unsigned LabelID) const { 586 const auto I = LabelMap.find(LabelID); 587 assert(I != LabelMap.end() && "Use of undeclared label"); 588 return I->second; 589 } 590 591 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; } 592 593 void emitDeclaration(raw_ostream &OS) const { 594 unsigned Indentation = 4; 595 OS << " constexpr static int64_t MatchTable" << ID << "[] = {"; 596 LineBreak.emit(OS, true, *this); 597 OS << std::string(Indentation, ' '); 598 599 for (auto I = Contents.begin(), E = Contents.end(); I != E; 600 ++I) { 601 bool LineBreakIsNext = false; 602 const auto &NextI = std::next(I); 603 604 if (NextI != E) { 605 if (NextI->EmitStr == "" && 606 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows) 607 LineBreakIsNext = true; 608 } 609 610 if (I->Flags & MatchTableRecord::MTRF_Indent) 611 Indentation += 2; 612 613 I->emit(OS, LineBreakIsNext, *this); 614 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows) 615 OS << std::string(Indentation, ' '); 616 617 if (I->Flags & MatchTableRecord::MTRF_Outdent) 618 Indentation -= 2; 619 } 620 OS << "};\n"; 621 } 622 }; 623 624 MatchTableRecord MatchTable::LineBreak = { 625 None, "" /* Emit String */, 0 /* Elements */, 626 MatchTableRecord::MTRF_LineBreakFollows}; 627 628 void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis, 629 const MatchTable &Table) const { 630 bool UseLineComment = 631 LineBreakIsNextAfterThis || (Flags & MTRF_LineBreakFollows); 632 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows)) 633 UseLineComment = false; 634 635 if (Flags & MTRF_Comment) 636 OS << (UseLineComment ? "// " : "/*"); 637 638 OS << EmitStr; 639 if (Flags & MTRF_Label) 640 OS << ": @" << Table.getLabelIndex(LabelID); 641 642 if ((Flags & MTRF_Comment) && !UseLineComment) 643 OS << "*/"; 644 645 if (Flags & MTRF_JumpTarget) { 646 if (Flags & MTRF_Comment) 647 OS << " "; 648 OS << Table.getLabelIndex(LabelID); 649 } 650 651 if (Flags & MTRF_CommaFollows) { 652 OS << ","; 653 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows)) 654 OS << " "; 655 } 656 657 if (Flags & MTRF_LineBreakFollows) 658 OS << "\n"; 659 } 660 661 MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) { 662 Table.push_back(Value); 663 return Table; 664 } 665 666 //===- Matchers -----------------------------------------------------------===// 667 668 class OperandMatcher; 669 class MatchAction; 670 class PredicateMatcher; 671 672 class Matcher { 673 public: 674 virtual ~Matcher() = default; 675 virtual void optimize() {} 676 virtual void emit(MatchTable &Table) = 0; 677 678 virtual bool hasFirstCondition() const = 0; 679 virtual const PredicateMatcher &getFirstCondition() const = 0; 680 virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0; 681 }; 682 683 MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules, 684 bool WithCoverage) { 685 MatchTable Table(WithCoverage); 686 for (Matcher *Rule : Rules) 687 Rule->emit(Table); 688 689 return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak; 690 } 691 692 class GroupMatcher final : public Matcher { 693 /// Conditions that form a common prefix of all the matchers contained. 694 SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions; 695 696 /// All the nested matchers, sharing a common prefix. 697 std::vector<Matcher *> Matchers; 698 699 /// An owning collection for any auxiliary matchers created while optimizing 700 /// nested matchers contained. 701 std::vector<std::unique_ptr<Matcher>> MatcherStorage; 702 703 public: 704 /// Add a matcher to the collection of nested matchers if it meets the 705 /// requirements, and return true. If it doesn't, do nothing and return false. 706 /// 707 /// Expected to preserve its argument, so it could be moved out later on. 708 bool addMatcher(Matcher &Candidate); 709 710 /// Mark the matcher as fully-built and ensure any invariants expected by both 711 /// optimize() and emit(...) methods. Generally, both sequences of calls 712 /// are expected to lead to a sensible result: 713 /// 714 /// addMatcher(...)*; finalize(); optimize(); emit(...); and 715 /// addMatcher(...)*; finalize(); emit(...); 716 /// 717 /// or generally 718 /// 719 /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }* 720 /// 721 /// Multiple calls to optimize() are expected to be handled gracefully, though 722 /// optimize() is not expected to be idempotent. Multiple calls to finalize() 723 /// aren't generally supported. emit(...) is expected to be non-mutating and 724 /// producing the exact same results upon repeated calls. 725 /// 726 /// addMatcher() calls after the finalize() call are not supported. 727 /// 728 /// finalize() and optimize() are both allowed to mutate the contained 729 /// matchers, so moving them out after finalize() is not supported. 730 void finalize(); 731 void optimize() override; 732 void emit(MatchTable &Table) override; 733 734 /// Could be used to move out the matchers added previously, unless finalize() 735 /// has been already called. If any of the matchers are moved out, the group 736 /// becomes safe to destroy, but not safe to re-use for anything else. 737 iterator_range<std::vector<Matcher *>::iterator> matchers() { 738 return make_range(Matchers.begin(), Matchers.end()); 739 } 740 size_t size() const { return Matchers.size(); } 741 bool empty() const { return Matchers.empty(); } 742 743 std::unique_ptr<PredicateMatcher> popFirstCondition() override { 744 assert(!Conditions.empty() && 745 "Trying to pop a condition from a condition-less group"); 746 std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front()); 747 Conditions.erase(Conditions.begin()); 748 return P; 749 } 750 const PredicateMatcher &getFirstCondition() const override { 751 assert(!Conditions.empty() && 752 "Trying to get a condition from a condition-less group"); 753 return *Conditions.front(); 754 } 755 bool hasFirstCondition() const override { return !Conditions.empty(); } 756 757 private: 758 /// See if a candidate matcher could be added to this group solely by 759 /// analyzing its first condition. 760 bool candidateConditionMatches(const PredicateMatcher &Predicate) const; 761 }; 762 763 class SwitchMatcher : public Matcher { 764 /// All the nested matchers, representing distinct switch-cases. The first 765 /// conditions (as Matcher::getFirstCondition() reports) of all the nested 766 /// matchers must share the same type and path to a value they check, in other 767 /// words, be isIdenticalDownToValue, but have different values they check 768 /// against. 769 std::vector<Matcher *> Matchers; 770 771 /// The representative condition, with a type and a path (InsnVarID and OpIdx 772 /// in most cases) shared by all the matchers contained. 773 std::unique_ptr<PredicateMatcher> Condition = nullptr; 774 775 /// Temporary set used to check that the case values don't repeat within the 776 /// same switch. 777 std::set<MatchTableRecord> Values; 778 779 /// An owning collection for any auxiliary matchers created while optimizing 780 /// nested matchers contained. 781 std::vector<std::unique_ptr<Matcher>> MatcherStorage; 782 783 public: 784 bool addMatcher(Matcher &Candidate); 785 786 void finalize(); 787 void emit(MatchTable &Table) override; 788 789 iterator_range<std::vector<Matcher *>::iterator> matchers() { 790 return make_range(Matchers.begin(), Matchers.end()); 791 } 792 size_t size() const { return Matchers.size(); } 793 bool empty() const { return Matchers.empty(); } 794 795 std::unique_ptr<PredicateMatcher> popFirstCondition() override { 796 // SwitchMatcher doesn't have a common first condition for its cases, as all 797 // the cases only share a kind of a value (a type and a path to it) they 798 // match, but deliberately differ in the actual value they match. 799 llvm_unreachable("Trying to pop a condition from a condition-less group"); 800 } 801 const PredicateMatcher &getFirstCondition() const override { 802 llvm_unreachable("Trying to pop a condition from a condition-less group"); 803 } 804 bool hasFirstCondition() const override { return false; } 805 806 private: 807 /// See if the predicate type has a Switch-implementation for it. 808 static bool isSupportedPredicateType(const PredicateMatcher &Predicate); 809 810 bool candidateConditionMatches(const PredicateMatcher &Predicate) const; 811 812 /// emit()-helper 813 static void emitPredicateSpecificOpcodes(const PredicateMatcher &P, 814 MatchTable &Table); 815 }; 816 817 /// Generates code to check that a match rule matches. 818 class RuleMatcher : public Matcher { 819 public: 820 using ActionList = std::list<std::unique_ptr<MatchAction>>; 821 using action_iterator = ActionList::iterator; 822 823 protected: 824 /// A list of matchers that all need to succeed for the current rule to match. 825 /// FIXME: This currently supports a single match position but could be 826 /// extended to support multiple positions to support div/rem fusion or 827 /// load-multiple instructions. 828 using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ; 829 MatchersTy Matchers; 830 831 /// A list of actions that need to be taken when all predicates in this rule 832 /// have succeeded. 833 ActionList Actions; 834 835 using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>; 836 837 /// A map of instruction matchers to the local variables 838 DefinedInsnVariablesMap InsnVariableIDs; 839 840 using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>; 841 842 // The set of instruction matchers that have not yet been claimed for mutation 843 // by a BuildMI. 844 MutatableInsnSet MutatableInsns; 845 846 /// A map of named operands defined by the matchers that may be referenced by 847 /// the renderers. 848 StringMap<OperandMatcher *> DefinedOperands; 849 850 /// A map of anonymous physical register operands defined by the matchers that 851 /// may be referenced by the renderers. 852 DenseMap<Record *, OperandMatcher *> PhysRegOperands; 853 854 /// ID for the next instruction variable defined with implicitlyDefineInsnVar() 855 unsigned NextInsnVarID; 856 857 /// ID for the next output instruction allocated with allocateOutputInsnID() 858 unsigned NextOutputInsnID; 859 860 /// ID for the next temporary register ID allocated with allocateTempRegID() 861 unsigned NextTempRegID; 862 863 std::vector<Record *> RequiredFeatures; 864 std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers; 865 866 ArrayRef<SMLoc> SrcLoc; 867 868 typedef std::tuple<Record *, unsigned, unsigned> 869 DefinedComplexPatternSubOperand; 870 typedef StringMap<DefinedComplexPatternSubOperand> 871 DefinedComplexPatternSubOperandMap; 872 /// A map of Symbolic Names to ComplexPattern sub-operands. 873 DefinedComplexPatternSubOperandMap ComplexSubOperands; 874 /// A map used to for multiple referenced error check of ComplexSubOperand. 875 /// ComplexSubOperand can't be referenced multiple from different operands, 876 /// however multiple references from same operand are allowed since that is 877 /// how 'same operand checks' are generated. 878 StringMap<std::string> ComplexSubOperandsParentName; 879 880 uint64_t RuleID; 881 static uint64_t NextRuleID; 882 883 public: 884 RuleMatcher(ArrayRef<SMLoc> SrcLoc) 885 : NextInsnVarID(0), NextOutputInsnID(0), NextTempRegID(0), SrcLoc(SrcLoc), 886 RuleID(NextRuleID++) {} 887 RuleMatcher(RuleMatcher &&Other) = default; 888 RuleMatcher &operator=(RuleMatcher &&Other) = default; 889 890 uint64_t getRuleID() const { return RuleID; } 891 892 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName); 893 void addRequiredFeature(Record *Feature); 894 const std::vector<Record *> &getRequiredFeatures() const; 895 896 template <class Kind, class... Args> Kind &addAction(Args &&... args); 897 template <class Kind, class... Args> 898 action_iterator insertAction(action_iterator InsertPt, Args &&... args); 899 900 /// Define an instruction without emitting any code to do so. 901 unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher); 902 903 unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const; 904 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const { 905 return InsnVariableIDs.begin(); 906 } 907 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const { 908 return InsnVariableIDs.end(); 909 } 910 iterator_range<typename DefinedInsnVariablesMap::const_iterator> 911 defined_insn_vars() const { 912 return make_range(defined_insn_vars_begin(), defined_insn_vars_end()); 913 } 914 915 MutatableInsnSet::const_iterator mutatable_insns_begin() const { 916 return MutatableInsns.begin(); 917 } 918 MutatableInsnSet::const_iterator mutatable_insns_end() const { 919 return MutatableInsns.end(); 920 } 921 iterator_range<typename MutatableInsnSet::const_iterator> 922 mutatable_insns() const { 923 return make_range(mutatable_insns_begin(), mutatable_insns_end()); 924 } 925 void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) { 926 bool R = MutatableInsns.erase(InsnMatcher); 927 assert(R && "Reserving a mutatable insn that isn't available"); 928 (void)R; 929 } 930 931 action_iterator actions_begin() { return Actions.begin(); } 932 action_iterator actions_end() { return Actions.end(); } 933 iterator_range<action_iterator> actions() { 934 return make_range(actions_begin(), actions_end()); 935 } 936 937 void defineOperand(StringRef SymbolicName, OperandMatcher &OM); 938 939 void definePhysRegOperand(Record *Reg, OperandMatcher &OM); 940 941 Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern, 942 unsigned RendererID, unsigned SubOperandID, 943 StringRef ParentSymbolicName) { 944 std::string ParentName(ParentSymbolicName); 945 if (ComplexSubOperands.count(SymbolicName)) { 946 const std::string &RecordedParentName = 947 ComplexSubOperandsParentName[SymbolicName]; 948 if (RecordedParentName != ParentName) 949 return failedImport("Error: Complex suboperand " + SymbolicName + 950 " referenced by different operands: " + 951 RecordedParentName + " and " + ParentName + "."); 952 // Complex suboperand referenced more than once from same the operand is 953 // used to generate 'same operand check'. Emitting of 954 // GIR_ComplexSubOperandRenderer for them is already handled. 955 return Error::success(); 956 } 957 958 ComplexSubOperands[SymbolicName] = 959 std::make_tuple(ComplexPattern, RendererID, SubOperandID); 960 ComplexSubOperandsParentName[SymbolicName] = ParentName; 961 962 return Error::success(); 963 } 964 965 Optional<DefinedComplexPatternSubOperand> 966 getComplexSubOperand(StringRef SymbolicName) const { 967 const auto &I = ComplexSubOperands.find(SymbolicName); 968 if (I == ComplexSubOperands.end()) 969 return None; 970 return I->second; 971 } 972 973 InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const; 974 const OperandMatcher &getOperandMatcher(StringRef Name) const; 975 const OperandMatcher &getPhysRegOperandMatcher(Record *) const; 976 977 void optimize() override; 978 void emit(MatchTable &Table) override; 979 980 /// Compare the priority of this object and B. 981 /// 982 /// Returns true if this object is more important than B. 983 bool isHigherPriorityThan(const RuleMatcher &B) const; 984 985 /// Report the maximum number of temporary operands needed by the rule 986 /// matcher. 987 unsigned countRendererFns() const; 988 989 std::unique_ptr<PredicateMatcher> popFirstCondition() override; 990 const PredicateMatcher &getFirstCondition() const override; 991 LLTCodeGen getFirstConditionAsRootType(); 992 bool hasFirstCondition() const override; 993 unsigned getNumOperands() const; 994 StringRef getOpcode() const; 995 996 // FIXME: Remove this as soon as possible 997 InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); } 998 999 unsigned allocateOutputInsnID() { return NextOutputInsnID++; } 1000 unsigned allocateTempRegID() { return NextTempRegID++; } 1001 1002 iterator_range<MatchersTy::iterator> insnmatchers() { 1003 return make_range(Matchers.begin(), Matchers.end()); 1004 } 1005 bool insnmatchers_empty() const { return Matchers.empty(); } 1006 void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); } 1007 }; 1008 1009 uint64_t RuleMatcher::NextRuleID = 0; 1010 1011 using action_iterator = RuleMatcher::action_iterator; 1012 1013 template <class PredicateTy> class PredicateListMatcher { 1014 private: 1015 /// Template instantiations should specialize this to return a string to use 1016 /// for the comment emitted when there are no predicates. 1017 std::string getNoPredicateComment() const; 1018 1019 protected: 1020 using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>; 1021 PredicatesTy Predicates; 1022 1023 /// Track if the list of predicates was manipulated by one of the optimization 1024 /// methods. 1025 bool Optimized = false; 1026 1027 public: 1028 typename PredicatesTy::iterator predicates_begin() { 1029 return Predicates.begin(); 1030 } 1031 typename PredicatesTy::iterator predicates_end() { 1032 return Predicates.end(); 1033 } 1034 iterator_range<typename PredicatesTy::iterator> predicates() { 1035 return make_range(predicates_begin(), predicates_end()); 1036 } 1037 typename PredicatesTy::size_type predicates_size() const { 1038 return Predicates.size(); 1039 } 1040 bool predicates_empty() const { return Predicates.empty(); } 1041 1042 std::unique_ptr<PredicateTy> predicates_pop_front() { 1043 std::unique_ptr<PredicateTy> Front = std::move(Predicates.front()); 1044 Predicates.pop_front(); 1045 Optimized = true; 1046 return Front; 1047 } 1048 1049 void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) { 1050 Predicates.push_front(std::move(Predicate)); 1051 } 1052 1053 void eraseNullPredicates() { 1054 const auto NewEnd = 1055 std::stable_partition(Predicates.begin(), Predicates.end(), 1056 std::logical_not<std::unique_ptr<PredicateTy>>()); 1057 if (NewEnd != Predicates.begin()) { 1058 Predicates.erase(Predicates.begin(), NewEnd); 1059 Optimized = true; 1060 } 1061 } 1062 1063 /// Emit MatchTable opcodes that tests whether all the predicates are met. 1064 template <class... Args> 1065 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) { 1066 if (Predicates.empty() && !Optimized) { 1067 Table << MatchTable::Comment(getNoPredicateComment()) 1068 << MatchTable::LineBreak; 1069 return; 1070 } 1071 1072 for (const auto &Predicate : predicates()) 1073 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...); 1074 } 1075 1076 /// Provide a function to avoid emitting certain predicates. This is used to 1077 /// defer some predicate checks until after others 1078 using PredicateFilterFunc = std::function<bool(const PredicateTy&)>; 1079 1080 /// Emit MatchTable opcodes for predicates which satisfy \p 1081 /// ShouldEmitPredicate. This should be called multiple times to ensure all 1082 /// predicates are eventually added to the match table. 1083 template <class... Args> 1084 void emitFilteredPredicateListOpcodes(PredicateFilterFunc ShouldEmitPredicate, 1085 MatchTable &Table, Args &&... args) { 1086 if (Predicates.empty() && !Optimized) { 1087 Table << MatchTable::Comment(getNoPredicateComment()) 1088 << MatchTable::LineBreak; 1089 return; 1090 } 1091 1092 for (const auto &Predicate : predicates()) { 1093 if (ShouldEmitPredicate(*Predicate)) 1094 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...); 1095 } 1096 } 1097 }; 1098 1099 class PredicateMatcher { 1100 public: 1101 /// This enum is used for RTTI and also defines the priority that is given to 1102 /// the predicate when generating the matcher code. Kinds with higher priority 1103 /// must be tested first. 1104 /// 1105 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter 1106 /// but OPM_Int must have priority over OPM_RegBank since constant integers 1107 /// are represented by a virtual register defined by a G_CONSTANT instruction. 1108 /// 1109 /// Note: The relative priority between IPM_ and OPM_ does not matter, they 1110 /// are currently not compared between each other. 1111 enum PredicateKind { 1112 IPM_Opcode, 1113 IPM_NumOperands, 1114 IPM_ImmPredicate, 1115 IPM_Imm, 1116 IPM_AtomicOrderingMMO, 1117 IPM_MemoryLLTSize, 1118 IPM_MemoryVsLLTSize, 1119 IPM_MemoryAddressSpace, 1120 IPM_MemoryAlignment, 1121 IPM_VectorSplatImm, 1122 IPM_GenericPredicate, 1123 OPM_SameOperand, 1124 OPM_ComplexPattern, 1125 OPM_IntrinsicID, 1126 OPM_CmpPredicate, 1127 OPM_Instruction, 1128 OPM_Int, 1129 OPM_LiteralInt, 1130 OPM_LLT, 1131 OPM_PointerToAny, 1132 OPM_RegBank, 1133 OPM_MBB, 1134 OPM_RecordNamedOperand, 1135 }; 1136 1137 protected: 1138 PredicateKind Kind; 1139 unsigned InsnVarID; 1140 unsigned OpIdx; 1141 1142 public: 1143 PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0) 1144 : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {} 1145 1146 unsigned getInsnVarID() const { return InsnVarID; } 1147 unsigned getOpIdx() const { return OpIdx; } 1148 1149 virtual ~PredicateMatcher() = default; 1150 /// Emit MatchTable opcodes that check the predicate for the given operand. 1151 virtual void emitPredicateOpcodes(MatchTable &Table, 1152 RuleMatcher &Rule) const = 0; 1153 1154 PredicateKind getKind() const { return Kind; } 1155 1156 bool dependsOnOperands() const { 1157 // Custom predicates really depend on the context pattern of the 1158 // instruction, not just the individual instruction. This therefore 1159 // implicitly depends on all other pattern constraints. 1160 return Kind == IPM_GenericPredicate; 1161 } 1162 1163 virtual bool isIdentical(const PredicateMatcher &B) const { 1164 return B.getKind() == getKind() && InsnVarID == B.InsnVarID && 1165 OpIdx == B.OpIdx; 1166 } 1167 1168 virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const { 1169 return hasValue() && PredicateMatcher::isIdentical(B); 1170 } 1171 1172 virtual MatchTableRecord getValue() const { 1173 assert(hasValue() && "Can not get a value of a value-less predicate!"); 1174 llvm_unreachable("Not implemented yet"); 1175 } 1176 virtual bool hasValue() const { return false; } 1177 1178 /// Report the maximum number of temporary operands needed by the predicate 1179 /// matcher. 1180 virtual unsigned countRendererFns() const { return 0; } 1181 }; 1182 1183 /// Generates code to check a predicate of an operand. 1184 /// 1185 /// Typical predicates include: 1186 /// * Operand is a particular register. 1187 /// * Operand is assigned a particular register bank. 1188 /// * Operand is an MBB. 1189 class OperandPredicateMatcher : public PredicateMatcher { 1190 public: 1191 OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID, 1192 unsigned OpIdx) 1193 : PredicateMatcher(Kind, InsnVarID, OpIdx) {} 1194 virtual ~OperandPredicateMatcher() {} 1195 1196 /// Compare the priority of this object and B. 1197 /// 1198 /// Returns true if this object is more important than B. 1199 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const; 1200 }; 1201 1202 template <> 1203 std::string 1204 PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const { 1205 return "No operand predicates"; 1206 } 1207 1208 /// Generates code to check that a register operand is defined by the same exact 1209 /// one as another. 1210 class SameOperandMatcher : public OperandPredicateMatcher { 1211 std::string MatchingName; 1212 unsigned OrigOpIdx; 1213 1214 public: 1215 SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName, 1216 unsigned OrigOpIdx) 1217 : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx), 1218 MatchingName(MatchingName), OrigOpIdx(OrigOpIdx) {} 1219 1220 static bool classof(const PredicateMatcher *P) { 1221 return P->getKind() == OPM_SameOperand; 1222 } 1223 1224 void emitPredicateOpcodes(MatchTable &Table, 1225 RuleMatcher &Rule) const override; 1226 1227 bool isIdentical(const PredicateMatcher &B) const override { 1228 return OperandPredicateMatcher::isIdentical(B) && 1229 OrigOpIdx == cast<SameOperandMatcher>(&B)->OrigOpIdx && 1230 MatchingName == cast<SameOperandMatcher>(&B)->MatchingName; 1231 } 1232 }; 1233 1234 /// Generates code to check that an operand is a particular LLT. 1235 class LLTOperandMatcher : public OperandPredicateMatcher { 1236 protected: 1237 LLTCodeGen Ty; 1238 1239 public: 1240 static std::map<LLTCodeGen, unsigned> TypeIDValues; 1241 1242 static void initTypeIDValuesMap() { 1243 TypeIDValues.clear(); 1244 1245 unsigned ID = 0; 1246 for (const LLTCodeGen &LLTy : KnownTypes) 1247 TypeIDValues[LLTy] = ID++; 1248 } 1249 1250 LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty) 1251 : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) { 1252 KnownTypes.insert(Ty); 1253 } 1254 1255 static bool classof(const PredicateMatcher *P) { 1256 return P->getKind() == OPM_LLT; 1257 } 1258 bool isIdentical(const PredicateMatcher &B) const override { 1259 return OperandPredicateMatcher::isIdentical(B) && 1260 Ty == cast<LLTOperandMatcher>(&B)->Ty; 1261 } 1262 MatchTableRecord getValue() const override { 1263 const auto VI = TypeIDValues.find(Ty); 1264 if (VI == TypeIDValues.end()) 1265 return MatchTable::NamedValue(getTy().getCxxEnumValue()); 1266 return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second); 1267 } 1268 bool hasValue() const override { 1269 if (TypeIDValues.size() != KnownTypes.size()) 1270 initTypeIDValuesMap(); 1271 return TypeIDValues.count(Ty); 1272 } 1273 1274 LLTCodeGen getTy() const { return Ty; } 1275 1276 void emitPredicateOpcodes(MatchTable &Table, 1277 RuleMatcher &Rule) const override { 1278 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI") 1279 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op") 1280 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type") 1281 << getValue() << MatchTable::LineBreak; 1282 } 1283 }; 1284 1285 std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues; 1286 1287 /// Generates code to check that an operand is a pointer to any address space. 1288 /// 1289 /// In SelectionDAG, the types did not describe pointers or address spaces. As a 1290 /// result, iN is used to describe a pointer of N bits to any address space and 1291 /// PatFrag predicates are typically used to constrain the address space. There's 1292 /// no reliable means to derive the missing type information from the pattern so 1293 /// imported rules must test the components of a pointer separately. 1294 /// 1295 /// If SizeInBits is zero, then the pointer size will be obtained from the 1296 /// subtarget. 1297 class PointerToAnyOperandMatcher : public OperandPredicateMatcher { 1298 protected: 1299 unsigned SizeInBits; 1300 1301 public: 1302 PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx, 1303 unsigned SizeInBits) 1304 : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx), 1305 SizeInBits(SizeInBits) {} 1306 1307 static bool classof(const PredicateMatcher *P) { 1308 return P->getKind() == OPM_PointerToAny; 1309 } 1310 1311 bool isIdentical(const PredicateMatcher &B) const override { 1312 return OperandPredicateMatcher::isIdentical(B) && 1313 SizeInBits == cast<PointerToAnyOperandMatcher>(&B)->SizeInBits; 1314 } 1315 1316 void emitPredicateOpcodes(MatchTable &Table, 1317 RuleMatcher &Rule) const override { 1318 Table << MatchTable::Opcode("GIM_CheckPointerToAny") 1319 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1320 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 1321 << MatchTable::Comment("SizeInBits") 1322 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak; 1323 } 1324 }; 1325 1326 /// Generates code to record named operand in RecordedOperands list at StoreIdx. 1327 /// Predicates with 'let PredicateCodeUsesOperands = 1' get RecordedOperands as 1328 /// an argument to predicate's c++ code once all operands have been matched. 1329 class RecordNamedOperandMatcher : public OperandPredicateMatcher { 1330 protected: 1331 unsigned StoreIdx; 1332 std::string Name; 1333 1334 public: 1335 RecordNamedOperandMatcher(unsigned InsnVarID, unsigned OpIdx, 1336 unsigned StoreIdx, StringRef Name) 1337 : OperandPredicateMatcher(OPM_RecordNamedOperand, InsnVarID, OpIdx), 1338 StoreIdx(StoreIdx), Name(Name) {} 1339 1340 static bool classof(const PredicateMatcher *P) { 1341 return P->getKind() == OPM_RecordNamedOperand; 1342 } 1343 1344 bool isIdentical(const PredicateMatcher &B) const override { 1345 return OperandPredicateMatcher::isIdentical(B) && 1346 StoreIdx == cast<RecordNamedOperandMatcher>(&B)->StoreIdx && 1347 Name == cast<RecordNamedOperandMatcher>(&B)->Name; 1348 } 1349 1350 void emitPredicateOpcodes(MatchTable &Table, 1351 RuleMatcher &Rule) const override { 1352 Table << MatchTable::Opcode("GIM_RecordNamedOperand") 1353 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1354 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 1355 << MatchTable::Comment("StoreIdx") << MatchTable::IntValue(StoreIdx) 1356 << MatchTable::Comment("Name : " + Name) << MatchTable::LineBreak; 1357 } 1358 }; 1359 1360 /// Generates code to check that an operand is a particular target constant. 1361 class ComplexPatternOperandMatcher : public OperandPredicateMatcher { 1362 protected: 1363 const OperandMatcher &Operand; 1364 const Record &TheDef; 1365 1366 unsigned getAllocatedTemporariesBaseID() const; 1367 1368 public: 1369 bool isIdentical(const PredicateMatcher &B) const override { return false; } 1370 1371 ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx, 1372 const OperandMatcher &Operand, 1373 const Record &TheDef) 1374 : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx), 1375 Operand(Operand), TheDef(TheDef) {} 1376 1377 static bool classof(const PredicateMatcher *P) { 1378 return P->getKind() == OPM_ComplexPattern; 1379 } 1380 1381 void emitPredicateOpcodes(MatchTable &Table, 1382 RuleMatcher &Rule) const override { 1383 unsigned ID = getAllocatedTemporariesBaseID(); 1384 Table << MatchTable::Opcode("GIM_CheckComplexPattern") 1385 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1386 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 1387 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID) 1388 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str()) 1389 << MatchTable::LineBreak; 1390 } 1391 1392 unsigned countRendererFns() const override { 1393 return 1; 1394 } 1395 }; 1396 1397 /// Generates code to check that an operand is in a particular register bank. 1398 class RegisterBankOperandMatcher : public OperandPredicateMatcher { 1399 protected: 1400 const CodeGenRegisterClass &RC; 1401 1402 public: 1403 RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx, 1404 const CodeGenRegisterClass &RC) 1405 : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {} 1406 1407 bool isIdentical(const PredicateMatcher &B) const override { 1408 return OperandPredicateMatcher::isIdentical(B) && 1409 RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef(); 1410 } 1411 1412 static bool classof(const PredicateMatcher *P) { 1413 return P->getKind() == OPM_RegBank; 1414 } 1415 1416 void emitPredicateOpcodes(MatchTable &Table, 1417 RuleMatcher &Rule) const override { 1418 Table << MatchTable::Opcode("GIM_CheckRegBankForClass") 1419 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1420 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 1421 << MatchTable::Comment("RC") 1422 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID") 1423 << MatchTable::LineBreak; 1424 } 1425 }; 1426 1427 /// Generates code to check that an operand is a basic block. 1428 class MBBOperandMatcher : public OperandPredicateMatcher { 1429 public: 1430 MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx) 1431 : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {} 1432 1433 static bool classof(const PredicateMatcher *P) { 1434 return P->getKind() == OPM_MBB; 1435 } 1436 1437 void emitPredicateOpcodes(MatchTable &Table, 1438 RuleMatcher &Rule) const override { 1439 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI") 1440 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op") 1441 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak; 1442 } 1443 }; 1444 1445 class ImmOperandMatcher : public OperandPredicateMatcher { 1446 public: 1447 ImmOperandMatcher(unsigned InsnVarID, unsigned OpIdx) 1448 : OperandPredicateMatcher(IPM_Imm, InsnVarID, OpIdx) {} 1449 1450 static bool classof(const PredicateMatcher *P) { 1451 return P->getKind() == IPM_Imm; 1452 } 1453 1454 void emitPredicateOpcodes(MatchTable &Table, 1455 RuleMatcher &Rule) const override { 1456 Table << MatchTable::Opcode("GIM_CheckIsImm") << MatchTable::Comment("MI") 1457 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op") 1458 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak; 1459 } 1460 }; 1461 1462 /// Generates code to check that an operand is a G_CONSTANT with a particular 1463 /// int. 1464 class ConstantIntOperandMatcher : public OperandPredicateMatcher { 1465 protected: 1466 int64_t Value; 1467 1468 public: 1469 ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value) 1470 : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {} 1471 1472 bool isIdentical(const PredicateMatcher &B) const override { 1473 return OperandPredicateMatcher::isIdentical(B) && 1474 Value == cast<ConstantIntOperandMatcher>(&B)->Value; 1475 } 1476 1477 static bool classof(const PredicateMatcher *P) { 1478 return P->getKind() == OPM_Int; 1479 } 1480 1481 void emitPredicateOpcodes(MatchTable &Table, 1482 RuleMatcher &Rule) const override { 1483 Table << MatchTable::Opcode("GIM_CheckConstantInt") 1484 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1485 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 1486 << MatchTable::IntValue(Value) << MatchTable::LineBreak; 1487 } 1488 }; 1489 1490 /// Generates code to check that an operand is a raw int (where MO.isImm() or 1491 /// MO.isCImm() is true). 1492 class LiteralIntOperandMatcher : public OperandPredicateMatcher { 1493 protected: 1494 int64_t Value; 1495 1496 public: 1497 LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value) 1498 : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx), 1499 Value(Value) {} 1500 1501 bool isIdentical(const PredicateMatcher &B) const override { 1502 return OperandPredicateMatcher::isIdentical(B) && 1503 Value == cast<LiteralIntOperandMatcher>(&B)->Value; 1504 } 1505 1506 static bool classof(const PredicateMatcher *P) { 1507 return P->getKind() == OPM_LiteralInt; 1508 } 1509 1510 void emitPredicateOpcodes(MatchTable &Table, 1511 RuleMatcher &Rule) const override { 1512 Table << MatchTable::Opcode("GIM_CheckLiteralInt") 1513 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1514 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 1515 << MatchTable::IntValue(Value) << MatchTable::LineBreak; 1516 } 1517 }; 1518 1519 /// Generates code to check that an operand is an CmpInst predicate 1520 class CmpPredicateOperandMatcher : public OperandPredicateMatcher { 1521 protected: 1522 std::string PredName; 1523 1524 public: 1525 CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx, 1526 std::string P) 1527 : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {} 1528 1529 bool isIdentical(const PredicateMatcher &B) const override { 1530 return OperandPredicateMatcher::isIdentical(B) && 1531 PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName; 1532 } 1533 1534 static bool classof(const PredicateMatcher *P) { 1535 return P->getKind() == OPM_CmpPredicate; 1536 } 1537 1538 void emitPredicateOpcodes(MatchTable &Table, 1539 RuleMatcher &Rule) const override { 1540 Table << MatchTable::Opcode("GIM_CheckCmpPredicate") 1541 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1542 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 1543 << MatchTable::Comment("Predicate") 1544 << MatchTable::NamedValue("CmpInst", PredName) 1545 << MatchTable::LineBreak; 1546 } 1547 }; 1548 1549 /// Generates code to check that an operand is an intrinsic ID. 1550 class IntrinsicIDOperandMatcher : public OperandPredicateMatcher { 1551 protected: 1552 const CodeGenIntrinsic *II; 1553 1554 public: 1555 IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx, 1556 const CodeGenIntrinsic *II) 1557 : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {} 1558 1559 bool isIdentical(const PredicateMatcher &B) const override { 1560 return OperandPredicateMatcher::isIdentical(B) && 1561 II == cast<IntrinsicIDOperandMatcher>(&B)->II; 1562 } 1563 1564 static bool classof(const PredicateMatcher *P) { 1565 return P->getKind() == OPM_IntrinsicID; 1566 } 1567 1568 void emitPredicateOpcodes(MatchTable &Table, 1569 RuleMatcher &Rule) const override { 1570 Table << MatchTable::Opcode("GIM_CheckIntrinsicID") 1571 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1572 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 1573 << MatchTable::NamedValue("Intrinsic::" + II->EnumName) 1574 << MatchTable::LineBreak; 1575 } 1576 }; 1577 1578 /// Generates code to check that this operand is an immediate whose value meets 1579 /// an immediate predicate. 1580 class OperandImmPredicateMatcher : public OperandPredicateMatcher { 1581 protected: 1582 TreePredicateFn Predicate; 1583 1584 public: 1585 OperandImmPredicateMatcher(unsigned InsnVarID, unsigned OpIdx, 1586 const TreePredicateFn &Predicate) 1587 : OperandPredicateMatcher(IPM_ImmPredicate, InsnVarID, OpIdx), 1588 Predicate(Predicate) {} 1589 1590 bool isIdentical(const PredicateMatcher &B) const override { 1591 return OperandPredicateMatcher::isIdentical(B) && 1592 Predicate.getOrigPatFragRecord() == 1593 cast<OperandImmPredicateMatcher>(&B) 1594 ->Predicate.getOrigPatFragRecord(); 1595 } 1596 1597 static bool classof(const PredicateMatcher *P) { 1598 return P->getKind() == IPM_ImmPredicate; 1599 } 1600 1601 void emitPredicateOpcodes(MatchTable &Table, 1602 RuleMatcher &Rule) const override { 1603 Table << MatchTable::Opcode("GIM_CheckImmOperandPredicate") 1604 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1605 << MatchTable::Comment("MO") << MatchTable::IntValue(OpIdx) 1606 << MatchTable::Comment("Predicate") 1607 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate)) 1608 << MatchTable::LineBreak; 1609 } 1610 }; 1611 1612 /// Generates code to check that a set of predicates match for a particular 1613 /// operand. 1614 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> { 1615 protected: 1616 InstructionMatcher &Insn; 1617 unsigned OpIdx; 1618 std::string SymbolicName; 1619 1620 /// The index of the first temporary variable allocated to this operand. The 1621 /// number of allocated temporaries can be found with 1622 /// countRendererFns(). 1623 unsigned AllocatedTemporariesBaseID; 1624 1625 public: 1626 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx, 1627 const std::string &SymbolicName, 1628 unsigned AllocatedTemporariesBaseID) 1629 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName), 1630 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {} 1631 1632 bool hasSymbolicName() const { return !SymbolicName.empty(); } 1633 StringRef getSymbolicName() const { return SymbolicName; } 1634 void setSymbolicName(StringRef Name) { 1635 assert(SymbolicName.empty() && "Operand already has a symbolic name"); 1636 SymbolicName = std::string(Name); 1637 } 1638 1639 /// Construct a new operand predicate and add it to the matcher. 1640 template <class Kind, class... Args> 1641 Optional<Kind *> addPredicate(Args &&... args) { 1642 if (isSameAsAnotherOperand()) 1643 return None; 1644 Predicates.emplace_back(std::make_unique<Kind>( 1645 getInsnVarID(), getOpIdx(), std::forward<Args>(args)...)); 1646 return static_cast<Kind *>(Predicates.back().get()); 1647 } 1648 1649 unsigned getOpIdx() const { return OpIdx; } 1650 unsigned getInsnVarID() const; 1651 1652 std::string getOperandExpr(unsigned InsnVarID) const { 1653 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" + 1654 llvm::to_string(OpIdx) + ")"; 1655 } 1656 1657 InstructionMatcher &getInstructionMatcher() const { return Insn; } 1658 1659 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy, 1660 bool OperandIsAPointer); 1661 1662 /// Emit MatchTable opcodes that test whether the instruction named in 1663 /// InsnVarID matches all the predicates and all the operands. 1664 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) { 1665 if (!Optimized) { 1666 std::string Comment; 1667 raw_string_ostream CommentOS(Comment); 1668 CommentOS << "MIs[" << getInsnVarID() << "] "; 1669 if (SymbolicName.empty()) 1670 CommentOS << "Operand " << OpIdx; 1671 else 1672 CommentOS << SymbolicName; 1673 Table << MatchTable::Comment(Comment) << MatchTable::LineBreak; 1674 } 1675 1676 emitPredicateListOpcodes(Table, Rule); 1677 } 1678 1679 /// Compare the priority of this object and B. 1680 /// 1681 /// Returns true if this object is more important than B. 1682 bool isHigherPriorityThan(OperandMatcher &B) { 1683 // Operand matchers involving more predicates have higher priority. 1684 if (predicates_size() > B.predicates_size()) 1685 return true; 1686 if (predicates_size() < B.predicates_size()) 1687 return false; 1688 1689 // This assumes that predicates are added in a consistent order. 1690 for (auto &&Predicate : zip(predicates(), B.predicates())) { 1691 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate))) 1692 return true; 1693 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate))) 1694 return false; 1695 } 1696 1697 return false; 1698 }; 1699 1700 /// Report the maximum number of temporary operands needed by the operand 1701 /// matcher. 1702 unsigned countRendererFns() { 1703 return std::accumulate( 1704 predicates().begin(), predicates().end(), 0, 1705 [](unsigned A, 1706 const std::unique_ptr<OperandPredicateMatcher> &Predicate) { 1707 return A + Predicate->countRendererFns(); 1708 }); 1709 } 1710 1711 unsigned getAllocatedTemporariesBaseID() const { 1712 return AllocatedTemporariesBaseID; 1713 } 1714 1715 bool isSameAsAnotherOperand() { 1716 for (const auto &Predicate : predicates()) 1717 if (isa<SameOperandMatcher>(Predicate)) 1718 return true; 1719 return false; 1720 } 1721 }; 1722 1723 Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy, 1724 bool OperandIsAPointer) { 1725 if (!VTy.isMachineValueType()) 1726 return failedImport("unsupported typeset"); 1727 1728 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) { 1729 addPredicate<PointerToAnyOperandMatcher>(0); 1730 return Error::success(); 1731 } 1732 1733 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy); 1734 if (!OpTyOrNone) 1735 return failedImport("unsupported type"); 1736 1737 if (OperandIsAPointer) 1738 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits()); 1739 else if (VTy.isPointer()) 1740 addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(), 1741 OpTyOrNone->get().getSizeInBits())); 1742 else 1743 addPredicate<LLTOperandMatcher>(*OpTyOrNone); 1744 return Error::success(); 1745 } 1746 1747 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const { 1748 return Operand.getAllocatedTemporariesBaseID(); 1749 } 1750 1751 /// Generates code to check a predicate on an instruction. 1752 /// 1753 /// Typical predicates include: 1754 /// * The opcode of the instruction is a particular value. 1755 /// * The nsw/nuw flag is/isn't set. 1756 class InstructionPredicateMatcher : public PredicateMatcher { 1757 public: 1758 InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID) 1759 : PredicateMatcher(Kind, InsnVarID) {} 1760 virtual ~InstructionPredicateMatcher() {} 1761 1762 /// Compare the priority of this object and B. 1763 /// 1764 /// Returns true if this object is more important than B. 1765 virtual bool 1766 isHigherPriorityThan(const InstructionPredicateMatcher &B) const { 1767 return Kind < B.Kind; 1768 }; 1769 }; 1770 1771 template <> 1772 std::string 1773 PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const { 1774 return "No instruction predicates"; 1775 } 1776 1777 /// Generates code to check the opcode of an instruction. 1778 class InstructionOpcodeMatcher : public InstructionPredicateMatcher { 1779 protected: 1780 // Allow matching one to several, similar opcodes that share properties. This 1781 // is to handle patterns where one SelectionDAG operation maps to multiple 1782 // GlobalISel ones (e.g. G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC). The first 1783 // is treated as the canonical opcode. 1784 SmallVector<const CodeGenInstruction *, 2> Insts; 1785 1786 static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues; 1787 1788 1789 MatchTableRecord getInstValue(const CodeGenInstruction *I) const { 1790 const auto VI = OpcodeValues.find(I); 1791 if (VI != OpcodeValues.end()) 1792 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(), 1793 VI->second); 1794 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName()); 1795 } 1796 1797 public: 1798 static void initOpcodeValuesMap(const CodeGenTarget &Target) { 1799 OpcodeValues.clear(); 1800 1801 unsigned OpcodeValue = 0; 1802 for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue()) 1803 OpcodeValues[I] = OpcodeValue++; 1804 } 1805 1806 InstructionOpcodeMatcher(unsigned InsnVarID, 1807 ArrayRef<const CodeGenInstruction *> I) 1808 : InstructionPredicateMatcher(IPM_Opcode, InsnVarID), 1809 Insts(I.begin(), I.end()) { 1810 assert((Insts.size() == 1 || Insts.size() == 2) && 1811 "unexpected number of opcode alternatives"); 1812 } 1813 1814 static bool classof(const PredicateMatcher *P) { 1815 return P->getKind() == IPM_Opcode; 1816 } 1817 1818 bool isIdentical(const PredicateMatcher &B) const override { 1819 return InstructionPredicateMatcher::isIdentical(B) && 1820 Insts == cast<InstructionOpcodeMatcher>(&B)->Insts; 1821 } 1822 1823 bool hasValue() const override { 1824 return Insts.size() == 1 && OpcodeValues.count(Insts[0]); 1825 } 1826 1827 // TODO: This is used for the SwitchMatcher optimization. We should be able to 1828 // return a list of the opcodes to match. 1829 MatchTableRecord getValue() const override { 1830 assert(Insts.size() == 1); 1831 1832 const CodeGenInstruction *I = Insts[0]; 1833 const auto VI = OpcodeValues.find(I); 1834 if (VI != OpcodeValues.end()) 1835 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(), 1836 VI->second); 1837 return MatchTable::NamedValue(I->Namespace, I->TheDef->getName()); 1838 } 1839 1840 void emitPredicateOpcodes(MatchTable &Table, 1841 RuleMatcher &Rule) const override { 1842 StringRef CheckType = Insts.size() == 1 ? 1843 "GIM_CheckOpcode" : "GIM_CheckOpcodeIsEither"; 1844 Table << MatchTable::Opcode(CheckType) << MatchTable::Comment("MI") 1845 << MatchTable::IntValue(InsnVarID); 1846 1847 for (const CodeGenInstruction *I : Insts) 1848 Table << getInstValue(I); 1849 Table << MatchTable::LineBreak; 1850 } 1851 1852 /// Compare the priority of this object and B. 1853 /// 1854 /// Returns true if this object is more important than B. 1855 bool 1856 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override { 1857 if (InstructionPredicateMatcher::isHigherPriorityThan(B)) 1858 return true; 1859 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this)) 1860 return false; 1861 1862 // Prioritize opcodes for cosmetic reasons in the generated source. Although 1863 // this is cosmetic at the moment, we may want to drive a similar ordering 1864 // using instruction frequency information to improve compile time. 1865 if (const InstructionOpcodeMatcher *BO = 1866 dyn_cast<InstructionOpcodeMatcher>(&B)) 1867 return Insts[0]->TheDef->getName() < BO->Insts[0]->TheDef->getName(); 1868 1869 return false; 1870 }; 1871 1872 bool isConstantInstruction() const { 1873 return Insts.size() == 1 && Insts[0]->TheDef->getName() == "G_CONSTANT"; 1874 } 1875 1876 // The first opcode is the canonical opcode, and later are alternatives. 1877 StringRef getOpcode() const { 1878 return Insts[0]->TheDef->getName(); 1879 } 1880 1881 ArrayRef<const CodeGenInstruction *> getAlternativeOpcodes() { 1882 return Insts; 1883 } 1884 1885 bool isVariadicNumOperands() const { 1886 // If one is variadic, they all should be. 1887 return Insts[0]->Operands.isVariadic; 1888 } 1889 1890 StringRef getOperandType(unsigned OpIdx) const { 1891 // Types expected to be uniform for all alternatives. 1892 return Insts[0]->Operands[OpIdx].OperandType; 1893 } 1894 }; 1895 1896 DenseMap<const CodeGenInstruction *, unsigned> 1897 InstructionOpcodeMatcher::OpcodeValues; 1898 1899 class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher { 1900 unsigned NumOperands = 0; 1901 1902 public: 1903 InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands) 1904 : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID), 1905 NumOperands(NumOperands) {} 1906 1907 static bool classof(const PredicateMatcher *P) { 1908 return P->getKind() == IPM_NumOperands; 1909 } 1910 1911 bool isIdentical(const PredicateMatcher &B) const override { 1912 return InstructionPredicateMatcher::isIdentical(B) && 1913 NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands; 1914 } 1915 1916 void emitPredicateOpcodes(MatchTable &Table, 1917 RuleMatcher &Rule) const override { 1918 Table << MatchTable::Opcode("GIM_CheckNumOperands") 1919 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1920 << MatchTable::Comment("Expected") 1921 << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak; 1922 } 1923 }; 1924 1925 /// Generates code to check that this instruction is a constant whose value 1926 /// meets an immediate predicate. 1927 /// 1928 /// Immediates are slightly odd since they are typically used like an operand 1929 /// but are represented as an operator internally. We typically write simm8:$src 1930 /// in a tablegen pattern, but this is just syntactic sugar for 1931 /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes 1932 /// that will be matched and the predicate (which is attached to the imm 1933 /// operator) that will be tested. In SelectionDAG this describes a 1934 /// ConstantSDNode whose internal value will be tested using the simm8 predicate. 1935 /// 1936 /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In 1937 /// this representation, the immediate could be tested with an 1938 /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a 1939 /// OperandPredicateMatcher-subclass to check the Value meets the predicate but 1940 /// there are two implementation issues with producing that matcher 1941 /// configuration from the SelectionDAG pattern: 1942 /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that 1943 /// were we to sink the immediate predicate to the operand we would have to 1944 /// have two partial implementations of PatFrag support, one for immediates 1945 /// and one for non-immediates. 1946 /// * At the point we handle the predicate, the OperandMatcher hasn't been 1947 /// created yet. If we were to sink the predicate to the OperandMatcher we 1948 /// would also have to complicate (or duplicate) the code that descends and 1949 /// creates matchers for the subtree. 1950 /// Overall, it's simpler to handle it in the place it was found. 1951 class InstructionImmPredicateMatcher : public InstructionPredicateMatcher { 1952 protected: 1953 TreePredicateFn Predicate; 1954 1955 public: 1956 InstructionImmPredicateMatcher(unsigned InsnVarID, 1957 const TreePredicateFn &Predicate) 1958 : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID), 1959 Predicate(Predicate) {} 1960 1961 bool isIdentical(const PredicateMatcher &B) const override { 1962 return InstructionPredicateMatcher::isIdentical(B) && 1963 Predicate.getOrigPatFragRecord() == 1964 cast<InstructionImmPredicateMatcher>(&B) 1965 ->Predicate.getOrigPatFragRecord(); 1966 } 1967 1968 static bool classof(const PredicateMatcher *P) { 1969 return P->getKind() == IPM_ImmPredicate; 1970 } 1971 1972 void emitPredicateOpcodes(MatchTable &Table, 1973 RuleMatcher &Rule) const override { 1974 Table << MatchTable::Opcode(getMatchOpcodeForImmPredicate(Predicate)) 1975 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1976 << MatchTable::Comment("Predicate") 1977 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate)) 1978 << MatchTable::LineBreak; 1979 } 1980 }; 1981 1982 /// Generates code to check that a memory instruction has a atomic ordering 1983 /// MachineMemoryOperand. 1984 class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher { 1985 public: 1986 enum AOComparator { 1987 AO_Exactly, 1988 AO_OrStronger, 1989 AO_WeakerThan, 1990 }; 1991 1992 protected: 1993 StringRef Order; 1994 AOComparator Comparator; 1995 1996 public: 1997 AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order, 1998 AOComparator Comparator = AO_Exactly) 1999 : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID), 2000 Order(Order), Comparator(Comparator) {} 2001 2002 static bool classof(const PredicateMatcher *P) { 2003 return P->getKind() == IPM_AtomicOrderingMMO; 2004 } 2005 2006 bool isIdentical(const PredicateMatcher &B) const override { 2007 if (!InstructionPredicateMatcher::isIdentical(B)) 2008 return false; 2009 const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B); 2010 return Order == R.Order && Comparator == R.Comparator; 2011 } 2012 2013 void emitPredicateOpcodes(MatchTable &Table, 2014 RuleMatcher &Rule) const override { 2015 StringRef Opcode = "GIM_CheckAtomicOrdering"; 2016 2017 if (Comparator == AO_OrStronger) 2018 Opcode = "GIM_CheckAtomicOrderingOrStrongerThan"; 2019 if (Comparator == AO_WeakerThan) 2020 Opcode = "GIM_CheckAtomicOrderingWeakerThan"; 2021 2022 Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI") 2023 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order") 2024 << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str()) 2025 << MatchTable::LineBreak; 2026 } 2027 }; 2028 2029 /// Generates code to check that the size of an MMO is exactly N bytes. 2030 class MemorySizePredicateMatcher : public InstructionPredicateMatcher { 2031 protected: 2032 unsigned MMOIdx; 2033 uint64_t Size; 2034 2035 public: 2036 MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size) 2037 : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID), 2038 MMOIdx(MMOIdx), Size(Size) {} 2039 2040 static bool classof(const PredicateMatcher *P) { 2041 return P->getKind() == IPM_MemoryLLTSize; 2042 } 2043 bool isIdentical(const PredicateMatcher &B) const override { 2044 return InstructionPredicateMatcher::isIdentical(B) && 2045 MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx && 2046 Size == cast<MemorySizePredicateMatcher>(&B)->Size; 2047 } 2048 2049 void emitPredicateOpcodes(MatchTable &Table, 2050 RuleMatcher &Rule) const override { 2051 Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo") 2052 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 2053 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx) 2054 << MatchTable::Comment("Size") << MatchTable::IntValue(Size) 2055 << MatchTable::LineBreak; 2056 } 2057 }; 2058 2059 class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher { 2060 protected: 2061 unsigned MMOIdx; 2062 SmallVector<unsigned, 4> AddrSpaces; 2063 2064 public: 2065 MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, 2066 ArrayRef<unsigned> AddrSpaces) 2067 : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID), 2068 MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {} 2069 2070 static bool classof(const PredicateMatcher *P) { 2071 return P->getKind() == IPM_MemoryAddressSpace; 2072 } 2073 bool isIdentical(const PredicateMatcher &B) const override { 2074 if (!InstructionPredicateMatcher::isIdentical(B)) 2075 return false; 2076 auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B); 2077 return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces; 2078 } 2079 2080 void emitPredicateOpcodes(MatchTable &Table, 2081 RuleMatcher &Rule) const override { 2082 Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace") 2083 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 2084 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx) 2085 // Encode number of address spaces to expect. 2086 << MatchTable::Comment("NumAddrSpace") 2087 << MatchTable::IntValue(AddrSpaces.size()); 2088 for (unsigned AS : AddrSpaces) 2089 Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS); 2090 2091 Table << MatchTable::LineBreak; 2092 } 2093 }; 2094 2095 class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher { 2096 protected: 2097 unsigned MMOIdx; 2098 int MinAlign; 2099 2100 public: 2101 MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, 2102 int MinAlign) 2103 : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID), 2104 MMOIdx(MMOIdx), MinAlign(MinAlign) { 2105 assert(MinAlign > 0); 2106 } 2107 2108 static bool classof(const PredicateMatcher *P) { 2109 return P->getKind() == IPM_MemoryAlignment; 2110 } 2111 2112 bool isIdentical(const PredicateMatcher &B) const override { 2113 if (!InstructionPredicateMatcher::isIdentical(B)) 2114 return false; 2115 auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B); 2116 return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign; 2117 } 2118 2119 void emitPredicateOpcodes(MatchTable &Table, 2120 RuleMatcher &Rule) const override { 2121 Table << MatchTable::Opcode("GIM_CheckMemoryAlignment") 2122 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 2123 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx) 2124 << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign) 2125 << MatchTable::LineBreak; 2126 } 2127 }; 2128 2129 /// Generates code to check that the size of an MMO is less-than, equal-to, or 2130 /// greater than a given LLT. 2131 class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher { 2132 public: 2133 enum RelationKind { 2134 GreaterThan, 2135 EqualTo, 2136 LessThan, 2137 }; 2138 2139 protected: 2140 unsigned MMOIdx; 2141 RelationKind Relation; 2142 unsigned OpIdx; 2143 2144 public: 2145 MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, 2146 enum RelationKind Relation, 2147 unsigned OpIdx) 2148 : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID), 2149 MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {} 2150 2151 static bool classof(const PredicateMatcher *P) { 2152 return P->getKind() == IPM_MemoryVsLLTSize; 2153 } 2154 bool isIdentical(const PredicateMatcher &B) const override { 2155 return InstructionPredicateMatcher::isIdentical(B) && 2156 MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx && 2157 Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation && 2158 OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx; 2159 } 2160 2161 void emitPredicateOpcodes(MatchTable &Table, 2162 RuleMatcher &Rule) const override { 2163 Table << MatchTable::Opcode(Relation == EqualTo 2164 ? "GIM_CheckMemorySizeEqualToLLT" 2165 : Relation == GreaterThan 2166 ? "GIM_CheckMemorySizeGreaterThanLLT" 2167 : "GIM_CheckMemorySizeLessThanLLT") 2168 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 2169 << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx) 2170 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx) 2171 << MatchTable::LineBreak; 2172 } 2173 }; 2174 2175 // Matcher for immAllOnesV/immAllZerosV 2176 class VectorSplatImmPredicateMatcher : public InstructionPredicateMatcher { 2177 public: 2178 enum SplatKind { 2179 AllZeros, 2180 AllOnes 2181 }; 2182 2183 private: 2184 SplatKind Kind; 2185 2186 public: 2187 VectorSplatImmPredicateMatcher(unsigned InsnVarID, SplatKind K) 2188 : InstructionPredicateMatcher(IPM_VectorSplatImm, InsnVarID), Kind(K) {} 2189 2190 static bool classof(const PredicateMatcher *P) { 2191 return P->getKind() == IPM_VectorSplatImm; 2192 } 2193 2194 bool isIdentical(const PredicateMatcher &B) const override { 2195 return InstructionPredicateMatcher::isIdentical(B) && 2196 Kind == static_cast<const VectorSplatImmPredicateMatcher &>(B).Kind; 2197 } 2198 2199 void emitPredicateOpcodes(MatchTable &Table, 2200 RuleMatcher &Rule) const override { 2201 if (Kind == AllOnes) 2202 Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllOnes"); 2203 else 2204 Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllZeros"); 2205 2206 Table << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID); 2207 Table << MatchTable::LineBreak; 2208 } 2209 }; 2210 2211 /// Generates code to check an arbitrary C++ instruction predicate. 2212 class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher { 2213 protected: 2214 TreePredicateFn Predicate; 2215 2216 public: 2217 GenericInstructionPredicateMatcher(unsigned InsnVarID, 2218 TreePredicateFn Predicate) 2219 : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID), 2220 Predicate(Predicate) {} 2221 2222 static bool classof(const InstructionPredicateMatcher *P) { 2223 return P->getKind() == IPM_GenericPredicate; 2224 } 2225 bool isIdentical(const PredicateMatcher &B) const override { 2226 return InstructionPredicateMatcher::isIdentical(B) && 2227 Predicate == 2228 static_cast<const GenericInstructionPredicateMatcher &>(B) 2229 .Predicate; 2230 } 2231 void emitPredicateOpcodes(MatchTable &Table, 2232 RuleMatcher &Rule) const override { 2233 Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate") 2234 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 2235 << MatchTable::Comment("FnId") 2236 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate)) 2237 << MatchTable::LineBreak; 2238 } 2239 }; 2240 2241 /// Generates code to check that a set of predicates and operands match for a 2242 /// particular instruction. 2243 /// 2244 /// Typical predicates include: 2245 /// * Has a specific opcode. 2246 /// * Has an nsw/nuw flag or doesn't. 2247 class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> { 2248 protected: 2249 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec; 2250 2251 RuleMatcher &Rule; 2252 2253 /// The operands to match. All rendered operands must be present even if the 2254 /// condition is always true. 2255 OperandVec Operands; 2256 bool NumOperandsCheck = true; 2257 2258 std::string SymbolicName; 2259 unsigned InsnVarID; 2260 2261 /// PhysRegInputs - List list has an entry for each explicitly specified 2262 /// physreg input to the pattern. The first elt is the Register node, the 2263 /// second is the recorded slot number the input pattern match saved it in. 2264 SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs; 2265 2266 public: 2267 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName, 2268 bool NumOpsCheck = true) 2269 : Rule(Rule), NumOperandsCheck(NumOpsCheck), SymbolicName(SymbolicName) { 2270 // We create a new instruction matcher. 2271 // Get a new ID for that instruction. 2272 InsnVarID = Rule.implicitlyDefineInsnVar(*this); 2273 } 2274 2275 /// Construct a new instruction predicate and add it to the matcher. 2276 template <class Kind, class... Args> 2277 Optional<Kind *> addPredicate(Args &&... args) { 2278 Predicates.emplace_back( 2279 std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...)); 2280 return static_cast<Kind *>(Predicates.back().get()); 2281 } 2282 2283 RuleMatcher &getRuleMatcher() const { return Rule; } 2284 2285 unsigned getInsnVarID() const { return InsnVarID; } 2286 2287 /// Add an operand to the matcher. 2288 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName, 2289 unsigned AllocatedTemporariesBaseID) { 2290 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName, 2291 AllocatedTemporariesBaseID)); 2292 if (!SymbolicName.empty()) 2293 Rule.defineOperand(SymbolicName, *Operands.back()); 2294 2295 return *Operands.back(); 2296 } 2297 2298 OperandMatcher &getOperand(unsigned OpIdx) { 2299 auto I = llvm::find_if(Operands, 2300 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) { 2301 return X->getOpIdx() == OpIdx; 2302 }); 2303 if (I != Operands.end()) 2304 return **I; 2305 llvm_unreachable("Failed to lookup operand"); 2306 } 2307 2308 OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx, 2309 unsigned TempOpIdx) { 2310 assert(SymbolicName.empty()); 2311 OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx); 2312 Operands.emplace_back(OM); 2313 Rule.definePhysRegOperand(Reg, *OM); 2314 PhysRegInputs.emplace_back(Reg, OpIdx); 2315 return *OM; 2316 } 2317 2318 ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const { 2319 return PhysRegInputs; 2320 } 2321 2322 StringRef getSymbolicName() const { return SymbolicName; } 2323 unsigned getNumOperands() const { return Operands.size(); } 2324 OperandVec::iterator operands_begin() { return Operands.begin(); } 2325 OperandVec::iterator operands_end() { return Operands.end(); } 2326 iterator_range<OperandVec::iterator> operands() { 2327 return make_range(operands_begin(), operands_end()); 2328 } 2329 OperandVec::const_iterator operands_begin() const { return Operands.begin(); } 2330 OperandVec::const_iterator operands_end() const { return Operands.end(); } 2331 iterator_range<OperandVec::const_iterator> operands() const { 2332 return make_range(operands_begin(), operands_end()); 2333 } 2334 bool operands_empty() const { return Operands.empty(); } 2335 2336 void pop_front() { Operands.erase(Operands.begin()); } 2337 2338 void optimize(); 2339 2340 /// Emit MatchTable opcodes that test whether the instruction named in 2341 /// InsnVarName matches all the predicates and all the operands. 2342 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) { 2343 if (NumOperandsCheck) 2344 InstructionNumOperandsMatcher(InsnVarID, getNumOperands()) 2345 .emitPredicateOpcodes(Table, Rule); 2346 2347 // First emit all instruction level predicates need to be verified before we 2348 // can verify operands. 2349 emitFilteredPredicateListOpcodes( 2350 [](const PredicateMatcher &P) { 2351 return !P.dependsOnOperands(); 2352 }, Table, Rule); 2353 2354 // Emit all operand constraints. 2355 for (const auto &Operand : Operands) 2356 Operand->emitPredicateOpcodes(Table, Rule); 2357 2358 // All of the tablegen defined predicates should now be matched. Now emit 2359 // any custom predicates that rely on all generated checks. 2360 emitFilteredPredicateListOpcodes( 2361 [](const PredicateMatcher &P) { 2362 return P.dependsOnOperands(); 2363 }, Table, Rule); 2364 } 2365 2366 /// Compare the priority of this object and B. 2367 /// 2368 /// Returns true if this object is more important than B. 2369 bool isHigherPriorityThan(InstructionMatcher &B) { 2370 // Instruction matchers involving more operands have higher priority. 2371 if (Operands.size() > B.Operands.size()) 2372 return true; 2373 if (Operands.size() < B.Operands.size()) 2374 return false; 2375 2376 for (auto &&P : zip(predicates(), B.predicates())) { 2377 auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get()); 2378 auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get()); 2379 if (L->isHigherPriorityThan(*R)) 2380 return true; 2381 if (R->isHigherPriorityThan(*L)) 2382 return false; 2383 } 2384 2385 for (auto Operand : zip(Operands, B.Operands)) { 2386 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand))) 2387 return true; 2388 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand))) 2389 return false; 2390 } 2391 2392 return false; 2393 }; 2394 2395 /// Report the maximum number of temporary operands needed by the instruction 2396 /// matcher. 2397 unsigned countRendererFns() { 2398 return std::accumulate( 2399 predicates().begin(), predicates().end(), 0, 2400 [](unsigned A, 2401 const std::unique_ptr<PredicateMatcher> &Predicate) { 2402 return A + Predicate->countRendererFns(); 2403 }) + 2404 std::accumulate( 2405 Operands.begin(), Operands.end(), 0, 2406 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) { 2407 return A + Operand->countRendererFns(); 2408 }); 2409 } 2410 2411 InstructionOpcodeMatcher &getOpcodeMatcher() { 2412 for (auto &P : predicates()) 2413 if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get())) 2414 return *OpMatcher; 2415 llvm_unreachable("Didn't find an opcode matcher"); 2416 } 2417 2418 bool isConstantInstruction() { 2419 return getOpcodeMatcher().isConstantInstruction(); 2420 } 2421 2422 StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); } 2423 }; 2424 2425 StringRef RuleMatcher::getOpcode() const { 2426 return Matchers.front()->getOpcode(); 2427 } 2428 2429 unsigned RuleMatcher::getNumOperands() const { 2430 return Matchers.front()->getNumOperands(); 2431 } 2432 2433 LLTCodeGen RuleMatcher::getFirstConditionAsRootType() { 2434 InstructionMatcher &InsnMatcher = *Matchers.front(); 2435 if (!InsnMatcher.predicates_empty()) 2436 if (const auto *TM = 2437 dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin())) 2438 if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0) 2439 return TM->getTy(); 2440 return {}; 2441 } 2442 2443 /// Generates code to check that the operand is a register defined by an 2444 /// instruction that matches the given instruction matcher. 2445 /// 2446 /// For example, the pattern: 2447 /// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3)) 2448 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match 2449 /// the: 2450 /// (G_ADD $src1, $src2) 2451 /// subpattern. 2452 class InstructionOperandMatcher : public OperandPredicateMatcher { 2453 protected: 2454 std::unique_ptr<InstructionMatcher> InsnMatcher; 2455 2456 public: 2457 InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx, 2458 RuleMatcher &Rule, StringRef SymbolicName, 2459 bool NumOpsCheck = true) 2460 : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx), 2461 InsnMatcher(new InstructionMatcher(Rule, SymbolicName, NumOpsCheck)) {} 2462 2463 static bool classof(const PredicateMatcher *P) { 2464 return P->getKind() == OPM_Instruction; 2465 } 2466 2467 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; } 2468 2469 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const { 2470 const unsigned NewInsnVarID = InsnMatcher->getInsnVarID(); 2471 Table << MatchTable::Opcode("GIM_RecordInsn") 2472 << MatchTable::Comment("DefineMI") 2473 << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI") 2474 << MatchTable::IntValue(getInsnVarID()) 2475 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx()) 2476 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]") 2477 << MatchTable::LineBreak; 2478 } 2479 2480 void emitPredicateOpcodes(MatchTable &Table, 2481 RuleMatcher &Rule) const override { 2482 emitCaptureOpcodes(Table, Rule); 2483 InsnMatcher->emitPredicateOpcodes(Table, Rule); 2484 } 2485 2486 bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override { 2487 if (OperandPredicateMatcher::isHigherPriorityThan(B)) 2488 return true; 2489 if (B.OperandPredicateMatcher::isHigherPriorityThan(*this)) 2490 return false; 2491 2492 if (const InstructionOperandMatcher *BP = 2493 dyn_cast<InstructionOperandMatcher>(&B)) 2494 if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher)) 2495 return true; 2496 return false; 2497 } 2498 }; 2499 2500 void InstructionMatcher::optimize() { 2501 SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash; 2502 const auto &OpcMatcher = getOpcodeMatcher(); 2503 2504 Stash.push_back(predicates_pop_front()); 2505 if (Stash.back().get() == &OpcMatcher) { 2506 if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands()) 2507 Stash.emplace_back( 2508 new InstructionNumOperandsMatcher(InsnVarID, getNumOperands())); 2509 NumOperandsCheck = false; 2510 2511 for (auto &OM : Operands) 2512 for (auto &OP : OM->predicates()) 2513 if (isa<IntrinsicIDOperandMatcher>(OP)) { 2514 Stash.push_back(std::move(OP)); 2515 OM->eraseNullPredicates(); 2516 break; 2517 } 2518 } 2519 2520 if (InsnVarID > 0) { 2521 assert(!Operands.empty() && "Nested instruction is expected to def a vreg"); 2522 for (auto &OP : Operands[0]->predicates()) 2523 OP.reset(); 2524 Operands[0]->eraseNullPredicates(); 2525 } 2526 for (auto &OM : Operands) { 2527 for (auto &OP : OM->predicates()) 2528 if (isa<LLTOperandMatcher>(OP)) 2529 Stash.push_back(std::move(OP)); 2530 OM->eraseNullPredicates(); 2531 } 2532 while (!Stash.empty()) 2533 prependPredicate(Stash.pop_back_val()); 2534 } 2535 2536 //===- Actions ------------------------------------------------------------===// 2537 class OperandRenderer { 2538 public: 2539 enum RendererKind { 2540 OR_Copy, 2541 OR_CopyOrAddZeroReg, 2542 OR_CopySubReg, 2543 OR_CopyPhysReg, 2544 OR_CopyConstantAsImm, 2545 OR_CopyFConstantAsFPImm, 2546 OR_Imm, 2547 OR_SubRegIndex, 2548 OR_Register, 2549 OR_TempRegister, 2550 OR_ComplexPattern, 2551 OR_Custom, 2552 OR_CustomOperand 2553 }; 2554 2555 protected: 2556 RendererKind Kind; 2557 2558 public: 2559 OperandRenderer(RendererKind Kind) : Kind(Kind) {} 2560 virtual ~OperandRenderer() {} 2561 2562 RendererKind getKind() const { return Kind; } 2563 2564 virtual void emitRenderOpcodes(MatchTable &Table, 2565 RuleMatcher &Rule) const = 0; 2566 }; 2567 2568 /// A CopyRenderer emits code to copy a single operand from an existing 2569 /// instruction to the one being built. 2570 class CopyRenderer : public OperandRenderer { 2571 protected: 2572 unsigned NewInsnID; 2573 /// The name of the operand. 2574 const StringRef SymbolicName; 2575 2576 public: 2577 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName) 2578 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), 2579 SymbolicName(SymbolicName) { 2580 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source"); 2581 } 2582 2583 static bool classof(const OperandRenderer *R) { 2584 return R->getKind() == OR_Copy; 2585 } 2586 2587 StringRef getSymbolicName() const { return SymbolicName; } 2588 2589 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2590 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName); 2591 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); 2592 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID") 2593 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID") 2594 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx") 2595 << MatchTable::IntValue(Operand.getOpIdx()) 2596 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 2597 } 2598 }; 2599 2600 /// A CopyRenderer emits code to copy a virtual register to a specific physical 2601 /// register. 2602 class CopyPhysRegRenderer : public OperandRenderer { 2603 protected: 2604 unsigned NewInsnID; 2605 Record *PhysReg; 2606 2607 public: 2608 CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg) 2609 : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID), 2610 PhysReg(Reg) { 2611 assert(PhysReg); 2612 } 2613 2614 static bool classof(const OperandRenderer *R) { 2615 return R->getKind() == OR_CopyPhysReg; 2616 } 2617 2618 Record *getPhysReg() const { return PhysReg; } 2619 2620 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2621 const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg); 2622 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); 2623 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID") 2624 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID") 2625 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx") 2626 << MatchTable::IntValue(Operand.getOpIdx()) 2627 << MatchTable::Comment(PhysReg->getName()) 2628 << MatchTable::LineBreak; 2629 } 2630 }; 2631 2632 /// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an 2633 /// existing instruction to the one being built. If the operand turns out to be 2634 /// a 'G_CONSTANT 0' then it replaces the operand with a zero register. 2635 class CopyOrAddZeroRegRenderer : public OperandRenderer { 2636 protected: 2637 unsigned NewInsnID; 2638 /// The name of the operand. 2639 const StringRef SymbolicName; 2640 const Record *ZeroRegisterDef; 2641 2642 public: 2643 CopyOrAddZeroRegRenderer(unsigned NewInsnID, 2644 StringRef SymbolicName, Record *ZeroRegisterDef) 2645 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID), 2646 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) { 2647 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source"); 2648 } 2649 2650 static bool classof(const OperandRenderer *R) { 2651 return R->getKind() == OR_CopyOrAddZeroReg; 2652 } 2653 2654 StringRef getSymbolicName() const { return SymbolicName; } 2655 2656 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2657 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName); 2658 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); 2659 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg") 2660 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID) 2661 << MatchTable::Comment("OldInsnID") 2662 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx") 2663 << MatchTable::IntValue(Operand.getOpIdx()) 2664 << MatchTable::NamedValue( 2665 (ZeroRegisterDef->getValue("Namespace") 2666 ? ZeroRegisterDef->getValueAsString("Namespace") 2667 : ""), 2668 ZeroRegisterDef->getName()) 2669 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 2670 } 2671 }; 2672 2673 /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to 2674 /// an extended immediate operand. 2675 class CopyConstantAsImmRenderer : public OperandRenderer { 2676 protected: 2677 unsigned NewInsnID; 2678 /// The name of the operand. 2679 const std::string SymbolicName; 2680 bool Signed; 2681 2682 public: 2683 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName) 2684 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID), 2685 SymbolicName(SymbolicName), Signed(true) {} 2686 2687 static bool classof(const OperandRenderer *R) { 2688 return R->getKind() == OR_CopyConstantAsImm; 2689 } 2690 2691 StringRef getSymbolicName() const { return SymbolicName; } 2692 2693 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2694 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName); 2695 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher); 2696 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm" 2697 : "GIR_CopyConstantAsUImm") 2698 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID) 2699 << MatchTable::Comment("OldInsnID") 2700 << MatchTable::IntValue(OldInsnVarID) 2701 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 2702 } 2703 }; 2704 2705 /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT 2706 /// instruction to an extended immediate operand. 2707 class CopyFConstantAsFPImmRenderer : public OperandRenderer { 2708 protected: 2709 unsigned NewInsnID; 2710 /// The name of the operand. 2711 const std::string SymbolicName; 2712 2713 public: 2714 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName) 2715 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID), 2716 SymbolicName(SymbolicName) {} 2717 2718 static bool classof(const OperandRenderer *R) { 2719 return R->getKind() == OR_CopyFConstantAsFPImm; 2720 } 2721 2722 StringRef getSymbolicName() const { return SymbolicName; } 2723 2724 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2725 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName); 2726 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher); 2727 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm") 2728 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID) 2729 << MatchTable::Comment("OldInsnID") 2730 << MatchTable::IntValue(OldInsnVarID) 2731 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 2732 } 2733 }; 2734 2735 /// A CopySubRegRenderer emits code to copy a single register operand from an 2736 /// existing instruction to the one being built and indicate that only a 2737 /// subregister should be copied. 2738 class CopySubRegRenderer : public OperandRenderer { 2739 protected: 2740 unsigned NewInsnID; 2741 /// The name of the operand. 2742 const StringRef SymbolicName; 2743 /// The subregister to extract. 2744 const CodeGenSubRegIndex *SubReg; 2745 2746 public: 2747 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName, 2748 const CodeGenSubRegIndex *SubReg) 2749 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), 2750 SymbolicName(SymbolicName), SubReg(SubReg) {} 2751 2752 static bool classof(const OperandRenderer *R) { 2753 return R->getKind() == OR_CopySubReg; 2754 } 2755 2756 StringRef getSymbolicName() const { return SymbolicName; } 2757 2758 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2759 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName); 2760 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); 2761 Table << MatchTable::Opcode("GIR_CopySubReg") 2762 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID) 2763 << MatchTable::Comment("OldInsnID") 2764 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx") 2765 << MatchTable::IntValue(Operand.getOpIdx()) 2766 << MatchTable::Comment("SubRegIdx") 2767 << MatchTable::IntValue(SubReg->EnumValue) 2768 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 2769 } 2770 }; 2771 2772 /// Adds a specific physical register to the instruction being built. 2773 /// This is typically useful for WZR/XZR on AArch64. 2774 class AddRegisterRenderer : public OperandRenderer { 2775 protected: 2776 unsigned InsnID; 2777 const Record *RegisterDef; 2778 bool IsDef; 2779 const CodeGenTarget &Target; 2780 2781 public: 2782 AddRegisterRenderer(unsigned InsnID, const CodeGenTarget &Target, 2783 const Record *RegisterDef, bool IsDef = false) 2784 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef), 2785 IsDef(IsDef), Target(Target) {} 2786 2787 static bool classof(const OperandRenderer *R) { 2788 return R->getKind() == OR_Register; 2789 } 2790 2791 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2792 Table << MatchTable::Opcode("GIR_AddRegister") 2793 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID); 2794 if (RegisterDef->getName() != "zero_reg") { 2795 Table << MatchTable::NamedValue( 2796 (RegisterDef->getValue("Namespace") 2797 ? RegisterDef->getValueAsString("Namespace") 2798 : ""), 2799 RegisterDef->getName()); 2800 } else { 2801 Table << MatchTable::NamedValue(Target.getRegNamespace(), "NoRegister"); 2802 } 2803 Table << MatchTable::Comment("AddRegisterRegFlags"); 2804 2805 // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are 2806 // really needed for a physical register reference. We can pack the 2807 // register and flags in a single field. 2808 if (IsDef) 2809 Table << MatchTable::NamedValue("RegState::Define"); 2810 else 2811 Table << MatchTable::IntValue(0); 2812 Table << MatchTable::LineBreak; 2813 } 2814 }; 2815 2816 /// Adds a specific temporary virtual register to the instruction being built. 2817 /// This is used to chain instructions together when emitting multiple 2818 /// instructions. 2819 class TempRegRenderer : public OperandRenderer { 2820 protected: 2821 unsigned InsnID; 2822 unsigned TempRegID; 2823 const CodeGenSubRegIndex *SubRegIdx; 2824 bool IsDef; 2825 bool IsDead; 2826 2827 public: 2828 TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false, 2829 const CodeGenSubRegIndex *SubReg = nullptr, 2830 bool IsDead = false) 2831 : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID), 2832 SubRegIdx(SubReg), IsDef(IsDef), IsDead(IsDead) {} 2833 2834 static bool classof(const OperandRenderer *R) { 2835 return R->getKind() == OR_TempRegister; 2836 } 2837 2838 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2839 if (SubRegIdx) { 2840 assert(!IsDef); 2841 Table << MatchTable::Opcode("GIR_AddTempSubRegister"); 2842 } else 2843 Table << MatchTable::Opcode("GIR_AddTempRegister"); 2844 2845 Table << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 2846 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID) 2847 << MatchTable::Comment("TempRegFlags"); 2848 2849 if (IsDef) { 2850 SmallString<32> RegFlags; 2851 RegFlags += "RegState::Define"; 2852 if (IsDead) 2853 RegFlags += "|RegState::Dead"; 2854 Table << MatchTable::NamedValue(RegFlags); 2855 } else 2856 Table << MatchTable::IntValue(0); 2857 2858 if (SubRegIdx) 2859 Table << MatchTable::NamedValue(SubRegIdx->getQualifiedName()); 2860 Table << MatchTable::LineBreak; 2861 } 2862 }; 2863 2864 /// Adds a specific immediate to the instruction being built. 2865 class ImmRenderer : public OperandRenderer { 2866 protected: 2867 unsigned InsnID; 2868 int64_t Imm; 2869 2870 public: 2871 ImmRenderer(unsigned InsnID, int64_t Imm) 2872 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {} 2873 2874 static bool classof(const OperandRenderer *R) { 2875 return R->getKind() == OR_Imm; 2876 } 2877 2878 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2879 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID") 2880 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm") 2881 << MatchTable::IntValue(Imm) << MatchTable::LineBreak; 2882 } 2883 }; 2884 2885 /// Adds an enum value for a subreg index to the instruction being built. 2886 class SubRegIndexRenderer : public OperandRenderer { 2887 protected: 2888 unsigned InsnID; 2889 const CodeGenSubRegIndex *SubRegIdx; 2890 2891 public: 2892 SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI) 2893 : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {} 2894 2895 static bool classof(const OperandRenderer *R) { 2896 return R->getKind() == OR_SubRegIndex; 2897 } 2898 2899 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2900 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID") 2901 << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex") 2902 << MatchTable::IntValue(SubRegIdx->EnumValue) 2903 << MatchTable::LineBreak; 2904 } 2905 }; 2906 2907 /// Adds operands by calling a renderer function supplied by the ComplexPattern 2908 /// matcher function. 2909 class RenderComplexPatternOperand : public OperandRenderer { 2910 private: 2911 unsigned InsnID; 2912 const Record &TheDef; 2913 /// The name of the operand. 2914 const StringRef SymbolicName; 2915 /// The renderer number. This must be unique within a rule since it's used to 2916 /// identify a temporary variable to hold the renderer function. 2917 unsigned RendererID; 2918 /// When provided, this is the suboperand of the ComplexPattern operand to 2919 /// render. Otherwise all the suboperands will be rendered. 2920 Optional<unsigned> SubOperand; 2921 2922 unsigned getNumOperands() const { 2923 return TheDef.getValueAsDag("Operands")->getNumArgs(); 2924 } 2925 2926 public: 2927 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef, 2928 StringRef SymbolicName, unsigned RendererID, 2929 Optional<unsigned> SubOperand = None) 2930 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef), 2931 SymbolicName(SymbolicName), RendererID(RendererID), 2932 SubOperand(SubOperand) {} 2933 2934 static bool classof(const OperandRenderer *R) { 2935 return R->getKind() == OR_ComplexPattern; 2936 } 2937 2938 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2939 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer" 2940 : "GIR_ComplexRenderer") 2941 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 2942 << MatchTable::Comment("RendererID") 2943 << MatchTable::IntValue(RendererID); 2944 if (SubOperand.hasValue()) 2945 Table << MatchTable::Comment("SubOperand") 2946 << MatchTable::IntValue(SubOperand.getValue()); 2947 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 2948 } 2949 }; 2950 2951 class CustomRenderer : public OperandRenderer { 2952 protected: 2953 unsigned InsnID; 2954 const Record &Renderer; 2955 /// The name of the operand. 2956 const std::string SymbolicName; 2957 2958 public: 2959 CustomRenderer(unsigned InsnID, const Record &Renderer, 2960 StringRef SymbolicName) 2961 : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer), 2962 SymbolicName(SymbolicName) {} 2963 2964 static bool classof(const OperandRenderer *R) { 2965 return R->getKind() == OR_Custom; 2966 } 2967 2968 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 2969 InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName); 2970 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher); 2971 Table << MatchTable::Opcode("GIR_CustomRenderer") 2972 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 2973 << MatchTable::Comment("OldInsnID") 2974 << MatchTable::IntValue(OldInsnVarID) 2975 << MatchTable::Comment("Renderer") 2976 << MatchTable::NamedValue( 2977 "GICR_" + Renderer.getValueAsString("RendererFn").str()) 2978 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 2979 } 2980 }; 2981 2982 class CustomOperandRenderer : public OperandRenderer { 2983 protected: 2984 unsigned InsnID; 2985 const Record &Renderer; 2986 /// The name of the operand. 2987 const std::string SymbolicName; 2988 2989 public: 2990 CustomOperandRenderer(unsigned InsnID, const Record &Renderer, 2991 StringRef SymbolicName) 2992 : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer), 2993 SymbolicName(SymbolicName) {} 2994 2995 static bool classof(const OperandRenderer *R) { 2996 return R->getKind() == OR_CustomOperand; 2997 } 2998 2999 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 3000 const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName); 3001 Table << MatchTable::Opcode("GIR_CustomOperandRenderer") 3002 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 3003 << MatchTable::Comment("OldInsnID") 3004 << MatchTable::IntValue(OpdMatcher.getInsnVarID()) 3005 << MatchTable::Comment("OpIdx") 3006 << MatchTable::IntValue(OpdMatcher.getOpIdx()) 3007 << MatchTable::Comment("OperandRenderer") 3008 << MatchTable::NamedValue( 3009 "GICR_" + Renderer.getValueAsString("RendererFn").str()) 3010 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 3011 } 3012 }; 3013 3014 /// An action taken when all Matcher predicates succeeded for a parent rule. 3015 /// 3016 /// Typical actions include: 3017 /// * Changing the opcode of an instruction. 3018 /// * Adding an operand to an instruction. 3019 class MatchAction { 3020 public: 3021 virtual ~MatchAction() {} 3022 3023 /// Emit the MatchTable opcodes to implement the action. 3024 virtual void emitActionOpcodes(MatchTable &Table, 3025 RuleMatcher &Rule) const = 0; 3026 }; 3027 3028 /// Generates a comment describing the matched rule being acted upon. 3029 class DebugCommentAction : public MatchAction { 3030 private: 3031 std::string S; 3032 3033 public: 3034 DebugCommentAction(StringRef S) : S(std::string(S)) {} 3035 3036 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 3037 Table << MatchTable::Comment(S) << MatchTable::LineBreak; 3038 } 3039 }; 3040 3041 /// Generates code to build an instruction or mutate an existing instruction 3042 /// into the desired instruction when this is possible. 3043 class BuildMIAction : public MatchAction { 3044 private: 3045 unsigned InsnID; 3046 const CodeGenInstruction *I; 3047 InstructionMatcher *Matched; 3048 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers; 3049 3050 /// True if the instruction can be built solely by mutating the opcode. 3051 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const { 3052 if (!Insn) 3053 return false; 3054 3055 if (OperandRenderers.size() != Insn->getNumOperands()) 3056 return false; 3057 3058 for (const auto &Renderer : enumerate(OperandRenderers)) { 3059 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) { 3060 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName()); 3061 if (Insn != &OM.getInstructionMatcher() || 3062 OM.getOpIdx() != Renderer.index()) 3063 return false; 3064 } else 3065 return false; 3066 } 3067 3068 return true; 3069 } 3070 3071 public: 3072 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I) 3073 : InsnID(InsnID), I(I), Matched(nullptr) {} 3074 3075 unsigned getInsnID() const { return InsnID; } 3076 const CodeGenInstruction *getCGI() const { return I; } 3077 3078 void chooseInsnToMutate(RuleMatcher &Rule) { 3079 for (auto *MutateCandidate : Rule.mutatable_insns()) { 3080 if (canMutate(Rule, MutateCandidate)) { 3081 // Take the first one we're offered that we're able to mutate. 3082 Rule.reserveInsnMatcherForMutation(MutateCandidate); 3083 Matched = MutateCandidate; 3084 return; 3085 } 3086 } 3087 } 3088 3089 template <class Kind, class... Args> 3090 Kind &addRenderer(Args&&... args) { 3091 OperandRenderers.emplace_back( 3092 std::make_unique<Kind>(InsnID, std::forward<Args>(args)...)); 3093 return *static_cast<Kind *>(OperandRenderers.back().get()); 3094 } 3095 3096 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 3097 if (Matched) { 3098 assert(canMutate(Rule, Matched) && 3099 "Arranged to mutate an insn that isn't mutatable"); 3100 3101 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched); 3102 Table << MatchTable::Opcode("GIR_MutateOpcode") 3103 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 3104 << MatchTable::Comment("RecycleInsnID") 3105 << MatchTable::IntValue(RecycleInsnID) 3106 << MatchTable::Comment("Opcode") 3107 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName()) 3108 << MatchTable::LineBreak; 3109 3110 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) { 3111 for (auto Def : I->ImplicitDefs) { 3112 auto Namespace = Def->getValue("Namespace") 3113 ? Def->getValueAsString("Namespace") 3114 : ""; 3115 Table << MatchTable::Opcode("GIR_AddImplicitDef") 3116 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 3117 << MatchTable::NamedValue(Namespace, Def->getName()) 3118 << MatchTable::LineBreak; 3119 } 3120 for (auto Use : I->ImplicitUses) { 3121 auto Namespace = Use->getValue("Namespace") 3122 ? Use->getValueAsString("Namespace") 3123 : ""; 3124 Table << MatchTable::Opcode("GIR_AddImplicitUse") 3125 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 3126 << MatchTable::NamedValue(Namespace, Use->getName()) 3127 << MatchTable::LineBreak; 3128 } 3129 } 3130 return; 3131 } 3132 3133 // TODO: Simple permutation looks like it could be almost as common as 3134 // mutation due to commutative operations. 3135 3136 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID") 3137 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode") 3138 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName()) 3139 << MatchTable::LineBreak; 3140 for (const auto &Renderer : OperandRenderers) 3141 Renderer->emitRenderOpcodes(Table, Rule); 3142 3143 if (I->mayLoad || I->mayStore) { 3144 Table << MatchTable::Opcode("GIR_MergeMemOperands") 3145 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 3146 << MatchTable::Comment("MergeInsnID's"); 3147 // Emit the ID's for all the instructions that are matched by this rule. 3148 // TODO: Limit this to matched instructions that mayLoad/mayStore or have 3149 // some other means of having a memoperand. Also limit this to 3150 // emitted instructions that expect to have a memoperand too. For 3151 // example, (G_SEXT (G_LOAD x)) that results in separate load and 3152 // sign-extend instructions shouldn't put the memoperand on the 3153 // sign-extend since it has no effect there. 3154 std::vector<unsigned> MergeInsnIDs; 3155 for (const auto &IDMatcherPair : Rule.defined_insn_vars()) 3156 MergeInsnIDs.push_back(IDMatcherPair.second); 3157 llvm::sort(MergeInsnIDs); 3158 for (const auto &MergeInsnID : MergeInsnIDs) 3159 Table << MatchTable::IntValue(MergeInsnID); 3160 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList") 3161 << MatchTable::LineBreak; 3162 } 3163 3164 // FIXME: This is a hack but it's sufficient for ISel. We'll need to do 3165 // better for combines. Particularly when there are multiple match 3166 // roots. 3167 if (InsnID == 0) 3168 Table << MatchTable::Opcode("GIR_EraseFromParent") 3169 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 3170 << MatchTable::LineBreak; 3171 } 3172 }; 3173 3174 /// Generates code to constrain the operands of an output instruction to the 3175 /// register classes specified by the definition of that instruction. 3176 class ConstrainOperandsToDefinitionAction : public MatchAction { 3177 unsigned InsnID; 3178 3179 public: 3180 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {} 3181 3182 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 3183 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands") 3184 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 3185 << MatchTable::LineBreak; 3186 } 3187 }; 3188 3189 /// Generates code to constrain the specified operand of an output instruction 3190 /// to the specified register class. 3191 class ConstrainOperandToRegClassAction : public MatchAction { 3192 unsigned InsnID; 3193 unsigned OpIdx; 3194 const CodeGenRegisterClass &RC; 3195 3196 public: 3197 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx, 3198 const CodeGenRegisterClass &RC) 3199 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {} 3200 3201 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 3202 Table << MatchTable::Opcode("GIR_ConstrainOperandRC") 3203 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 3204 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 3205 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID") 3206 << MatchTable::LineBreak; 3207 } 3208 }; 3209 3210 /// Generates code to create a temporary register which can be used to chain 3211 /// instructions together. 3212 class MakeTempRegisterAction : public MatchAction { 3213 private: 3214 LLTCodeGen Ty; 3215 unsigned TempRegID; 3216 3217 public: 3218 MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID) 3219 : Ty(Ty), TempRegID(TempRegID) { 3220 KnownTypes.insert(Ty); 3221 } 3222 3223 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 3224 Table << MatchTable::Opcode("GIR_MakeTempReg") 3225 << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID) 3226 << MatchTable::Comment("TypeID") 3227 << MatchTable::NamedValue(Ty.getCxxEnumValue()) 3228 << MatchTable::LineBreak; 3229 } 3230 }; 3231 3232 InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) { 3233 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName)); 3234 MutatableInsns.insert(Matchers.back().get()); 3235 return *Matchers.back(); 3236 } 3237 3238 void RuleMatcher::addRequiredFeature(Record *Feature) { 3239 RequiredFeatures.push_back(Feature); 3240 } 3241 3242 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const { 3243 return RequiredFeatures; 3244 } 3245 3246 // Emplaces an action of the specified Kind at the end of the action list. 3247 // 3248 // Returns a reference to the newly created action. 3249 // 3250 // Like std::vector::emplace_back(), may invalidate all iterators if the new 3251 // size exceeds the capacity. Otherwise, only invalidates the past-the-end 3252 // iterator. 3253 template <class Kind, class... Args> 3254 Kind &RuleMatcher::addAction(Args &&... args) { 3255 Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...)); 3256 return *static_cast<Kind *>(Actions.back().get()); 3257 } 3258 3259 // Emplaces an action of the specified Kind before the given insertion point. 3260 // 3261 // Returns an iterator pointing at the newly created instruction. 3262 // 3263 // Like std::vector::insert(), may invalidate all iterators if the new size 3264 // exceeds the capacity. Otherwise, only invalidates the iterators from the 3265 // insertion point onwards. 3266 template <class Kind, class... Args> 3267 action_iterator RuleMatcher::insertAction(action_iterator InsertPt, 3268 Args &&... args) { 3269 return Actions.emplace(InsertPt, 3270 std::make_unique<Kind>(std::forward<Args>(args)...)); 3271 } 3272 3273 unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) { 3274 unsigned NewInsnVarID = NextInsnVarID++; 3275 InsnVariableIDs[&Matcher] = NewInsnVarID; 3276 return NewInsnVarID; 3277 } 3278 3279 unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const { 3280 const auto &I = InsnVariableIDs.find(&InsnMatcher); 3281 if (I != InsnVariableIDs.end()) 3282 return I->second; 3283 llvm_unreachable("Matched Insn was not captured in a local variable"); 3284 } 3285 3286 void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) { 3287 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) { 3288 DefinedOperands[SymbolicName] = &OM; 3289 return; 3290 } 3291 3292 // If the operand is already defined, then we must ensure both references in 3293 // the matcher have the exact same node. 3294 OM.addPredicate<SameOperandMatcher>( 3295 OM.getSymbolicName(), getOperandMatcher(OM.getSymbolicName()).getOpIdx()); 3296 } 3297 3298 void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) { 3299 if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) { 3300 PhysRegOperands[Reg] = &OM; 3301 return; 3302 } 3303 } 3304 3305 InstructionMatcher & 3306 RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const { 3307 for (const auto &I : InsnVariableIDs) 3308 if (I.first->getSymbolicName() == SymbolicName) 3309 return *I.first; 3310 llvm_unreachable( 3311 ("Failed to lookup instruction " + SymbolicName).str().c_str()); 3312 } 3313 3314 const OperandMatcher & 3315 RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const { 3316 const auto &I = PhysRegOperands.find(Reg); 3317 3318 if (I == PhysRegOperands.end()) { 3319 PrintFatalError(SrcLoc, "Register " + Reg->getName() + 3320 " was not declared in matcher"); 3321 } 3322 3323 return *I->second; 3324 } 3325 3326 const OperandMatcher & 3327 RuleMatcher::getOperandMatcher(StringRef Name) const { 3328 const auto &I = DefinedOperands.find(Name); 3329 3330 if (I == DefinedOperands.end()) 3331 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher"); 3332 3333 return *I->second; 3334 } 3335 3336 void RuleMatcher::emit(MatchTable &Table) { 3337 if (Matchers.empty()) 3338 llvm_unreachable("Unexpected empty matcher!"); 3339 3340 // The representation supports rules that require multiple roots such as: 3341 // %ptr(p0) = ... 3342 // %elt0(s32) = G_LOAD %ptr 3343 // %1(p0) = G_ADD %ptr, 4 3344 // %elt1(s32) = G_LOAD p0 %1 3345 // which could be usefully folded into: 3346 // %ptr(p0) = ... 3347 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr 3348 // on some targets but we don't need to make use of that yet. 3349 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet"); 3350 3351 unsigned LabelID = Table.allocateLabelID(); 3352 Table << MatchTable::Opcode("GIM_Try", +1) 3353 << MatchTable::Comment("On fail goto") 3354 << MatchTable::JumpTarget(LabelID) 3355 << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str()) 3356 << MatchTable::LineBreak; 3357 3358 if (!RequiredFeatures.empty()) { 3359 Table << MatchTable::Opcode("GIM_CheckFeatures") 3360 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures)) 3361 << MatchTable::LineBreak; 3362 } 3363 3364 Matchers.front()->emitPredicateOpcodes(Table, *this); 3365 3366 // We must also check if it's safe to fold the matched instructions. 3367 if (InsnVariableIDs.size() >= 2) { 3368 // Invert the map to create stable ordering (by var names) 3369 SmallVector<unsigned, 2> InsnIDs; 3370 for (const auto &Pair : InsnVariableIDs) { 3371 // Skip the root node since it isn't moving anywhere. Everything else is 3372 // sinking to meet it. 3373 if (Pair.first == Matchers.front().get()) 3374 continue; 3375 3376 InsnIDs.push_back(Pair.second); 3377 } 3378 llvm::sort(InsnIDs); 3379 3380 for (const auto &InsnID : InsnIDs) { 3381 // Reject the difficult cases until we have a more accurate check. 3382 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold") 3383 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 3384 << MatchTable::LineBreak; 3385 3386 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or 3387 // account for unsafe cases. 3388 // 3389 // Example: 3390 // MI1--> %0 = ... 3391 // %1 = ... %0 3392 // MI0--> %2 = ... %0 3393 // It's not safe to erase MI1. We currently handle this by not 3394 // erasing %0 (even when it's dead). 3395 // 3396 // Example: 3397 // MI1--> %0 = load volatile @a 3398 // %1 = load volatile @a 3399 // MI0--> %2 = ... %0 3400 // It's not safe to sink %0's def past %1. We currently handle 3401 // this by rejecting all loads. 3402 // 3403 // Example: 3404 // MI1--> %0 = load @a 3405 // %1 = store @a 3406 // MI0--> %2 = ... %0 3407 // It's not safe to sink %0's def past %1. We currently handle 3408 // this by rejecting all loads. 3409 // 3410 // Example: 3411 // G_CONDBR %cond, @BB1 3412 // BB0: 3413 // MI1--> %0 = load @a 3414 // G_BR @BB1 3415 // BB1: 3416 // MI0--> %2 = ... %0 3417 // It's not always safe to sink %0 across control flow. In this 3418 // case it may introduce a memory fault. We currentl handle this 3419 // by rejecting all loads. 3420 } 3421 } 3422 3423 for (const auto &PM : EpilogueMatchers) 3424 PM->emitPredicateOpcodes(Table, *this); 3425 3426 for (const auto &MA : Actions) 3427 MA->emitActionOpcodes(Table, *this); 3428 3429 if (Table.isWithCoverage()) 3430 Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID) 3431 << MatchTable::LineBreak; 3432 else 3433 Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str()) 3434 << MatchTable::LineBreak; 3435 3436 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak 3437 << MatchTable::Label(LabelID); 3438 ++NumPatternEmitted; 3439 } 3440 3441 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const { 3442 // Rules involving more match roots have higher priority. 3443 if (Matchers.size() > B.Matchers.size()) 3444 return true; 3445 if (Matchers.size() < B.Matchers.size()) 3446 return false; 3447 3448 for (auto Matcher : zip(Matchers, B.Matchers)) { 3449 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher))) 3450 return true; 3451 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher))) 3452 return false; 3453 } 3454 3455 return false; 3456 } 3457 3458 unsigned RuleMatcher::countRendererFns() const { 3459 return std::accumulate( 3460 Matchers.begin(), Matchers.end(), 0, 3461 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) { 3462 return A + Matcher->countRendererFns(); 3463 }); 3464 } 3465 3466 bool OperandPredicateMatcher::isHigherPriorityThan( 3467 const OperandPredicateMatcher &B) const { 3468 // Generally speaking, an instruction is more important than an Int or a 3469 // LiteralInt because it can cover more nodes but theres an exception to 3470 // this. G_CONSTANT's are less important than either of those two because they 3471 // are more permissive. 3472 3473 const InstructionOperandMatcher *AOM = 3474 dyn_cast<InstructionOperandMatcher>(this); 3475 const InstructionOperandMatcher *BOM = 3476 dyn_cast<InstructionOperandMatcher>(&B); 3477 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction(); 3478 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction(); 3479 3480 if (AOM && BOM) { 3481 // The relative priorities between a G_CONSTANT and any other instruction 3482 // don't actually matter but this code is needed to ensure a strict weak 3483 // ordering. This is particularly important on Windows where the rules will 3484 // be incorrectly sorted without it. 3485 if (AIsConstantInsn != BIsConstantInsn) 3486 return AIsConstantInsn < BIsConstantInsn; 3487 return false; 3488 } 3489 3490 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt)) 3491 return false; 3492 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt)) 3493 return true; 3494 3495 return Kind < B.Kind; 3496 } 3497 3498 void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table, 3499 RuleMatcher &Rule) const { 3500 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName); 3501 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher()); 3502 assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID()); 3503 3504 Table << MatchTable::Opcode("GIM_CheckIsSameOperand") 3505 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 3506 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx) 3507 << MatchTable::Comment("OtherMI") 3508 << MatchTable::IntValue(OtherInsnVarID) 3509 << MatchTable::Comment("OtherOpIdx") 3510 << MatchTable::IntValue(OtherOM.getOpIdx()) 3511 << MatchTable::LineBreak; 3512 } 3513 3514 //===- GlobalISelEmitter class --------------------------------------------===// 3515 3516 static Expected<LLTCodeGen> getInstResultType(const TreePatternNode *Dst) { 3517 ArrayRef<TypeSetByHwMode> ChildTypes = Dst->getExtTypes(); 3518 if (ChildTypes.size() != 1) 3519 return failedImport("Dst pattern child has multiple results"); 3520 3521 Optional<LLTCodeGen> MaybeOpTy; 3522 if (ChildTypes.front().isMachineValueType()) { 3523 MaybeOpTy = 3524 MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy); 3525 } 3526 3527 if (!MaybeOpTy) 3528 return failedImport("Dst operand has an unsupported type"); 3529 return *MaybeOpTy; 3530 } 3531 3532 class GlobalISelEmitter { 3533 public: 3534 explicit GlobalISelEmitter(RecordKeeper &RK); 3535 void run(raw_ostream &OS); 3536 3537 private: 3538 const RecordKeeper &RK; 3539 const CodeGenDAGPatterns CGP; 3540 const CodeGenTarget &Target; 3541 CodeGenRegBank &CGRegs; 3542 3543 /// Keep track of the equivalence between SDNodes and Instruction by mapping 3544 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to 3545 /// check for attributes on the relation such as CheckMMOIsNonAtomic. 3546 /// This is defined using 'GINodeEquiv' in the target description. 3547 DenseMap<Record *, Record *> NodeEquivs; 3548 3549 /// Keep track of the equivalence between ComplexPattern's and 3550 /// GIComplexOperandMatcher. Map entries are specified by subclassing 3551 /// GIComplexPatternEquiv. 3552 DenseMap<const Record *, const Record *> ComplexPatternEquivs; 3553 3554 /// Keep track of the equivalence between SDNodeXForm's and 3555 /// GICustomOperandRenderer. Map entries are specified by subclassing 3556 /// GISDNodeXFormEquiv. 3557 DenseMap<const Record *, const Record *> SDNodeXFormEquivs; 3558 3559 /// Keep track of Scores of PatternsToMatch similar to how the DAG does. 3560 /// This adds compatibility for RuleMatchers to use this for ordering rules. 3561 DenseMap<uint64_t, int> RuleMatcherScores; 3562 3563 // Map of predicates to their subtarget features. 3564 SubtargetFeatureInfoMap SubtargetFeatures; 3565 3566 // Rule coverage information. 3567 Optional<CodeGenCoverage> RuleCoverage; 3568 3569 /// Variables used to help with collecting of named operands for predicates 3570 /// with 'let PredicateCodeUsesOperands = 1'. WaitingForNamedOperands is set 3571 /// to the number of named operands that predicate expects. Store locations in 3572 /// StoreIdxForName correspond to the order in which operand names appear in 3573 /// predicate's argument list. 3574 /// When we visit named leaf operand and WaitingForNamedOperands is not zero, 3575 /// add matcher that will record operand and decrease counter. 3576 unsigned WaitingForNamedOperands = 0; 3577 StringMap<unsigned> StoreIdxForName; 3578 3579 void gatherOpcodeValues(); 3580 void gatherTypeIDValues(); 3581 void gatherNodeEquivs(); 3582 3583 Record *findNodeEquiv(Record *N) const; 3584 const CodeGenInstruction *getEquivNode(Record &Equiv, 3585 const TreePatternNode *N) const; 3586 3587 Error importRulePredicates(RuleMatcher &M, ArrayRef<Record *> Predicates); 3588 Expected<InstructionMatcher &> 3589 createAndImportSelDAGMatcher(RuleMatcher &Rule, 3590 InstructionMatcher &InsnMatcher, 3591 const TreePatternNode *Src, unsigned &TempOpIdx); 3592 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R, 3593 unsigned &TempOpIdx) const; 3594 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher, 3595 const TreePatternNode *SrcChild, 3596 bool OperandIsAPointer, bool OperandIsImmArg, 3597 unsigned OpIdx, unsigned &TempOpIdx); 3598 3599 Expected<BuildMIAction &> createAndImportInstructionRenderer( 3600 RuleMatcher &M, InstructionMatcher &InsnMatcher, 3601 const TreePatternNode *Src, const TreePatternNode *Dst); 3602 Expected<action_iterator> createAndImportSubInstructionRenderer( 3603 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst, 3604 unsigned TempReg); 3605 Expected<action_iterator> 3606 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M, 3607 const TreePatternNode *Dst); 3608 3609 Expected<action_iterator> 3610 importExplicitDefRenderers(action_iterator InsertPt, RuleMatcher &M, 3611 BuildMIAction &DstMIBuilder, 3612 const TreePatternNode *Dst); 3613 3614 Expected<action_iterator> 3615 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M, 3616 BuildMIAction &DstMIBuilder, 3617 const llvm::TreePatternNode *Dst); 3618 Expected<action_iterator> 3619 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule, 3620 BuildMIAction &DstMIBuilder, 3621 TreePatternNode *DstChild); 3622 Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M, 3623 BuildMIAction &DstMIBuilder, 3624 DagInit *DefaultOps) const; 3625 Error 3626 importImplicitDefRenderers(BuildMIAction &DstMIBuilder, 3627 const std::vector<Record *> &ImplicitDefs) const; 3628 3629 void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName, 3630 StringRef TypeIdentifier, StringRef ArgType, 3631 StringRef ArgName, StringRef AdditionalArgs, 3632 StringRef AdditionalDeclarations, 3633 std::function<bool(const Record *R)> Filter); 3634 void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier, 3635 StringRef ArgType, 3636 std::function<bool(const Record *R)> Filter); 3637 void emitMIPredicateFns(raw_ostream &OS); 3638 3639 /// Analyze pattern \p P, returning a matcher for it if possible. 3640 /// Otherwise, return an Error explaining why we don't support it. 3641 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P); 3642 3643 void declareSubtargetFeature(Record *Predicate); 3644 3645 MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize, 3646 bool WithCoverage); 3647 3648 /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned 3649 /// CodeGenRegisterClass will support the CodeGenRegisterClass of 3650 /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode. 3651 /// If no register class is found, return None. 3652 Optional<const CodeGenRegisterClass *> 3653 inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty, 3654 TreePatternNode *SuperRegNode, 3655 TreePatternNode *SubRegIdxNode); 3656 Optional<CodeGenSubRegIndex *> 3657 inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode); 3658 3659 /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode. 3660 /// Return None if no such class exists. 3661 Optional<const CodeGenRegisterClass *> 3662 inferSuperRegisterClass(const TypeSetByHwMode &Ty, 3663 TreePatternNode *SubRegIdxNode); 3664 3665 /// Return the CodeGenRegisterClass associated with \p Leaf if it has one. 3666 Optional<const CodeGenRegisterClass *> 3667 getRegClassFromLeaf(TreePatternNode *Leaf); 3668 3669 /// Return a CodeGenRegisterClass for \p N if one can be found. Return None 3670 /// otherwise. 3671 Optional<const CodeGenRegisterClass *> 3672 inferRegClassFromPattern(TreePatternNode *N); 3673 3674 /// Return the size of the MemoryVT in this predicate, if possible. 3675 Optional<unsigned> 3676 getMemSizeBitsFromPredicate(const TreePredicateFn &Predicate); 3677 3678 // Add builtin predicates. 3679 Expected<InstructionMatcher &> 3680 addBuiltinPredicates(const Record *SrcGIEquivOrNull, 3681 const TreePredicateFn &Predicate, 3682 InstructionMatcher &InsnMatcher, bool &HasAddedMatcher); 3683 3684 public: 3685 /// Takes a sequence of \p Rules and group them based on the predicates 3686 /// they share. \p MatcherStorage is used as a memory container 3687 /// for the group that are created as part of this process. 3688 /// 3689 /// What this optimization does looks like if GroupT = GroupMatcher: 3690 /// Output without optimization: 3691 /// \verbatim 3692 /// # R1 3693 /// # predicate A 3694 /// # predicate B 3695 /// ... 3696 /// # R2 3697 /// # predicate A // <-- effectively this is going to be checked twice. 3698 /// // Once in R1 and once in R2. 3699 /// # predicate C 3700 /// \endverbatim 3701 /// Output with optimization: 3702 /// \verbatim 3703 /// # Group1_2 3704 /// # predicate A // <-- Check is now shared. 3705 /// # R1 3706 /// # predicate B 3707 /// # R2 3708 /// # predicate C 3709 /// \endverbatim 3710 template <class GroupT> 3711 static std::vector<Matcher *> optimizeRules( 3712 ArrayRef<Matcher *> Rules, 3713 std::vector<std::unique_ptr<Matcher>> &MatcherStorage); 3714 }; 3715 3716 void GlobalISelEmitter::gatherOpcodeValues() { 3717 InstructionOpcodeMatcher::initOpcodeValuesMap(Target); 3718 } 3719 3720 void GlobalISelEmitter::gatherTypeIDValues() { 3721 LLTOperandMatcher::initTypeIDValuesMap(); 3722 } 3723 3724 void GlobalISelEmitter::gatherNodeEquivs() { 3725 assert(NodeEquivs.empty()); 3726 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv")) 3727 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv; 3728 3729 assert(ComplexPatternEquivs.empty()); 3730 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) { 3731 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent"); 3732 if (!SelDAGEquiv) 3733 continue; 3734 ComplexPatternEquivs[SelDAGEquiv] = Equiv; 3735 } 3736 3737 assert(SDNodeXFormEquivs.empty()); 3738 for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) { 3739 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent"); 3740 if (!SelDAGEquiv) 3741 continue; 3742 SDNodeXFormEquivs[SelDAGEquiv] = Equiv; 3743 } 3744 } 3745 3746 Record *GlobalISelEmitter::findNodeEquiv(Record *N) const { 3747 return NodeEquivs.lookup(N); 3748 } 3749 3750 const CodeGenInstruction * 3751 GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const { 3752 if (N->getNumChildren() >= 1) { 3753 // setcc operation maps to two different G_* instructions based on the type. 3754 if (!Equiv.isValueUnset("IfFloatingPoint") && 3755 MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint()) 3756 return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint")); 3757 } 3758 3759 for (const TreePredicateCall &Call : N->getPredicateCalls()) { 3760 const TreePredicateFn &Predicate = Call.Fn; 3761 if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() && 3762 Predicate.isSignExtLoad()) 3763 return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend")); 3764 if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() && 3765 Predicate.isZeroExtLoad()) 3766 return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend")); 3767 } 3768 3769 return &Target.getInstruction(Equiv.getValueAsDef("I")); 3770 } 3771 3772 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK) 3773 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()), 3774 CGRegs(Target.getRegBank()) {} 3775 3776 //===- Emitter ------------------------------------------------------------===// 3777 3778 Error GlobalISelEmitter::importRulePredicates(RuleMatcher &M, 3779 ArrayRef<Record *> Predicates) { 3780 for (Record *Pred : Predicates) { 3781 if (Pred->getValueAsString("CondString").empty()) 3782 continue; 3783 declareSubtargetFeature(Pred); 3784 M.addRequiredFeature(Pred); 3785 } 3786 3787 return Error::success(); 3788 } 3789 3790 Optional<unsigned> GlobalISelEmitter::getMemSizeBitsFromPredicate(const TreePredicateFn &Predicate) { 3791 Optional<LLTCodeGen> MemTyOrNone = 3792 MVTToLLT(getValueType(Predicate.getMemoryVT())); 3793 3794 if (!MemTyOrNone) 3795 return None; 3796 3797 // Align so unusual types like i1 don't get rounded down. 3798 return llvm::alignTo( 3799 static_cast<unsigned>(MemTyOrNone->get().getSizeInBits()), 8); 3800 } 3801 3802 Expected<InstructionMatcher &> GlobalISelEmitter::addBuiltinPredicates( 3803 const Record *SrcGIEquivOrNull, const TreePredicateFn &Predicate, 3804 InstructionMatcher &InsnMatcher, bool &HasAddedMatcher) { 3805 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) { 3806 if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) { 3807 SmallVector<unsigned, 4> ParsedAddrSpaces; 3808 3809 for (Init *Val : AddrSpaces->getValues()) { 3810 IntInit *IntVal = dyn_cast<IntInit>(Val); 3811 if (!IntVal) 3812 return failedImport("Address space is not an integer"); 3813 ParsedAddrSpaces.push_back(IntVal->getValue()); 3814 } 3815 3816 if (!ParsedAddrSpaces.empty()) { 3817 InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>( 3818 0, ParsedAddrSpaces); 3819 } 3820 } 3821 3822 int64_t MinAlign = Predicate.getMinAlignment(); 3823 if (MinAlign > 0) 3824 InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign); 3825 } 3826 3827 // G_LOAD is used for both non-extending and any-extending loads. 3828 if (Predicate.isLoad() && Predicate.isNonExtLoad()) { 3829 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>( 3830 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0); 3831 return InsnMatcher; 3832 } 3833 if (Predicate.isLoad() && Predicate.isAnyExtLoad()) { 3834 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>( 3835 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0); 3836 return InsnMatcher; 3837 } 3838 3839 if (Predicate.isStore()) { 3840 if (Predicate.isTruncStore()) { 3841 if (Predicate.getMemoryVT() != nullptr) { 3842 // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size. 3843 auto MemSizeInBits = getMemSizeBitsFromPredicate(Predicate); 3844 if (!MemSizeInBits) 3845 return failedImport("MemVT could not be converted to LLT"); 3846 3847 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0, *MemSizeInBits / 3848 8); 3849 } else { 3850 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>( 3851 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0); 3852 } 3853 return InsnMatcher; 3854 } 3855 if (Predicate.isNonTruncStore()) { 3856 // We need to check the sizes match here otherwise we could incorrectly 3857 // match truncating stores with non-truncating ones. 3858 InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>( 3859 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0); 3860 } 3861 } 3862 3863 // No check required. We already did it by swapping the opcode. 3864 if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") && 3865 Predicate.isSignExtLoad()) 3866 return InsnMatcher; 3867 3868 // No check required. We already did it by swapping the opcode. 3869 if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") && 3870 Predicate.isZeroExtLoad()) 3871 return InsnMatcher; 3872 3873 // No check required. G_STORE by itself is a non-extending store. 3874 if (Predicate.isNonTruncStore()) 3875 return InsnMatcher; 3876 3877 if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) { 3878 if (Predicate.getMemoryVT() != nullptr) { 3879 auto MemSizeInBits = getMemSizeBitsFromPredicate(Predicate); 3880 if (!MemSizeInBits) 3881 return failedImport("MemVT could not be converted to LLT"); 3882 3883 InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0, 3884 *MemSizeInBits / 8); 3885 return InsnMatcher; 3886 } 3887 } 3888 3889 if (Predicate.isLoad() || Predicate.isStore()) { 3890 // No check required. A G_LOAD/G_STORE is an unindexed load. 3891 if (Predicate.isUnindexed()) 3892 return InsnMatcher; 3893 } 3894 3895 if (Predicate.isAtomic()) { 3896 if (Predicate.isAtomicOrderingMonotonic()) { 3897 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Monotonic"); 3898 return InsnMatcher; 3899 } 3900 if (Predicate.isAtomicOrderingAcquire()) { 3901 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire"); 3902 return InsnMatcher; 3903 } 3904 if (Predicate.isAtomicOrderingRelease()) { 3905 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release"); 3906 return InsnMatcher; 3907 } 3908 if (Predicate.isAtomicOrderingAcquireRelease()) { 3909 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>( 3910 "AcquireRelease"); 3911 return InsnMatcher; 3912 } 3913 if (Predicate.isAtomicOrderingSequentiallyConsistent()) { 3914 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>( 3915 "SequentiallyConsistent"); 3916 return InsnMatcher; 3917 } 3918 } 3919 3920 if (Predicate.isAtomicOrderingAcquireOrStronger()) { 3921 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>( 3922 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger); 3923 return InsnMatcher; 3924 } 3925 if (Predicate.isAtomicOrderingWeakerThanAcquire()) { 3926 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>( 3927 "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan); 3928 return InsnMatcher; 3929 } 3930 3931 if (Predicate.isAtomicOrderingReleaseOrStronger()) { 3932 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>( 3933 "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger); 3934 return InsnMatcher; 3935 } 3936 if (Predicate.isAtomicOrderingWeakerThanRelease()) { 3937 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>( 3938 "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan); 3939 return InsnMatcher; 3940 } 3941 HasAddedMatcher = false; 3942 return InsnMatcher; 3943 } 3944 3945 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher( 3946 RuleMatcher &Rule, InstructionMatcher &InsnMatcher, 3947 const TreePatternNode *Src, unsigned &TempOpIdx) { 3948 Record *SrcGIEquivOrNull = nullptr; 3949 const CodeGenInstruction *SrcGIOrNull = nullptr; 3950 3951 // Start with the defined operands (i.e., the results of the root operator). 3952 if (Src->getExtTypes().size() > 1) 3953 return failedImport("Src pattern has multiple results"); 3954 3955 if (Src->isLeaf()) { 3956 Init *SrcInit = Src->getLeafValue(); 3957 if (isa<IntInit>(SrcInit)) { 3958 InsnMatcher.addPredicate<InstructionOpcodeMatcher>( 3959 &Target.getInstruction(RK.getDef("G_CONSTANT"))); 3960 } else 3961 return failedImport( 3962 "Unable to deduce gMIR opcode to handle Src (which is a leaf)"); 3963 } else { 3964 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator()); 3965 if (!SrcGIEquivOrNull) 3966 return failedImport("Pattern operator lacks an equivalent Instruction" + 3967 explainOperator(Src->getOperator())); 3968 SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src); 3969 3970 // The operators look good: match the opcode 3971 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull); 3972 } 3973 3974 unsigned OpIdx = 0; 3975 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) { 3976 // Results don't have a name unless they are the root node. The caller will 3977 // set the name if appropriate. 3978 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx); 3979 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */)) 3980 return failedImport(toString(std::move(Error)) + 3981 " for result of Src pattern operator"); 3982 } 3983 3984 for (const TreePredicateCall &Call : Src->getPredicateCalls()) { 3985 const TreePredicateFn &Predicate = Call.Fn; 3986 bool HasAddedBuiltinMatcher = true; 3987 if (Predicate.isAlwaysTrue()) 3988 continue; 3989 3990 if (Predicate.isImmediatePattern()) { 3991 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate); 3992 continue; 3993 } 3994 3995 auto InsnMatcherOrError = addBuiltinPredicates( 3996 SrcGIEquivOrNull, Predicate, InsnMatcher, HasAddedBuiltinMatcher); 3997 if (auto Error = InsnMatcherOrError.takeError()) 3998 return std::move(Error); 3999 4000 if (Predicate.hasGISelPredicateCode()) { 4001 if (Predicate.usesOperands()) { 4002 assert(WaitingForNamedOperands == 0 && 4003 "previous predicate didn't find all operands or " 4004 "nested predicate that uses operands"); 4005 TreePattern *TP = Predicate.getOrigPatFragRecord(); 4006 WaitingForNamedOperands = TP->getNumArgs(); 4007 for (unsigned i = 0; i < WaitingForNamedOperands; ++i) 4008 StoreIdxForName[getScopedName(Call.Scope, TP->getArgName(i))] = i; 4009 } 4010 InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate); 4011 continue; 4012 } 4013 if (!HasAddedBuiltinMatcher) { 4014 return failedImport("Src pattern child has predicate (" + 4015 explainPredicates(Src) + ")"); 4016 } 4017 } 4018 4019 bool IsAtomic = false; 4020 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic")) 4021 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic"); 4022 else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) { 4023 IsAtomic = true; 4024 InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>( 4025 "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger); 4026 } 4027 4028 if (Src->isLeaf()) { 4029 Init *SrcInit = Src->getLeafValue(); 4030 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) { 4031 OperandMatcher &OM = 4032 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx); 4033 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue()); 4034 } else 4035 return failedImport( 4036 "Unable to deduce gMIR opcode to handle Src (which is a leaf)"); 4037 } else { 4038 assert(SrcGIOrNull && 4039 "Expected to have already found an equivalent Instruction"); 4040 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" || 4041 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") { 4042 // imm/fpimm still have operands but we don't need to do anything with it 4043 // here since we don't support ImmLeaf predicates yet. However, we still 4044 // need to note the hidden operand to get GIM_CheckNumOperands correct. 4045 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx); 4046 return InsnMatcher; 4047 } 4048 4049 // Special case because the operand order is changed from setcc. The 4050 // predicate operand needs to be swapped from the last operand to the first 4051 // source. 4052 4053 unsigned NumChildren = Src->getNumChildren(); 4054 bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP"; 4055 4056 if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") { 4057 TreePatternNode *SrcChild = Src->getChild(NumChildren - 1); 4058 if (SrcChild->isLeaf()) { 4059 DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue()); 4060 Record *CCDef = DI ? DI->getDef() : nullptr; 4061 if (!CCDef || !CCDef->isSubClassOf("CondCode")) 4062 return failedImport("Unable to handle CondCode"); 4063 4064 OperandMatcher &OM = 4065 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx); 4066 StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") : 4067 CCDef->getValueAsString("ICmpPredicate"); 4068 4069 if (!PredType.empty()) { 4070 OM.addPredicate<CmpPredicateOperandMatcher>(std::string(PredType)); 4071 // Process the other 2 operands normally. 4072 --NumChildren; 4073 } 4074 } 4075 } 4076 4077 // Hack around an unfortunate mistake in how atomic store (and really 4078 // atomicrmw in general) operands were ordered. A ISD::STORE used the order 4079 // <stored value>, <pointer> order. ISD::ATOMIC_STORE used the opposite, 4080 // <pointer>, <stored value>. In GlobalISel there's just the one store 4081 // opcode, so we need to swap the operands here to get the right type check. 4082 if (IsAtomic && SrcGIOrNull->TheDef->getName() == "G_STORE") { 4083 assert(NumChildren == 2 && "wrong operands for atomic store"); 4084 4085 TreePatternNode *PtrChild = Src->getChild(0); 4086 TreePatternNode *ValueChild = Src->getChild(1); 4087 4088 if (auto Error = importChildMatcher(Rule, InsnMatcher, PtrChild, true, 4089 false, 1, TempOpIdx)) 4090 return std::move(Error); 4091 4092 if (auto Error = importChildMatcher(Rule, InsnMatcher, ValueChild, false, 4093 false, 0, TempOpIdx)) 4094 return std::move(Error); 4095 return InsnMatcher; 4096 } 4097 4098 // Match the used operands (i.e. the children of the operator). 4099 bool IsIntrinsic = 4100 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" || 4101 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS"; 4102 const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP); 4103 if (IsIntrinsic && !II) 4104 return failedImport("Expected IntInit containing intrinsic ID)"); 4105 4106 for (unsigned i = 0; i != NumChildren; ++i) { 4107 TreePatternNode *SrcChild = Src->getChild(i); 4108 4109 // We need to determine the meaning of a literal integer based on the 4110 // context. If this is a field required to be an immediate (such as an 4111 // immarg intrinsic argument), the required predicates are different than 4112 // a constant which may be materialized in a register. If we have an 4113 // argument that is required to be an immediate, we should not emit an LLT 4114 // type check, and should not be looking for a G_CONSTANT defined 4115 // register. 4116 bool OperandIsImmArg = SrcGIOrNull->isOperandImmArg(i); 4117 4118 // SelectionDAG allows pointers to be represented with iN since it doesn't 4119 // distinguish between pointers and integers but they are different types in GlobalISel. 4120 // Coerce integers to pointers to address space 0 if the context indicates a pointer. 4121 // 4122 bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i); 4123 4124 if (IsIntrinsic) { 4125 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately 4126 // following the defs is an intrinsic ID. 4127 if (i == 0) { 4128 OperandMatcher &OM = 4129 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx); 4130 OM.addPredicate<IntrinsicIDOperandMatcher>(II); 4131 continue; 4132 } 4133 4134 // We have to check intrinsics for llvm_anyptr_ty and immarg parameters. 4135 // 4136 // Note that we have to look at the i-1th parameter, because we don't 4137 // have the intrinsic ID in the intrinsic's parameter list. 4138 OperandIsAPointer |= II->isParamAPointer(i - 1); 4139 OperandIsImmArg |= II->isParamImmArg(i - 1); 4140 } 4141 4142 if (auto Error = 4143 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer, 4144 OperandIsImmArg, OpIdx++, TempOpIdx)) 4145 return std::move(Error); 4146 } 4147 } 4148 4149 return InsnMatcher; 4150 } 4151 4152 Error GlobalISelEmitter::importComplexPatternOperandMatcher( 4153 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const { 4154 const auto &ComplexPattern = ComplexPatternEquivs.find(R); 4155 if (ComplexPattern == ComplexPatternEquivs.end()) 4156 return failedImport("SelectionDAG ComplexPattern (" + R->getName() + 4157 ") not mapped to GlobalISel"); 4158 4159 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second); 4160 TempOpIdx++; 4161 return Error::success(); 4162 } 4163 4164 // Get the name to use for a pattern operand. For an anonymous physical register 4165 // input, this should use the register name. 4166 static StringRef getSrcChildName(const TreePatternNode *SrcChild, 4167 Record *&PhysReg) { 4168 StringRef SrcChildName = SrcChild->getName(); 4169 if (SrcChildName.empty() && SrcChild->isLeaf()) { 4170 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) { 4171 auto *ChildRec = ChildDefInit->getDef(); 4172 if (ChildRec->isSubClassOf("Register")) { 4173 SrcChildName = ChildRec->getName(); 4174 PhysReg = ChildRec; 4175 } 4176 } 4177 } 4178 4179 return SrcChildName; 4180 } 4181 4182 Error GlobalISelEmitter::importChildMatcher( 4183 RuleMatcher &Rule, InstructionMatcher &InsnMatcher, 4184 const TreePatternNode *SrcChild, bool OperandIsAPointer, 4185 bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) { 4186 4187 Record *PhysReg = nullptr; 4188 std::string SrcChildName = std::string(getSrcChildName(SrcChild, PhysReg)); 4189 if (!SrcChild->isLeaf() && 4190 SrcChild->getOperator()->isSubClassOf("ComplexPattern")) { 4191 // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is 4192 // "MY_PAT:op1:op2" and the ones with same "name" represent same operand. 4193 std::string PatternName = std::string(SrcChild->getOperator()->getName()); 4194 for (unsigned i = 0; i < SrcChild->getNumChildren(); ++i) { 4195 PatternName += ":"; 4196 PatternName += SrcChild->getChild(i)->getName(); 4197 } 4198 SrcChildName = PatternName; 4199 } 4200 4201 OperandMatcher &OM = 4202 PhysReg ? InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx) 4203 : InsnMatcher.addOperand(OpIdx, SrcChildName, TempOpIdx); 4204 if (OM.isSameAsAnotherOperand()) 4205 return Error::success(); 4206 4207 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes(); 4208 if (ChildTypes.size() != 1) 4209 return failedImport("Src pattern child has multiple results"); 4210 4211 // Check MBB's before the type check since they are not a known type. 4212 if (!SrcChild->isLeaf()) { 4213 if (SrcChild->getOperator()->isSubClassOf("SDNode")) { 4214 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator()); 4215 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { 4216 OM.addPredicate<MBBOperandMatcher>(); 4217 return Error::success(); 4218 } 4219 if (SrcChild->getOperator()->getName() == "timm") { 4220 OM.addPredicate<ImmOperandMatcher>(); 4221 4222 // Add predicates, if any 4223 for (const TreePredicateCall &Call : SrcChild->getPredicateCalls()) { 4224 const TreePredicateFn &Predicate = Call.Fn; 4225 4226 // Only handle immediate patterns for now 4227 if (Predicate.isImmediatePattern()) { 4228 OM.addPredicate<OperandImmPredicateMatcher>(Predicate); 4229 } 4230 } 4231 4232 return Error::success(); 4233 } 4234 } 4235 } 4236 4237 // Immediate arguments have no meaningful type to check as they don't have 4238 // registers. 4239 if (!OperandIsImmArg) { 4240 if (auto Error = 4241 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer)) 4242 return failedImport(toString(std::move(Error)) + " for Src operand (" + 4243 to_string(*SrcChild) + ")"); 4244 } 4245 4246 // Check for nested instructions. 4247 if (!SrcChild->isLeaf()) { 4248 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) { 4249 // When a ComplexPattern is used as an operator, it should do the same 4250 // thing as when used as a leaf. However, the children of the operator 4251 // name the sub-operands that make up the complex operand and we must 4252 // prepare to reference them in the renderer too. 4253 unsigned RendererID = TempOpIdx; 4254 if (auto Error = importComplexPatternOperandMatcher( 4255 OM, SrcChild->getOperator(), TempOpIdx)) 4256 return Error; 4257 4258 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) { 4259 auto *SubOperand = SrcChild->getChild(i); 4260 if (!SubOperand->getName().empty()) { 4261 if (auto Error = Rule.defineComplexSubOperand( 4262 SubOperand->getName(), SrcChild->getOperator(), RendererID, i, 4263 SrcChildName)) 4264 return Error; 4265 } 4266 } 4267 4268 return Error::success(); 4269 } 4270 4271 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>( 4272 InsnMatcher.getRuleMatcher(), SrcChild->getName()); 4273 if (!MaybeInsnOperand.hasValue()) { 4274 // This isn't strictly true. If the user were to provide exactly the same 4275 // matchers as the original operand then we could allow it. However, it's 4276 // simpler to not permit the redundant specification. 4277 return failedImport("Nested instruction cannot be the same as another operand"); 4278 } 4279 4280 // Map the node to a gMIR instruction. 4281 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand; 4282 auto InsnMatcherOrError = createAndImportSelDAGMatcher( 4283 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx); 4284 if (auto Error = InsnMatcherOrError.takeError()) 4285 return Error; 4286 4287 return Error::success(); 4288 } 4289 4290 if (SrcChild->hasAnyPredicate()) 4291 return failedImport("Src pattern child has unsupported predicate"); 4292 4293 // Check for constant immediates. 4294 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) { 4295 if (OperandIsImmArg) { 4296 // Checks for argument directly in operand list 4297 OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue()); 4298 } else { 4299 // Checks for materialized constant 4300 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue()); 4301 } 4302 return Error::success(); 4303 } 4304 4305 // Check for def's like register classes or ComplexPattern's. 4306 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) { 4307 auto *ChildRec = ChildDefInit->getDef(); 4308 4309 if (WaitingForNamedOperands) { 4310 auto PA = SrcChild->getNamesAsPredicateArg().begin(); 4311 std::string Name = getScopedName(PA->getScope(), PA->getIdentifier()); 4312 OM.addPredicate<RecordNamedOperandMatcher>(StoreIdxForName[Name], Name); 4313 --WaitingForNamedOperands; 4314 } 4315 4316 // Check for register classes. 4317 if (ChildRec->isSubClassOf("RegisterClass") || 4318 ChildRec->isSubClassOf("RegisterOperand")) { 4319 OM.addPredicate<RegisterBankOperandMatcher>( 4320 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit))); 4321 return Error::success(); 4322 } 4323 4324 if (ChildRec->isSubClassOf("Register")) { 4325 // This just be emitted as a copy to the specific register. 4326 ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode(); 4327 const CodeGenRegisterClass *RC 4328 = CGRegs.getMinimalPhysRegClass(ChildRec, &VT); 4329 if (!RC) { 4330 return failedImport( 4331 "Could not determine physical register class of pattern source"); 4332 } 4333 4334 OM.addPredicate<RegisterBankOperandMatcher>(*RC); 4335 return Error::success(); 4336 } 4337 4338 // Check for ValueType. 4339 if (ChildRec->isSubClassOf("ValueType")) { 4340 // We already added a type check as standard practice so this doesn't need 4341 // to do anything. 4342 return Error::success(); 4343 } 4344 4345 // Check for ComplexPattern's. 4346 if (ChildRec->isSubClassOf("ComplexPattern")) 4347 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx); 4348 4349 if (ChildRec->isSubClassOf("ImmLeaf")) { 4350 return failedImport( 4351 "Src pattern child def is an unsupported tablegen class (ImmLeaf)"); 4352 } 4353 4354 // Place holder for SRCVALUE nodes. Nothing to do here. 4355 if (ChildRec->getName() == "srcvalue") 4356 return Error::success(); 4357 4358 const bool ImmAllOnesV = ChildRec->getName() == "immAllOnesV"; 4359 if (ImmAllOnesV || ChildRec->getName() == "immAllZerosV") { 4360 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>( 4361 InsnMatcher.getRuleMatcher(), SrcChild->getName(), false); 4362 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand; 4363 4364 ValueTypeByHwMode VTy = ChildTypes.front().getValueTypeByHwMode(); 4365 4366 const CodeGenInstruction &BuildVector 4367 = Target.getInstruction(RK.getDef("G_BUILD_VECTOR")); 4368 const CodeGenInstruction &BuildVectorTrunc 4369 = Target.getInstruction(RK.getDef("G_BUILD_VECTOR_TRUNC")); 4370 4371 // Treat G_BUILD_VECTOR as the canonical opcode, and G_BUILD_VECTOR_TRUNC 4372 // as an alternative. 4373 InsnOperand.getInsnMatcher().addPredicate<InstructionOpcodeMatcher>( 4374 makeArrayRef({&BuildVector, &BuildVectorTrunc})); 4375 4376 // TODO: Handle both G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC We could 4377 // theoretically not emit any opcode check, but getOpcodeMatcher currently 4378 // has to succeed. 4379 OperandMatcher &OM = 4380 InsnOperand.getInsnMatcher().addOperand(0, "", TempOpIdx); 4381 if (auto Error = 4382 OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */)) 4383 return failedImport(toString(std::move(Error)) + 4384 " for result of Src pattern operator"); 4385 4386 InsnOperand.getInsnMatcher().addPredicate<VectorSplatImmPredicateMatcher>( 4387 ImmAllOnesV ? VectorSplatImmPredicateMatcher::AllOnes 4388 : VectorSplatImmPredicateMatcher::AllZeros); 4389 return Error::success(); 4390 } 4391 4392 return failedImport( 4393 "Src pattern child def is an unsupported tablegen class"); 4394 } 4395 4396 return failedImport("Src pattern child is an unsupported kind"); 4397 } 4398 4399 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer( 4400 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder, 4401 TreePatternNode *DstChild) { 4402 4403 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName()); 4404 if (SubOperand.hasValue()) { 4405 DstMIBuilder.addRenderer<RenderComplexPatternOperand>( 4406 *std::get<0>(*SubOperand), DstChild->getName(), 4407 std::get<1>(*SubOperand), std::get<2>(*SubOperand)); 4408 return InsertPt; 4409 } 4410 4411 if (!DstChild->isLeaf()) { 4412 if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) { 4413 auto Child = DstChild->getChild(0); 4414 auto I = SDNodeXFormEquivs.find(DstChild->getOperator()); 4415 if (I != SDNodeXFormEquivs.end()) { 4416 Record *XFormOpc = DstChild->getOperator()->getValueAsDef("Opcode"); 4417 if (XFormOpc->getName() == "timm") { 4418 // If this is a TargetConstant, there won't be a corresponding 4419 // instruction to transform. Instead, this will refer directly to an 4420 // operand in an instruction's operand list. 4421 DstMIBuilder.addRenderer<CustomOperandRenderer>(*I->second, 4422 Child->getName()); 4423 } else { 4424 DstMIBuilder.addRenderer<CustomRenderer>(*I->second, 4425 Child->getName()); 4426 } 4427 4428 return InsertPt; 4429 } 4430 return failedImport("SDNodeXForm " + Child->getName() + 4431 " has no custom renderer"); 4432 } 4433 4434 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't 4435 // inline, but in MI it's just another operand. 4436 if (DstChild->getOperator()->isSubClassOf("SDNode")) { 4437 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator()); 4438 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { 4439 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName()); 4440 return InsertPt; 4441 } 4442 } 4443 4444 // Similarly, imm is an operator in TreePatternNode's view but must be 4445 // rendered as operands. 4446 // FIXME: The target should be able to choose sign-extended when appropriate 4447 // (e.g. on Mips). 4448 if (DstChild->getOperator()->getName() == "timm") { 4449 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName()); 4450 return InsertPt; 4451 } else if (DstChild->getOperator()->getName() == "imm") { 4452 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName()); 4453 return InsertPt; 4454 } else if (DstChild->getOperator()->getName() == "fpimm") { 4455 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>( 4456 DstChild->getName()); 4457 return InsertPt; 4458 } 4459 4460 if (DstChild->getOperator()->isSubClassOf("Instruction")) { 4461 auto OpTy = getInstResultType(DstChild); 4462 if (!OpTy) 4463 return OpTy.takeError(); 4464 4465 unsigned TempRegID = Rule.allocateTempRegID(); 4466 InsertPt = Rule.insertAction<MakeTempRegisterAction>( 4467 InsertPt, *OpTy, TempRegID); 4468 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID); 4469 4470 auto InsertPtOrError = createAndImportSubInstructionRenderer( 4471 ++InsertPt, Rule, DstChild, TempRegID); 4472 if (auto Error = InsertPtOrError.takeError()) 4473 return std::move(Error); 4474 return InsertPtOrError.get(); 4475 } 4476 4477 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild)); 4478 } 4479 4480 // It could be a specific immediate in which case we should just check for 4481 // that immediate. 4482 if (const IntInit *ChildIntInit = 4483 dyn_cast<IntInit>(DstChild->getLeafValue())) { 4484 DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue()); 4485 return InsertPt; 4486 } 4487 4488 // Otherwise, we're looking for a bog-standard RegisterClass operand. 4489 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) { 4490 auto *ChildRec = ChildDefInit->getDef(); 4491 4492 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes(); 4493 if (ChildTypes.size() != 1) 4494 return failedImport("Dst pattern child has multiple results"); 4495 4496 Optional<LLTCodeGen> OpTyOrNone = None; 4497 if (ChildTypes.front().isMachineValueType()) 4498 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy); 4499 if (!OpTyOrNone) 4500 return failedImport("Dst operand has an unsupported type"); 4501 4502 if (ChildRec->isSubClassOf("Register")) { 4503 DstMIBuilder.addRenderer<AddRegisterRenderer>(Target, ChildRec); 4504 return InsertPt; 4505 } 4506 4507 if (ChildRec->isSubClassOf("RegisterClass") || 4508 ChildRec->isSubClassOf("RegisterOperand") || 4509 ChildRec->isSubClassOf("ValueType")) { 4510 if (ChildRec->isSubClassOf("RegisterOperand") && 4511 !ChildRec->isValueUnset("GIZeroRegister")) { 4512 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>( 4513 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister")); 4514 return InsertPt; 4515 } 4516 4517 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName()); 4518 return InsertPt; 4519 } 4520 4521 if (ChildRec->isSubClassOf("SubRegIndex")) { 4522 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec); 4523 DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue); 4524 return InsertPt; 4525 } 4526 4527 if (ChildRec->isSubClassOf("ComplexPattern")) { 4528 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec); 4529 if (ComplexPattern == ComplexPatternEquivs.end()) 4530 return failedImport( 4531 "SelectionDAG ComplexPattern not mapped to GlobalISel"); 4532 4533 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName()); 4534 DstMIBuilder.addRenderer<RenderComplexPatternOperand>( 4535 *ComplexPattern->second, DstChild->getName(), 4536 OM.getAllocatedTemporariesBaseID()); 4537 return InsertPt; 4538 } 4539 4540 return failedImport( 4541 "Dst pattern child def is an unsupported tablegen class"); 4542 } 4543 return failedImport("Dst pattern child is an unsupported kind"); 4544 } 4545 4546 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer( 4547 RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src, 4548 const TreePatternNode *Dst) { 4549 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst); 4550 if (auto Error = InsertPtOrError.takeError()) 4551 return std::move(Error); 4552 4553 action_iterator InsertPt = InsertPtOrError.get(); 4554 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get()); 4555 4556 for (auto PhysInput : InsnMatcher.getPhysRegInputs()) { 4557 InsertPt = M.insertAction<BuildMIAction>( 4558 InsertPt, M.allocateOutputInsnID(), 4559 &Target.getInstruction(RK.getDef("COPY"))); 4560 BuildMIAction &CopyToPhysRegMIBuilder = 4561 *static_cast<BuildMIAction *>(InsertPt->get()); 4562 CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(Target, 4563 PhysInput.first, 4564 true); 4565 CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first); 4566 } 4567 4568 if (auto Error = importExplicitDefRenderers(InsertPt, M, DstMIBuilder, Dst) 4569 .takeError()) 4570 return std::move(Error); 4571 4572 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst) 4573 .takeError()) 4574 return std::move(Error); 4575 4576 return DstMIBuilder; 4577 } 4578 4579 Expected<action_iterator> 4580 GlobalISelEmitter::createAndImportSubInstructionRenderer( 4581 const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst, 4582 unsigned TempRegID) { 4583 auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst); 4584 4585 // TODO: Assert there's exactly one result. 4586 4587 if (auto Error = InsertPtOrError.takeError()) 4588 return std::move(Error); 4589 4590 BuildMIAction &DstMIBuilder = 4591 *static_cast<BuildMIAction *>(InsertPtOrError.get()->get()); 4592 4593 // Assign the result to TempReg. 4594 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true); 4595 4596 InsertPtOrError = 4597 importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst); 4598 if (auto Error = InsertPtOrError.takeError()) 4599 return std::move(Error); 4600 4601 // We need to make sure that when we import an INSERT_SUBREG as a 4602 // subinstruction that it ends up being constrained to the correct super 4603 // register and subregister classes. 4604 auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName(); 4605 if (OpName == "INSERT_SUBREG") { 4606 auto SubClass = inferRegClassFromPattern(Dst->getChild(1)); 4607 if (!SubClass) 4608 return failedImport( 4609 "Cannot infer register class from INSERT_SUBREG operand #1"); 4610 Optional<const CodeGenRegisterClass *> SuperClass = 4611 inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0), 4612 Dst->getChild(2)); 4613 if (!SuperClass) 4614 return failedImport( 4615 "Cannot infer register class for INSERT_SUBREG operand #0"); 4616 // The destination and the super register source of an INSERT_SUBREG must 4617 // be the same register class. 4618 M.insertAction<ConstrainOperandToRegClassAction>( 4619 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass); 4620 M.insertAction<ConstrainOperandToRegClassAction>( 4621 InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass); 4622 M.insertAction<ConstrainOperandToRegClassAction>( 4623 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass); 4624 return InsertPtOrError.get(); 4625 } 4626 4627 if (OpName == "EXTRACT_SUBREG") { 4628 // EXTRACT_SUBREG selects into a subregister COPY but unlike most 4629 // instructions, the result register class is controlled by the 4630 // subregisters of the operand. As a result, we must constrain the result 4631 // class rather than check that it's already the right one. 4632 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0)); 4633 if (!SuperClass) 4634 return failedImport( 4635 "Cannot infer register class from EXTRACT_SUBREG operand #0"); 4636 4637 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1)); 4638 if (!SubIdx) 4639 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index"); 4640 4641 const auto SrcRCDstRCPair = 4642 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx); 4643 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass"); 4644 M.insertAction<ConstrainOperandToRegClassAction>( 4645 InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second); 4646 M.insertAction<ConstrainOperandToRegClassAction>( 4647 InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first); 4648 4649 // We're done with this pattern! It's eligible for GISel emission; return 4650 // it. 4651 return InsertPtOrError.get(); 4652 } 4653 4654 // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a 4655 // subinstruction. 4656 if (OpName == "SUBREG_TO_REG") { 4657 auto SubClass = inferRegClassFromPattern(Dst->getChild(1)); 4658 if (!SubClass) 4659 return failedImport( 4660 "Cannot infer register class from SUBREG_TO_REG child #1"); 4661 auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0), 4662 Dst->getChild(2)); 4663 if (!SuperClass) 4664 return failedImport( 4665 "Cannot infer register class for SUBREG_TO_REG operand #0"); 4666 M.insertAction<ConstrainOperandToRegClassAction>( 4667 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass); 4668 M.insertAction<ConstrainOperandToRegClassAction>( 4669 InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass); 4670 return InsertPtOrError.get(); 4671 } 4672 4673 if (OpName == "REG_SEQUENCE") { 4674 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0)); 4675 M.insertAction<ConstrainOperandToRegClassAction>( 4676 InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass); 4677 4678 unsigned Num = Dst->getNumChildren(); 4679 for (unsigned I = 1; I != Num; I += 2) { 4680 TreePatternNode *SubRegChild = Dst->getChild(I + 1); 4681 4682 auto SubIdx = inferSubRegIndexForNode(SubRegChild); 4683 if (!SubIdx) 4684 return failedImport("REG_SEQUENCE child is not a subreg index"); 4685 4686 const auto SrcRCDstRCPair = 4687 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx); 4688 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass"); 4689 M.insertAction<ConstrainOperandToRegClassAction>( 4690 InsertPt, DstMIBuilder.getInsnID(), I, *SrcRCDstRCPair->second); 4691 } 4692 4693 return InsertPtOrError.get(); 4694 } 4695 4696 M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt, 4697 DstMIBuilder.getInsnID()); 4698 return InsertPtOrError.get(); 4699 } 4700 4701 Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer( 4702 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) { 4703 Record *DstOp = Dst->getOperator(); 4704 if (!DstOp->isSubClassOf("Instruction")) { 4705 if (DstOp->isSubClassOf("ValueType")) 4706 return failedImport( 4707 "Pattern operator isn't an instruction (it's a ValueType)"); 4708 return failedImport("Pattern operator isn't an instruction"); 4709 } 4710 CodeGenInstruction *DstI = &Target.getInstruction(DstOp); 4711 4712 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction 4713 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy. 4714 StringRef Name = DstI->TheDef->getName(); 4715 if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG") 4716 DstI = &Target.getInstruction(RK.getDef("COPY")); 4717 4718 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(), 4719 DstI); 4720 } 4721 4722 Expected<action_iterator> GlobalISelEmitter::importExplicitDefRenderers( 4723 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder, 4724 const TreePatternNode *Dst) { 4725 const CodeGenInstruction *DstI = DstMIBuilder.getCGI(); 4726 const unsigned NumDefs = DstI->Operands.NumDefs; 4727 if (NumDefs == 0) 4728 return InsertPt; 4729 4730 DstMIBuilder.addRenderer<CopyRenderer>(DstI->Operands[0].Name); 4731 4732 // Some instructions have multiple defs, but are missing a type entry 4733 // (e.g. s_cc_out operands). 4734 if (Dst->getExtTypes().size() < NumDefs) 4735 return failedImport("unhandled discarded def"); 4736 4737 // Patterns only handle a single result, so any result after the first is an 4738 // implicitly dead def. 4739 for (unsigned I = 1; I < NumDefs; ++I) { 4740 const TypeSetByHwMode &ExtTy = Dst->getExtType(I); 4741 if (!ExtTy.isMachineValueType()) 4742 return failedImport("unsupported typeset"); 4743 4744 auto OpTy = MVTToLLT(ExtTy.getMachineValueType().SimpleTy); 4745 if (!OpTy) 4746 return failedImport("unsupported type"); 4747 4748 unsigned TempRegID = M.allocateTempRegID(); 4749 InsertPt = 4750 M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTy, TempRegID); 4751 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true, nullptr, true); 4752 } 4753 4754 return InsertPt; 4755 } 4756 4757 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers( 4758 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder, 4759 const llvm::TreePatternNode *Dst) { 4760 const CodeGenInstruction *DstI = DstMIBuilder.getCGI(); 4761 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator()); 4762 4763 StringRef Name = OrigDstI->TheDef->getName(); 4764 unsigned ExpectedDstINumUses = Dst->getNumChildren(); 4765 4766 // EXTRACT_SUBREG needs to use a subregister COPY. 4767 if (Name == "EXTRACT_SUBREG") { 4768 if (!Dst->getChild(1)->isLeaf()) 4769 return failedImport("EXTRACT_SUBREG child #1 is not a leaf"); 4770 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue()); 4771 if (!SubRegInit) 4772 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index"); 4773 4774 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef()); 4775 TreePatternNode *ValChild = Dst->getChild(0); 4776 if (!ValChild->isLeaf()) { 4777 // We really have to handle the source instruction, and then insert a 4778 // copy from the subregister. 4779 auto ExtractSrcTy = getInstResultType(ValChild); 4780 if (!ExtractSrcTy) 4781 return ExtractSrcTy.takeError(); 4782 4783 unsigned TempRegID = M.allocateTempRegID(); 4784 InsertPt = M.insertAction<MakeTempRegisterAction>( 4785 InsertPt, *ExtractSrcTy, TempRegID); 4786 4787 auto InsertPtOrError = createAndImportSubInstructionRenderer( 4788 ++InsertPt, M, ValChild, TempRegID); 4789 if (auto Error = InsertPtOrError.takeError()) 4790 return std::move(Error); 4791 4792 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, false, SubIdx); 4793 return InsertPt; 4794 } 4795 4796 // If this is a source operand, this is just a subregister copy. 4797 Record *RCDef = getInitValueAsRegClass(ValChild->getLeafValue()); 4798 if (!RCDef) 4799 return failedImport("EXTRACT_SUBREG child #0 could not " 4800 "be coerced to a register class"); 4801 4802 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef); 4803 4804 const auto SrcRCDstRCPair = 4805 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx); 4806 if (SrcRCDstRCPair.hasValue()) { 4807 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass"); 4808 if (SrcRCDstRCPair->first != RC) 4809 return failedImport("EXTRACT_SUBREG requires an additional COPY"); 4810 } 4811 4812 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(), 4813 SubIdx); 4814 return InsertPt; 4815 } 4816 4817 if (Name == "REG_SEQUENCE") { 4818 if (!Dst->getChild(0)->isLeaf()) 4819 return failedImport("REG_SEQUENCE child #0 is not a leaf"); 4820 4821 Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()); 4822 if (!RCDef) 4823 return failedImport("REG_SEQUENCE child #0 could not " 4824 "be coerced to a register class"); 4825 4826 if ((ExpectedDstINumUses - 1) % 2 != 0) 4827 return failedImport("Malformed REG_SEQUENCE"); 4828 4829 for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) { 4830 TreePatternNode *ValChild = Dst->getChild(I); 4831 TreePatternNode *SubRegChild = Dst->getChild(I + 1); 4832 4833 if (DefInit *SubRegInit = 4834 dyn_cast<DefInit>(SubRegChild->getLeafValue())) { 4835 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef()); 4836 4837 auto InsertPtOrError = 4838 importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild); 4839 if (auto Error = InsertPtOrError.takeError()) 4840 return std::move(Error); 4841 InsertPt = InsertPtOrError.get(); 4842 DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx); 4843 } 4844 } 4845 4846 return InsertPt; 4847 } 4848 4849 // Render the explicit uses. 4850 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs; 4851 if (Name == "COPY_TO_REGCLASS") { 4852 DstINumUses--; // Ignore the class constraint. 4853 ExpectedDstINumUses--; 4854 } 4855 4856 // NumResults - This is the number of results produced by the instruction in 4857 // the "outs" list. 4858 unsigned NumResults = OrigDstI->Operands.NumDefs; 4859 4860 // Number of operands we know the output instruction must have. If it is 4861 // variadic, we could have more operands. 4862 unsigned NumFixedOperands = DstI->Operands.size(); 4863 4864 // Loop over all of the fixed operands of the instruction pattern, emitting 4865 // code to fill them all in. The node 'N' usually has number children equal to 4866 // the number of input operands of the instruction. However, in cases where 4867 // there are predicate operands for an instruction, we need to fill in the 4868 // 'execute always' values. Match up the node operands to the instruction 4869 // operands to do this. 4870 unsigned Child = 0; 4871 4872 // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the 4873 // number of operands at the end of the list which have default values. 4874 // Those can come from the pattern if it provides enough arguments, or be 4875 // filled in with the default if the pattern hasn't provided them. But any 4876 // operand with a default value _before_ the last mandatory one will be 4877 // filled in with their defaults unconditionally. 4878 unsigned NonOverridableOperands = NumFixedOperands; 4879 while (NonOverridableOperands > NumResults && 4880 CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec)) 4881 --NonOverridableOperands; 4882 4883 unsigned NumDefaultOps = 0; 4884 for (unsigned I = 0; I != DstINumUses; ++I) { 4885 unsigned InstOpNo = DstI->Operands.NumDefs + I; 4886 4887 // Determine what to emit for this operand. 4888 Record *OperandNode = DstI->Operands[InstOpNo].Rec; 4889 4890 // If the operand has default values, introduce them now. 4891 if (CGP.operandHasDefault(OperandNode) && 4892 (InstOpNo < NonOverridableOperands || Child >= Dst->getNumChildren())) { 4893 // This is a predicate or optional def operand which the pattern has not 4894 // overridden, or which we aren't letting it override; emit the 'default 4895 // ops' operands. 4896 4897 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[InstOpNo]; 4898 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps"); 4899 if (auto Error = importDefaultOperandRenderers( 4900 InsertPt, M, DstMIBuilder, DefaultOps)) 4901 return std::move(Error); 4902 ++NumDefaultOps; 4903 continue; 4904 } 4905 4906 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder, 4907 Dst->getChild(Child)); 4908 if (auto Error = InsertPtOrError.takeError()) 4909 return std::move(Error); 4910 InsertPt = InsertPtOrError.get(); 4911 ++Child; 4912 } 4913 4914 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses) 4915 return failedImport("Expected " + llvm::to_string(DstINumUses) + 4916 " used operands but found " + 4917 llvm::to_string(ExpectedDstINumUses) + 4918 " explicit ones and " + llvm::to_string(NumDefaultOps) + 4919 " default ones"); 4920 4921 return InsertPt; 4922 } 4923 4924 Error GlobalISelEmitter::importDefaultOperandRenderers( 4925 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder, 4926 DagInit *DefaultOps) const { 4927 for (const auto *DefaultOp : DefaultOps->getArgs()) { 4928 Optional<LLTCodeGen> OpTyOrNone = None; 4929 4930 // Look through ValueType operators. 4931 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) { 4932 if (const DefInit *DefaultDagOperator = 4933 dyn_cast<DefInit>(DefaultDagOp->getOperator())) { 4934 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) { 4935 OpTyOrNone = MVTToLLT(getValueType( 4936 DefaultDagOperator->getDef())); 4937 DefaultOp = DefaultDagOp->getArg(0); 4938 } 4939 } 4940 } 4941 4942 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) { 4943 auto Def = DefaultDefOp->getDef(); 4944 if (Def->getName() == "undef_tied_input") { 4945 unsigned TempRegID = M.allocateTempRegID(); 4946 M.insertAction<MakeTempRegisterAction>( 4947 InsertPt, OpTyOrNone.getValue(), TempRegID); 4948 InsertPt = M.insertAction<BuildMIAction>( 4949 InsertPt, M.allocateOutputInsnID(), 4950 &Target.getInstruction(RK.getDef("IMPLICIT_DEF"))); 4951 BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>( 4952 InsertPt->get()); 4953 IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID); 4954 DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID); 4955 } else { 4956 DstMIBuilder.addRenderer<AddRegisterRenderer>(Target, Def); 4957 } 4958 continue; 4959 } 4960 4961 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) { 4962 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue()); 4963 continue; 4964 } 4965 4966 return failedImport("Could not add default op"); 4967 } 4968 4969 return Error::success(); 4970 } 4971 4972 Error GlobalISelEmitter::importImplicitDefRenderers( 4973 BuildMIAction &DstMIBuilder, 4974 const std::vector<Record *> &ImplicitDefs) const { 4975 if (!ImplicitDefs.empty()) 4976 return failedImport("Pattern defines a physical register"); 4977 return Error::success(); 4978 } 4979 4980 Optional<const CodeGenRegisterClass *> 4981 GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) { 4982 assert(Leaf && "Expected node?"); 4983 assert(Leaf->isLeaf() && "Expected leaf?"); 4984 Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue()); 4985 if (!RCRec) 4986 return None; 4987 CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec); 4988 if (!RC) 4989 return None; 4990 return RC; 4991 } 4992 4993 Optional<const CodeGenRegisterClass *> 4994 GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) { 4995 if (!N) 4996 return None; 4997 4998 if (N->isLeaf()) 4999 return getRegClassFromLeaf(N); 5000 5001 // We don't have a leaf node, so we have to try and infer something. Check 5002 // that we have an instruction that we an infer something from. 5003 5004 // Only handle things that produce a single type. 5005 if (N->getNumTypes() != 1) 5006 return None; 5007 Record *OpRec = N->getOperator(); 5008 5009 // We only want instructions. 5010 if (!OpRec->isSubClassOf("Instruction")) 5011 return None; 5012 5013 // Don't want to try and infer things when there could potentially be more 5014 // than one candidate register class. 5015 auto &Inst = Target.getInstruction(OpRec); 5016 if (Inst.Operands.NumDefs > 1) 5017 return None; 5018 5019 // Handle any special-case instructions which we can safely infer register 5020 // classes from. 5021 StringRef InstName = Inst.TheDef->getName(); 5022 bool IsRegSequence = InstName == "REG_SEQUENCE"; 5023 if (IsRegSequence || InstName == "COPY_TO_REGCLASS") { 5024 // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It 5025 // has the desired register class as the first child. 5026 TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1); 5027 if (!RCChild->isLeaf()) 5028 return None; 5029 return getRegClassFromLeaf(RCChild); 5030 } 5031 if (InstName == "INSERT_SUBREG") { 5032 TreePatternNode *Child0 = N->getChild(0); 5033 assert(Child0->getNumTypes() == 1 && "Unexpected number of types!"); 5034 const TypeSetByHwMode &VTy = Child0->getExtType(0); 5035 return inferSuperRegisterClassForNode(VTy, Child0, N->getChild(2)); 5036 } 5037 if (InstName == "EXTRACT_SUBREG") { 5038 assert(N->getNumTypes() == 1 && "Unexpected number of types!"); 5039 const TypeSetByHwMode &VTy = N->getExtType(0); 5040 return inferSuperRegisterClass(VTy, N->getChild(1)); 5041 } 5042 5043 // Handle destination record types that we can safely infer a register class 5044 // from. 5045 const auto &DstIOperand = Inst.Operands[0]; 5046 Record *DstIOpRec = DstIOperand.Rec; 5047 if (DstIOpRec->isSubClassOf("RegisterOperand")) { 5048 DstIOpRec = DstIOpRec->getValueAsDef("RegClass"); 5049 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec); 5050 return &RC; 5051 } 5052 5053 if (DstIOpRec->isSubClassOf("RegisterClass")) { 5054 const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec); 5055 return &RC; 5056 } 5057 5058 return None; 5059 } 5060 5061 Optional<const CodeGenRegisterClass *> 5062 GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty, 5063 TreePatternNode *SubRegIdxNode) { 5064 assert(SubRegIdxNode && "Expected subregister index node!"); 5065 // We need a ValueTypeByHwMode for getSuperRegForSubReg. 5066 if (!Ty.isValueTypeByHwMode(false)) 5067 return None; 5068 if (!SubRegIdxNode->isLeaf()) 5069 return None; 5070 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue()); 5071 if (!SubRegInit) 5072 return None; 5073 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef()); 5074 5075 // Use the information we found above to find a minimal register class which 5076 // supports the subregister and type we want. 5077 auto RC = 5078 Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx, 5079 /* MustBeAllocatable */ true); 5080 if (!RC) 5081 return None; 5082 return *RC; 5083 } 5084 5085 Optional<const CodeGenRegisterClass *> 5086 GlobalISelEmitter::inferSuperRegisterClassForNode( 5087 const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode, 5088 TreePatternNode *SubRegIdxNode) { 5089 assert(SuperRegNode && "Expected super register node!"); 5090 // Check if we already have a defined register class for the super register 5091 // node. If we do, then we should preserve that rather than inferring anything 5092 // from the subregister index node. We can assume that whoever wrote the 5093 // pattern in the first place made sure that the super register and 5094 // subregister are compatible. 5095 if (Optional<const CodeGenRegisterClass *> SuperRegisterClass = 5096 inferRegClassFromPattern(SuperRegNode)) 5097 return *SuperRegisterClass; 5098 return inferSuperRegisterClass(Ty, SubRegIdxNode); 5099 } 5100 5101 Optional<CodeGenSubRegIndex *> 5102 GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) { 5103 if (!SubRegIdxNode->isLeaf()) 5104 return None; 5105 5106 DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue()); 5107 if (!SubRegInit) 5108 return None; 5109 return CGRegs.getSubRegIdx(SubRegInit->getDef()); 5110 } 5111 5112 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) { 5113 // Keep track of the matchers and actions to emit. 5114 int Score = P.getPatternComplexity(CGP); 5115 RuleMatcher M(P.getSrcRecord()->getLoc()); 5116 RuleMatcherScores[M.getRuleID()] = Score; 5117 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) + 5118 " => " + 5119 llvm::to_string(*P.getDstPattern())); 5120 5121 SmallVector<Record *, 4> Predicates; 5122 P.getPredicateRecords(Predicates); 5123 if (auto Error = importRulePredicates(M, Predicates)) 5124 return std::move(Error); 5125 5126 // Next, analyze the pattern operators. 5127 TreePatternNode *Src = P.getSrcPattern(); 5128 TreePatternNode *Dst = P.getDstPattern(); 5129 5130 // If the root of either pattern isn't a simple operator, ignore it. 5131 if (auto Err = isTrivialOperatorNode(Dst)) 5132 return failedImport("Dst pattern root isn't a trivial operator (" + 5133 toString(std::move(Err)) + ")"); 5134 if (auto Err = isTrivialOperatorNode(Src)) 5135 return failedImport("Src pattern root isn't a trivial operator (" + 5136 toString(std::move(Err)) + ")"); 5137 5138 // The different predicates and matchers created during 5139 // addInstructionMatcher use the RuleMatcher M to set up their 5140 // instruction ID (InsnVarID) that are going to be used when 5141 // M is going to be emitted. 5142 // However, the code doing the emission still relies on the IDs 5143 // returned during that process by the RuleMatcher when issuing 5144 // the recordInsn opcodes. 5145 // Because of that: 5146 // 1. The order in which we created the predicates 5147 // and such must be the same as the order in which we emit them, 5148 // and 5149 // 2. We need to reset the generation of the IDs in M somewhere between 5150 // addInstructionMatcher and emit 5151 // 5152 // FIXME: Long term, we don't want to have to rely on this implicit 5153 // naming being the same. One possible solution would be to have 5154 // explicit operator for operation capture and reference those. 5155 // The plus side is that it would expose opportunities to share 5156 // the capture accross rules. The downside is that it would 5157 // introduce a dependency between predicates (captures must happen 5158 // before their first use.) 5159 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName()); 5160 unsigned TempOpIdx = 0; 5161 auto InsnMatcherOrError = 5162 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx); 5163 if (auto Error = InsnMatcherOrError.takeError()) 5164 return std::move(Error); 5165 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get(); 5166 5167 if (Dst->isLeaf()) { 5168 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue()); 5169 if (RCDef) { 5170 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef); 5171 5172 // We need to replace the def and all its uses with the specified 5173 // operand. However, we must also insert COPY's wherever needed. 5174 // For now, emit a copy and let the register allocator clean up. 5175 auto &DstI = Target.getInstruction(RK.getDef("COPY")); 5176 const auto &DstIOperand = DstI.Operands[0]; 5177 5178 OperandMatcher &OM0 = InsnMatcher.getOperand(0); 5179 OM0.setSymbolicName(DstIOperand.Name); 5180 M.defineOperand(OM0.getSymbolicName(), OM0); 5181 OM0.addPredicate<RegisterBankOperandMatcher>(RC); 5182 5183 auto &DstMIBuilder = 5184 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI); 5185 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name); 5186 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName()); 5187 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC); 5188 5189 // We're done with this pattern! It's eligible for GISel emission; return 5190 // it. 5191 ++NumPatternImported; 5192 return std::move(M); 5193 } 5194 5195 return failedImport("Dst pattern root isn't a known leaf"); 5196 } 5197 5198 // Start with the defined operands (i.e., the results of the root operator). 5199 Record *DstOp = Dst->getOperator(); 5200 if (!DstOp->isSubClassOf("Instruction")) 5201 return failedImport("Pattern operator isn't an instruction"); 5202 5203 auto &DstI = Target.getInstruction(DstOp); 5204 StringRef DstIName = DstI.TheDef->getName(); 5205 5206 if (DstI.Operands.NumDefs < Src->getExtTypes().size()) 5207 return failedImport("Src pattern result has more defs than dst MI (" + 5208 to_string(Src->getExtTypes().size()) + " def(s) vs " + 5209 to_string(DstI.Operands.NumDefs) + " def(s))"); 5210 5211 // The root of the match also has constraints on the register bank so that it 5212 // matches the result instruction. 5213 unsigned OpIdx = 0; 5214 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) { 5215 (void)VTy; 5216 5217 const auto &DstIOperand = DstI.Operands[OpIdx]; 5218 Record *DstIOpRec = DstIOperand.Rec; 5219 if (DstIName == "COPY_TO_REGCLASS") { 5220 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue()); 5221 5222 if (DstIOpRec == nullptr) 5223 return failedImport( 5224 "COPY_TO_REGCLASS operand #1 isn't a register class"); 5225 } else if (DstIName == "REG_SEQUENCE") { 5226 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()); 5227 if (DstIOpRec == nullptr) 5228 return failedImport("REG_SEQUENCE operand #0 isn't a register class"); 5229 } else if (DstIName == "EXTRACT_SUBREG") { 5230 auto InferredClass = inferRegClassFromPattern(Dst->getChild(0)); 5231 if (!InferredClass) 5232 return failedImport("Could not infer class for EXTRACT_SUBREG operand #0"); 5233 5234 // We can assume that a subregister is in the same bank as it's super 5235 // register. 5236 DstIOpRec = (*InferredClass)->getDef(); 5237 } else if (DstIName == "INSERT_SUBREG") { 5238 auto MaybeSuperClass = inferSuperRegisterClassForNode( 5239 VTy, Dst->getChild(0), Dst->getChild(2)); 5240 if (!MaybeSuperClass) 5241 return failedImport( 5242 "Cannot infer register class for INSERT_SUBREG operand #0"); 5243 // Move to the next pattern here, because the register class we found 5244 // doesn't necessarily have a record associated with it. So, we can't 5245 // set DstIOpRec using this. 5246 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx); 5247 OM.setSymbolicName(DstIOperand.Name); 5248 M.defineOperand(OM.getSymbolicName(), OM); 5249 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass); 5250 ++OpIdx; 5251 continue; 5252 } else if (DstIName == "SUBREG_TO_REG") { 5253 auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2)); 5254 if (!MaybeRegClass) 5255 return failedImport( 5256 "Cannot infer register class for SUBREG_TO_REG operand #0"); 5257 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx); 5258 OM.setSymbolicName(DstIOperand.Name); 5259 M.defineOperand(OM.getSymbolicName(), OM); 5260 OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass); 5261 ++OpIdx; 5262 continue; 5263 } else if (DstIOpRec->isSubClassOf("RegisterOperand")) 5264 DstIOpRec = DstIOpRec->getValueAsDef("RegClass"); 5265 else if (!DstIOpRec->isSubClassOf("RegisterClass")) 5266 return failedImport("Dst MI def isn't a register class" + 5267 to_string(*Dst)); 5268 5269 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx); 5270 OM.setSymbolicName(DstIOperand.Name); 5271 M.defineOperand(OM.getSymbolicName(), OM); 5272 OM.addPredicate<RegisterBankOperandMatcher>( 5273 Target.getRegisterClass(DstIOpRec)); 5274 ++OpIdx; 5275 } 5276 5277 auto DstMIBuilderOrError = 5278 createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst); 5279 if (auto Error = DstMIBuilderOrError.takeError()) 5280 return std::move(Error); 5281 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get(); 5282 5283 // Render the implicit defs. 5284 // These are only added to the root of the result. 5285 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs())) 5286 return std::move(Error); 5287 5288 DstMIBuilder.chooseInsnToMutate(M); 5289 5290 // Constrain the registers to classes. This is normally derived from the 5291 // emitted instruction but a few instructions require special handling. 5292 if (DstIName == "COPY_TO_REGCLASS") { 5293 // COPY_TO_REGCLASS does not provide operand constraints itself but the 5294 // result is constrained to the class given by the second child. 5295 Record *DstIOpRec = 5296 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue()); 5297 5298 if (DstIOpRec == nullptr) 5299 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class"); 5300 5301 M.addAction<ConstrainOperandToRegClassAction>( 5302 0, 0, Target.getRegisterClass(DstIOpRec)); 5303 5304 // We're done with this pattern! It's eligible for GISel emission; return 5305 // it. 5306 ++NumPatternImported; 5307 return std::move(M); 5308 } 5309 5310 if (DstIName == "EXTRACT_SUBREG") { 5311 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0)); 5312 if (!SuperClass) 5313 return failedImport( 5314 "Cannot infer register class from EXTRACT_SUBREG operand #0"); 5315 5316 auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1)); 5317 if (!SubIdx) 5318 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index"); 5319 5320 // It would be nice to leave this constraint implicit but we're required 5321 // to pick a register class so constrain the result to a register class 5322 // that can hold the correct MVT. 5323 // 5324 // FIXME: This may introduce an extra copy if the chosen class doesn't 5325 // actually contain the subregisters. 5326 assert(Src->getExtTypes().size() == 1 && 5327 "Expected Src of EXTRACT_SUBREG to have one result type"); 5328 5329 const auto SrcRCDstRCPair = 5330 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx); 5331 if (!SrcRCDstRCPair) { 5332 return failedImport("subreg index is incompatible " 5333 "with inferred reg class"); 5334 } 5335 5336 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass"); 5337 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second); 5338 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first); 5339 5340 // We're done with this pattern! It's eligible for GISel emission; return 5341 // it. 5342 ++NumPatternImported; 5343 return std::move(M); 5344 } 5345 5346 if (DstIName == "INSERT_SUBREG") { 5347 assert(Src->getExtTypes().size() == 1 && 5348 "Expected Src of INSERT_SUBREG to have one result type"); 5349 // We need to constrain the destination, a super regsister source, and a 5350 // subregister source. 5351 auto SubClass = inferRegClassFromPattern(Dst->getChild(1)); 5352 if (!SubClass) 5353 return failedImport( 5354 "Cannot infer register class from INSERT_SUBREG operand #1"); 5355 auto SuperClass = inferSuperRegisterClassForNode( 5356 Src->getExtType(0), Dst->getChild(0), Dst->getChild(2)); 5357 if (!SuperClass) 5358 return failedImport( 5359 "Cannot infer register class for INSERT_SUBREG operand #0"); 5360 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass); 5361 M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass); 5362 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass); 5363 ++NumPatternImported; 5364 return std::move(M); 5365 } 5366 5367 if (DstIName == "SUBREG_TO_REG") { 5368 // We need to constrain the destination and subregister source. 5369 assert(Src->getExtTypes().size() == 1 && 5370 "Expected Src of SUBREG_TO_REG to have one result type"); 5371 5372 // Attempt to infer the subregister source from the first child. If it has 5373 // an explicitly given register class, we'll use that. Otherwise, we will 5374 // fail. 5375 auto SubClass = inferRegClassFromPattern(Dst->getChild(1)); 5376 if (!SubClass) 5377 return failedImport( 5378 "Cannot infer register class from SUBREG_TO_REG child #1"); 5379 // We don't have a child to look at that might have a super register node. 5380 auto SuperClass = 5381 inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2)); 5382 if (!SuperClass) 5383 return failedImport( 5384 "Cannot infer register class for SUBREG_TO_REG operand #0"); 5385 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass); 5386 M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass); 5387 ++NumPatternImported; 5388 return std::move(M); 5389 } 5390 5391 if (DstIName == "REG_SEQUENCE") { 5392 auto SuperClass = inferRegClassFromPattern(Dst->getChild(0)); 5393 5394 M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass); 5395 5396 unsigned Num = Dst->getNumChildren(); 5397 for (unsigned I = 1; I != Num; I += 2) { 5398 TreePatternNode *SubRegChild = Dst->getChild(I + 1); 5399 5400 auto SubIdx = inferSubRegIndexForNode(SubRegChild); 5401 if (!SubIdx) 5402 return failedImport("REG_SEQUENCE child is not a subreg index"); 5403 5404 const auto SrcRCDstRCPair = 5405 (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx); 5406 5407 M.addAction<ConstrainOperandToRegClassAction>(0, I, 5408 *SrcRCDstRCPair->second); 5409 } 5410 5411 ++NumPatternImported; 5412 return std::move(M); 5413 } 5414 5415 M.addAction<ConstrainOperandsToDefinitionAction>(0); 5416 5417 // We're done with this pattern! It's eligible for GISel emission; return it. 5418 ++NumPatternImported; 5419 return std::move(M); 5420 } 5421 5422 // Emit imm predicate table and an enum to reference them with. 5423 // The 'Predicate_' part of the name is redundant but eliminating it is more 5424 // trouble than it's worth. 5425 void GlobalISelEmitter::emitCxxPredicateFns( 5426 raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier, 5427 StringRef ArgType, StringRef ArgName, StringRef AdditionalArgs, 5428 StringRef AdditionalDeclarations, 5429 std::function<bool(const Record *R)> Filter) { 5430 std::vector<const Record *> MatchedRecords; 5431 const auto &Defs = RK.getAllDerivedDefinitions("PatFrags"); 5432 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords), 5433 [&](Record *Record) { 5434 return !Record->getValueAsString(CodeFieldName).empty() && 5435 Filter(Record); 5436 }); 5437 5438 if (!MatchedRecords.empty()) { 5439 OS << "// PatFrag predicates.\n" 5440 << "enum {\n"; 5441 std::string EnumeratorSeparator = 5442 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str(); 5443 for (const auto *Record : MatchedRecords) { 5444 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName() 5445 << EnumeratorSeparator; 5446 EnumeratorSeparator = ",\n"; 5447 } 5448 OS << "};\n"; 5449 } 5450 5451 OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName 5452 << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " " 5453 << ArgName << AdditionalArgs <<") const {\n" 5454 << AdditionalDeclarations; 5455 if (!AdditionalDeclarations.empty()) 5456 OS << "\n"; 5457 if (!MatchedRecords.empty()) 5458 OS << " switch (PredicateID) {\n"; 5459 for (const auto *Record : MatchedRecords) { 5460 OS << " case GIPFP_" << TypeIdentifier << "_Predicate_" 5461 << Record->getName() << ": {\n" 5462 << " " << Record->getValueAsString(CodeFieldName) << "\n" 5463 << " llvm_unreachable(\"" << CodeFieldName 5464 << " should have returned\");\n" 5465 << " return false;\n" 5466 << " }\n"; 5467 } 5468 if (!MatchedRecords.empty()) 5469 OS << " }\n"; 5470 OS << " llvm_unreachable(\"Unknown predicate\");\n" 5471 << " return false;\n" 5472 << "}\n"; 5473 } 5474 5475 void GlobalISelEmitter::emitImmPredicateFns( 5476 raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType, 5477 std::function<bool(const Record *R)> Filter) { 5478 return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType, 5479 "Imm", "", "", Filter); 5480 } 5481 5482 void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) { 5483 return emitCxxPredicateFns( 5484 OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI", 5485 ", const std::array<const MachineOperand *, 3> &Operands", 5486 " const MachineFunction &MF = *MI.getParent()->getParent();\n" 5487 " const MachineRegisterInfo &MRI = MF.getRegInfo();\n" 5488 " (void)MRI;", 5489 [](const Record *R) { return true; }); 5490 } 5491 5492 template <class GroupT> 5493 std::vector<Matcher *> GlobalISelEmitter::optimizeRules( 5494 ArrayRef<Matcher *> Rules, 5495 std::vector<std::unique_ptr<Matcher>> &MatcherStorage) { 5496 5497 std::vector<Matcher *> OptRules; 5498 std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>(); 5499 assert(CurrentGroup->empty() && "Newly created group isn't empty!"); 5500 unsigned NumGroups = 0; 5501 5502 auto ProcessCurrentGroup = [&]() { 5503 if (CurrentGroup->empty()) 5504 // An empty group is good to be reused: 5505 return; 5506 5507 // If the group isn't large enough to provide any benefit, move all the 5508 // added rules out of it and make sure to re-create the group to properly 5509 // re-initialize it: 5510 if (CurrentGroup->size() < 2) 5511 append_range(OptRules, CurrentGroup->matchers()); 5512 else { 5513 CurrentGroup->finalize(); 5514 OptRules.push_back(CurrentGroup.get()); 5515 MatcherStorage.emplace_back(std::move(CurrentGroup)); 5516 ++NumGroups; 5517 } 5518 CurrentGroup = std::make_unique<GroupT>(); 5519 }; 5520 for (Matcher *Rule : Rules) { 5521 // Greedily add as many matchers as possible to the current group: 5522 if (CurrentGroup->addMatcher(*Rule)) 5523 continue; 5524 5525 ProcessCurrentGroup(); 5526 assert(CurrentGroup->empty() && "A group wasn't properly re-initialized"); 5527 5528 // Try to add the pending matcher to a newly created empty group: 5529 if (!CurrentGroup->addMatcher(*Rule)) 5530 // If we couldn't add the matcher to an empty group, that group type 5531 // doesn't support that kind of matchers at all, so just skip it: 5532 OptRules.push_back(Rule); 5533 } 5534 ProcessCurrentGroup(); 5535 5536 LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n"); 5537 assert(CurrentGroup->empty() && "The last group wasn't properly processed"); 5538 return OptRules; 5539 } 5540 5541 MatchTable 5542 GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules, 5543 bool Optimize, bool WithCoverage) { 5544 std::vector<Matcher *> InputRules; 5545 for (Matcher &Rule : Rules) 5546 InputRules.push_back(&Rule); 5547 5548 if (!Optimize) 5549 return MatchTable::buildTable(InputRules, WithCoverage); 5550 5551 unsigned CurrentOrdering = 0; 5552 StringMap<unsigned> OpcodeOrder; 5553 for (RuleMatcher &Rule : Rules) { 5554 const StringRef Opcode = Rule.getOpcode(); 5555 assert(!Opcode.empty() && "Didn't expect an undefined opcode"); 5556 if (OpcodeOrder.count(Opcode) == 0) 5557 OpcodeOrder[Opcode] = CurrentOrdering++; 5558 } 5559 5560 llvm::stable_sort(InputRules, [&OpcodeOrder](const Matcher *A, 5561 const Matcher *B) { 5562 auto *L = static_cast<const RuleMatcher *>(A); 5563 auto *R = static_cast<const RuleMatcher *>(B); 5564 return std::make_tuple(OpcodeOrder[L->getOpcode()], L->getNumOperands()) < 5565 std::make_tuple(OpcodeOrder[R->getOpcode()], R->getNumOperands()); 5566 }); 5567 5568 for (Matcher *Rule : InputRules) 5569 Rule->optimize(); 5570 5571 std::vector<std::unique_ptr<Matcher>> MatcherStorage; 5572 std::vector<Matcher *> OptRules = 5573 optimizeRules<GroupMatcher>(InputRules, MatcherStorage); 5574 5575 for (Matcher *Rule : OptRules) 5576 Rule->optimize(); 5577 5578 OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage); 5579 5580 return MatchTable::buildTable(OptRules, WithCoverage); 5581 } 5582 5583 void GroupMatcher::optimize() { 5584 // Make sure we only sort by a specific predicate within a range of rules that 5585 // all have that predicate checked against a specific value (not a wildcard): 5586 auto F = Matchers.begin(); 5587 auto T = F; 5588 auto E = Matchers.end(); 5589 while (T != E) { 5590 while (T != E) { 5591 auto *R = static_cast<RuleMatcher *>(*T); 5592 if (!R->getFirstConditionAsRootType().get().isValid()) 5593 break; 5594 ++T; 5595 } 5596 std::stable_sort(F, T, [](Matcher *A, Matcher *B) { 5597 auto *L = static_cast<RuleMatcher *>(A); 5598 auto *R = static_cast<RuleMatcher *>(B); 5599 return L->getFirstConditionAsRootType() < 5600 R->getFirstConditionAsRootType(); 5601 }); 5602 if (T != E) 5603 F = ++T; 5604 } 5605 GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage) 5606 .swap(Matchers); 5607 GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage) 5608 .swap(Matchers); 5609 } 5610 5611 void GlobalISelEmitter::run(raw_ostream &OS) { 5612 if (!UseCoverageFile.empty()) { 5613 RuleCoverage = CodeGenCoverage(); 5614 auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile); 5615 if (!RuleCoverageBufOrErr) { 5616 PrintWarning(SMLoc(), "Missing rule coverage data"); 5617 RuleCoverage = None; 5618 } else { 5619 if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) { 5620 PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data"); 5621 RuleCoverage = None; 5622 } 5623 } 5624 } 5625 5626 // Track the run-time opcode values 5627 gatherOpcodeValues(); 5628 // Track the run-time LLT ID values 5629 gatherTypeIDValues(); 5630 5631 // Track the GINodeEquiv definitions. 5632 gatherNodeEquivs(); 5633 5634 emitSourceFileHeader(("Global Instruction Selector for the " + 5635 Target.getName() + " target").str(), OS); 5636 std::vector<RuleMatcher> Rules; 5637 // Look through the SelectionDAG patterns we found, possibly emitting some. 5638 for (const PatternToMatch &Pat : CGP.ptms()) { 5639 ++NumPatternTotal; 5640 5641 auto MatcherOrErr = runOnPattern(Pat); 5642 5643 // The pattern analysis can fail, indicating an unsupported pattern. 5644 // Report that if we've been asked to do so. 5645 if (auto Err = MatcherOrErr.takeError()) { 5646 if (WarnOnSkippedPatterns) { 5647 PrintWarning(Pat.getSrcRecord()->getLoc(), 5648 "Skipped pattern: " + toString(std::move(Err))); 5649 } else { 5650 consumeError(std::move(Err)); 5651 } 5652 ++NumPatternImportsSkipped; 5653 continue; 5654 } 5655 5656 if (RuleCoverage) { 5657 if (RuleCoverage->isCovered(MatcherOrErr->getRuleID())) 5658 ++NumPatternsTested; 5659 else 5660 PrintWarning(Pat.getSrcRecord()->getLoc(), 5661 "Pattern is not covered by a test"); 5662 } 5663 Rules.push_back(std::move(MatcherOrErr.get())); 5664 } 5665 5666 // Comparison function to order records by name. 5667 auto orderByName = [](const Record *A, const Record *B) { 5668 return A->getName() < B->getName(); 5669 }; 5670 5671 std::vector<Record *> ComplexPredicates = 5672 RK.getAllDerivedDefinitions("GIComplexOperandMatcher"); 5673 llvm::sort(ComplexPredicates, orderByName); 5674 5675 std::vector<StringRef> CustomRendererFns; 5676 transform(RK.getAllDerivedDefinitions("GICustomOperandRenderer"), 5677 std::back_inserter(CustomRendererFns), [](const auto &Record) { 5678 return Record->getValueAsString("RendererFn"); 5679 }); 5680 // Sort and remove duplicates to get a list of unique renderer functions, in 5681 // case some were mentioned more than once. 5682 llvm::sort(CustomRendererFns); 5683 CustomRendererFns.erase( 5684 std::unique(CustomRendererFns.begin(), CustomRendererFns.end()), 5685 CustomRendererFns.end()); 5686 5687 unsigned MaxTemporaries = 0; 5688 for (const auto &Rule : Rules) 5689 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns()); 5690 5691 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n" 5692 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size() 5693 << ";\n" 5694 << "using PredicateBitset = " 5695 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n" 5696 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n"; 5697 5698 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n" 5699 << " mutable MatcherState State;\n" 5700 << " typedef " 5701 "ComplexRendererFns(" 5702 << Target.getName() 5703 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n" 5704 5705 << " typedef void(" << Target.getName() 5706 << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const " 5707 "MachineInstr &, int) " 5708 "const;\n" 5709 << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, " 5710 "CustomRendererFn> " 5711 "ISelInfo;\n"; 5712 OS << " static " << Target.getName() 5713 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n" 5714 << " static " << Target.getName() 5715 << "InstructionSelector::CustomRendererFn CustomRenderers[];\n" 5716 << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const " 5717 "override;\n" 5718 << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) " 5719 "const override;\n" 5720 << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat " 5721 "&Imm) const override;\n" 5722 << " const int64_t *getMatchTable() const override;\n" 5723 << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI" 5724 ", const std::array<const MachineOperand *, 3> &Operands) " 5725 "const override;\n" 5726 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n"; 5727 5728 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n" 5729 << ", State(" << MaxTemporaries << "),\n" 5730 << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets" 5731 << ", ComplexPredicateFns, CustomRenderers)\n" 5732 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n"; 5733 5734 OS << "#ifdef GET_GLOBALISEL_IMPL\n"; 5735 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures, 5736 OS); 5737 5738 // Separate subtarget features by how often they must be recomputed. 5739 SubtargetFeatureInfoMap ModuleFeatures; 5740 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(), 5741 std::inserter(ModuleFeatures, ModuleFeatures.end()), 5742 [](const SubtargetFeatureInfoMap::value_type &X) { 5743 return !X.second.mustRecomputePerFunction(); 5744 }); 5745 SubtargetFeatureInfoMap FunctionFeatures; 5746 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(), 5747 std::inserter(FunctionFeatures, FunctionFeatures.end()), 5748 [](const SubtargetFeatureInfoMap::value_type &X) { 5749 return X.second.mustRecomputePerFunction(); 5750 }); 5751 5752 SubtargetFeatureInfo::emitComputeAvailableFeatures( 5753 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures", 5754 ModuleFeatures, OS); 5755 5756 5757 OS << "void " << Target.getName() << "InstructionSelector" 5758 "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n" 5759 " AvailableFunctionFeatures = computeAvailableFunctionFeatures(" 5760 "(const " << Target.getName() << "Subtarget *)&MF.getSubtarget(), &MF);\n" 5761 "}\n"; 5762 5763 SubtargetFeatureInfo::emitComputeAvailableFeatures( 5764 Target.getName(), "InstructionSelector", 5765 "computeAvailableFunctionFeatures", FunctionFeatures, OS, 5766 "const MachineFunction *MF"); 5767 5768 // Emit a table containing the LLT objects needed by the matcher and an enum 5769 // for the matcher to reference them with. 5770 std::vector<LLTCodeGen> TypeObjects; 5771 append_range(TypeObjects, KnownTypes); 5772 llvm::sort(TypeObjects); 5773 OS << "// LLT Objects.\n" 5774 << "enum {\n"; 5775 for (const auto &TypeObject : TypeObjects) { 5776 OS << " "; 5777 TypeObject.emitCxxEnumValue(OS); 5778 OS << ",\n"; 5779 } 5780 OS << "};\n"; 5781 OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n" 5782 << "const static LLT TypeObjects[] = {\n"; 5783 for (const auto &TypeObject : TypeObjects) { 5784 OS << " "; 5785 TypeObject.emitCxxConstructorCall(OS); 5786 OS << ",\n"; 5787 } 5788 OS << "};\n\n"; 5789 5790 // Emit a table containing the PredicateBitsets objects needed by the matcher 5791 // and an enum for the matcher to reference them with. 5792 std::vector<std::vector<Record *>> FeatureBitsets; 5793 for (auto &Rule : Rules) 5794 FeatureBitsets.push_back(Rule.getRequiredFeatures()); 5795 llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A, 5796 const std::vector<Record *> &B) { 5797 if (A.size() < B.size()) 5798 return true; 5799 if (A.size() > B.size()) 5800 return false; 5801 for (auto Pair : zip(A, B)) { 5802 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName()) 5803 return true; 5804 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName()) 5805 return false; 5806 } 5807 return false; 5808 }); 5809 FeatureBitsets.erase( 5810 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()), 5811 FeatureBitsets.end()); 5812 OS << "// Feature bitsets.\n" 5813 << "enum {\n" 5814 << " GIFBS_Invalid,\n"; 5815 for (const auto &FeatureBitset : FeatureBitsets) { 5816 if (FeatureBitset.empty()) 5817 continue; 5818 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n"; 5819 } 5820 OS << "};\n" 5821 << "const static PredicateBitset FeatureBitsets[] {\n" 5822 << " {}, // GIFBS_Invalid\n"; 5823 for (const auto &FeatureBitset : FeatureBitsets) { 5824 if (FeatureBitset.empty()) 5825 continue; 5826 OS << " {"; 5827 for (const auto &Feature : FeatureBitset) { 5828 const auto &I = SubtargetFeatures.find(Feature); 5829 assert(I != SubtargetFeatures.end() && "Didn't import predicate?"); 5830 OS << I->second.getEnumBitName() << ", "; 5831 } 5832 OS << "},\n"; 5833 } 5834 OS << "};\n\n"; 5835 5836 // Emit complex predicate table and an enum to reference them with. 5837 OS << "// ComplexPattern predicates.\n" 5838 << "enum {\n" 5839 << " GICP_Invalid,\n"; 5840 for (const auto &Record : ComplexPredicates) 5841 OS << " GICP_" << Record->getName() << ",\n"; 5842 OS << "};\n" 5843 << "// See constructor for table contents\n\n"; 5844 5845 emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) { 5846 bool Unset; 5847 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) && 5848 !R->getValueAsBit("IsAPInt"); 5849 }); 5850 emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) { 5851 bool Unset; 5852 return R->getValueAsBitOrUnset("IsAPFloat", Unset); 5853 }); 5854 emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) { 5855 return R->getValueAsBit("IsAPInt"); 5856 }); 5857 emitMIPredicateFns(OS); 5858 OS << "\n"; 5859 5860 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n" 5861 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n" 5862 << " nullptr, // GICP_Invalid\n"; 5863 for (const auto &Record : ComplexPredicates) 5864 OS << " &" << Target.getName() 5865 << "InstructionSelector::" << Record->getValueAsString("MatcherFn") 5866 << ", // " << Record->getName() << "\n"; 5867 OS << "};\n\n"; 5868 5869 OS << "// Custom renderers.\n" 5870 << "enum {\n" 5871 << " GICR_Invalid,\n"; 5872 for (const auto &Fn : CustomRendererFns) 5873 OS << " GICR_" << Fn << ",\n"; 5874 OS << "};\n"; 5875 5876 OS << Target.getName() << "InstructionSelector::CustomRendererFn\n" 5877 << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n" 5878 << " nullptr, // GICR_Invalid\n"; 5879 for (const auto &Fn : CustomRendererFns) 5880 OS << " &" << Target.getName() << "InstructionSelector::" << Fn << ",\n"; 5881 OS << "};\n\n"; 5882 5883 llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) { 5884 int ScoreA = RuleMatcherScores[A.getRuleID()]; 5885 int ScoreB = RuleMatcherScores[B.getRuleID()]; 5886 if (ScoreA > ScoreB) 5887 return true; 5888 if (ScoreB > ScoreA) 5889 return false; 5890 if (A.isHigherPriorityThan(B)) { 5891 assert(!B.isHigherPriorityThan(A) && "Cannot be more important " 5892 "and less important at " 5893 "the same time"); 5894 return true; 5895 } 5896 return false; 5897 }); 5898 5899 OS << "bool " << Target.getName() 5900 << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage " 5901 "&CoverageInfo) const {\n" 5902 << " MachineFunction &MF = *I.getParent()->getParent();\n" 5903 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n" 5904 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n" 5905 << " NewMIVector OutMIs;\n" 5906 << " State.MIs.clear();\n" 5907 << " State.MIs.push_back(&I);\n\n" 5908 << " if (executeMatchTable(*this, OutMIs, State, ISelInfo" 5909 << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures" 5910 << ", CoverageInfo)) {\n" 5911 << " return true;\n" 5912 << " }\n\n" 5913 << " return false;\n" 5914 << "}\n\n"; 5915 5916 const MatchTable Table = 5917 buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage); 5918 OS << "const int64_t *" << Target.getName() 5919 << "InstructionSelector::getMatchTable() const {\n"; 5920 Table.emitDeclaration(OS); 5921 OS << " return "; 5922 Table.emitUse(OS); 5923 OS << ";\n}\n"; 5924 OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n"; 5925 5926 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n" 5927 << "PredicateBitset AvailableModuleFeatures;\n" 5928 << "mutable PredicateBitset AvailableFunctionFeatures;\n" 5929 << "PredicateBitset getAvailableFeatures() const {\n" 5930 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n" 5931 << "}\n" 5932 << "PredicateBitset\n" 5933 << "computeAvailableModuleFeatures(const " << Target.getName() 5934 << "Subtarget *Subtarget) const;\n" 5935 << "PredicateBitset\n" 5936 << "computeAvailableFunctionFeatures(const " << Target.getName() 5937 << "Subtarget *Subtarget,\n" 5938 << " const MachineFunction *MF) const;\n" 5939 << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n" 5940 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n"; 5941 5942 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n" 5943 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n" 5944 << "AvailableFunctionFeatures()\n" 5945 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n"; 5946 } 5947 5948 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) { 5949 if (SubtargetFeatures.count(Predicate) == 0) 5950 SubtargetFeatures.emplace( 5951 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size())); 5952 } 5953 5954 void RuleMatcher::optimize() { 5955 for (auto &Item : InsnVariableIDs) { 5956 InstructionMatcher &InsnMatcher = *Item.first; 5957 for (auto &OM : InsnMatcher.operands()) { 5958 // Complex Patterns are usually expensive and they relatively rarely fail 5959 // on their own: more often we end up throwing away all the work done by a 5960 // matching part of a complex pattern because some other part of the 5961 // enclosing pattern didn't match. All of this makes it beneficial to 5962 // delay complex patterns until the very end of the rule matching, 5963 // especially for targets having lots of complex patterns. 5964 for (auto &OP : OM->predicates()) 5965 if (isa<ComplexPatternOperandMatcher>(OP)) 5966 EpilogueMatchers.emplace_back(std::move(OP)); 5967 OM->eraseNullPredicates(); 5968 } 5969 InsnMatcher.optimize(); 5970 } 5971 llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L, 5972 const std::unique_ptr<PredicateMatcher> &R) { 5973 return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) < 5974 std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx()); 5975 }); 5976 } 5977 5978 bool RuleMatcher::hasFirstCondition() const { 5979 if (insnmatchers_empty()) 5980 return false; 5981 InstructionMatcher &Matcher = insnmatchers_front(); 5982 if (!Matcher.predicates_empty()) 5983 return true; 5984 for (auto &OM : Matcher.operands()) 5985 for (auto &OP : OM->predicates()) 5986 if (!isa<InstructionOperandMatcher>(OP)) 5987 return true; 5988 return false; 5989 } 5990 5991 const PredicateMatcher &RuleMatcher::getFirstCondition() const { 5992 assert(!insnmatchers_empty() && 5993 "Trying to get a condition from an empty RuleMatcher"); 5994 5995 InstructionMatcher &Matcher = insnmatchers_front(); 5996 if (!Matcher.predicates_empty()) 5997 return **Matcher.predicates_begin(); 5998 // If there is no more predicate on the instruction itself, look at its 5999 // operands. 6000 for (auto &OM : Matcher.operands()) 6001 for (auto &OP : OM->predicates()) 6002 if (!isa<InstructionOperandMatcher>(OP)) 6003 return *OP; 6004 6005 llvm_unreachable("Trying to get a condition from an InstructionMatcher with " 6006 "no conditions"); 6007 } 6008 6009 std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() { 6010 assert(!insnmatchers_empty() && 6011 "Trying to pop a condition from an empty RuleMatcher"); 6012 6013 InstructionMatcher &Matcher = insnmatchers_front(); 6014 if (!Matcher.predicates_empty()) 6015 return Matcher.predicates_pop_front(); 6016 // If there is no more predicate on the instruction itself, look at its 6017 // operands. 6018 for (auto &OM : Matcher.operands()) 6019 for (auto &OP : OM->predicates()) 6020 if (!isa<InstructionOperandMatcher>(OP)) { 6021 std::unique_ptr<PredicateMatcher> Result = std::move(OP); 6022 OM->eraseNullPredicates(); 6023 return Result; 6024 } 6025 6026 llvm_unreachable("Trying to pop a condition from an InstructionMatcher with " 6027 "no conditions"); 6028 } 6029 6030 bool GroupMatcher::candidateConditionMatches( 6031 const PredicateMatcher &Predicate) const { 6032 6033 if (empty()) { 6034 // Sharing predicates for nested instructions is not supported yet as we 6035 // currently don't hoist the GIM_RecordInsn's properly, therefore we can 6036 // only work on the original root instruction (InsnVarID == 0): 6037 if (Predicate.getInsnVarID() != 0) 6038 return false; 6039 // ... otherwise an empty group can handle any predicate with no specific 6040 // requirements: 6041 return true; 6042 } 6043 6044 const Matcher &Representative = **Matchers.begin(); 6045 const auto &RepresentativeCondition = Representative.getFirstCondition(); 6046 // ... if not empty, the group can only accomodate matchers with the exact 6047 // same first condition: 6048 return Predicate.isIdentical(RepresentativeCondition); 6049 } 6050 6051 bool GroupMatcher::addMatcher(Matcher &Candidate) { 6052 if (!Candidate.hasFirstCondition()) 6053 return false; 6054 6055 const PredicateMatcher &Predicate = Candidate.getFirstCondition(); 6056 if (!candidateConditionMatches(Predicate)) 6057 return false; 6058 6059 Matchers.push_back(&Candidate); 6060 return true; 6061 } 6062 6063 void GroupMatcher::finalize() { 6064 assert(Conditions.empty() && "Already finalized?"); 6065 if (empty()) 6066 return; 6067 6068 Matcher &FirstRule = **Matchers.begin(); 6069 for (;;) { 6070 // All the checks are expected to succeed during the first iteration: 6071 for (const auto &Rule : Matchers) 6072 if (!Rule->hasFirstCondition()) 6073 return; 6074 const auto &FirstCondition = FirstRule.getFirstCondition(); 6075 for (unsigned I = 1, E = Matchers.size(); I < E; ++I) 6076 if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition)) 6077 return; 6078 6079 Conditions.push_back(FirstRule.popFirstCondition()); 6080 for (unsigned I = 1, E = Matchers.size(); I < E; ++I) 6081 Matchers[I]->popFirstCondition(); 6082 } 6083 } 6084 6085 void GroupMatcher::emit(MatchTable &Table) { 6086 unsigned LabelID = ~0U; 6087 if (!Conditions.empty()) { 6088 LabelID = Table.allocateLabelID(); 6089 Table << MatchTable::Opcode("GIM_Try", +1) 6090 << MatchTable::Comment("On fail goto") 6091 << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak; 6092 } 6093 for (auto &Condition : Conditions) 6094 Condition->emitPredicateOpcodes( 6095 Table, *static_cast<RuleMatcher *>(*Matchers.begin())); 6096 6097 for (const auto &M : Matchers) 6098 M->emit(Table); 6099 6100 // Exit the group 6101 if (!Conditions.empty()) 6102 Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak 6103 << MatchTable::Label(LabelID); 6104 } 6105 6106 bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) { 6107 return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P); 6108 } 6109 6110 bool SwitchMatcher::candidateConditionMatches( 6111 const PredicateMatcher &Predicate) const { 6112 6113 if (empty()) { 6114 // Sharing predicates for nested instructions is not supported yet as we 6115 // currently don't hoist the GIM_RecordInsn's properly, therefore we can 6116 // only work on the original root instruction (InsnVarID == 0): 6117 if (Predicate.getInsnVarID() != 0) 6118 return false; 6119 // ... while an attempt to add even a root matcher to an empty SwitchMatcher 6120 // could fail as not all the types of conditions are supported: 6121 if (!isSupportedPredicateType(Predicate)) 6122 return false; 6123 // ... or the condition might not have a proper implementation of 6124 // getValue() / isIdenticalDownToValue() yet: 6125 if (!Predicate.hasValue()) 6126 return false; 6127 // ... otherwise an empty Switch can accomodate the condition with no 6128 // further requirements: 6129 return true; 6130 } 6131 6132 const Matcher &CaseRepresentative = **Matchers.begin(); 6133 const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition(); 6134 // Switch-cases must share the same kind of condition and path to the value it 6135 // checks: 6136 if (!Predicate.isIdenticalDownToValue(RepresentativeCondition)) 6137 return false; 6138 6139 const auto Value = Predicate.getValue(); 6140 // ... but be unique with respect to the actual value they check: 6141 return Values.count(Value) == 0; 6142 } 6143 6144 bool SwitchMatcher::addMatcher(Matcher &Candidate) { 6145 if (!Candidate.hasFirstCondition()) 6146 return false; 6147 6148 const PredicateMatcher &Predicate = Candidate.getFirstCondition(); 6149 if (!candidateConditionMatches(Predicate)) 6150 return false; 6151 const auto Value = Predicate.getValue(); 6152 Values.insert(Value); 6153 6154 Matchers.push_back(&Candidate); 6155 return true; 6156 } 6157 6158 void SwitchMatcher::finalize() { 6159 assert(Condition == nullptr && "Already finalized"); 6160 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher"); 6161 if (empty()) 6162 return; 6163 6164 llvm::stable_sort(Matchers, [](const Matcher *L, const Matcher *R) { 6165 return L->getFirstCondition().getValue() < 6166 R->getFirstCondition().getValue(); 6167 }); 6168 Condition = Matchers[0]->popFirstCondition(); 6169 for (unsigned I = 1, E = Values.size(); I < E; ++I) 6170 Matchers[I]->popFirstCondition(); 6171 } 6172 6173 void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P, 6174 MatchTable &Table) { 6175 assert(isSupportedPredicateType(P) && "Predicate type is not supported"); 6176 6177 if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) { 6178 Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI") 6179 << MatchTable::IntValue(Condition->getInsnVarID()); 6180 return; 6181 } 6182 if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) { 6183 Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI") 6184 << MatchTable::IntValue(Condition->getInsnVarID()) 6185 << MatchTable::Comment("Op") 6186 << MatchTable::IntValue(Condition->getOpIdx()); 6187 return; 6188 } 6189 6190 llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a " 6191 "predicate type that is claimed to be supported"); 6192 } 6193 6194 void SwitchMatcher::emit(MatchTable &Table) { 6195 assert(Values.size() == Matchers.size() && "Broken SwitchMatcher"); 6196 if (empty()) 6197 return; 6198 assert(Condition != nullptr && 6199 "Broken SwitchMatcher, hasn't been finalized?"); 6200 6201 std::vector<unsigned> LabelIDs(Values.size()); 6202 std::generate(LabelIDs.begin(), LabelIDs.end(), 6203 [&Table]() { return Table.allocateLabelID(); }); 6204 const unsigned Default = Table.allocateLabelID(); 6205 6206 const int64_t LowerBound = Values.begin()->getRawValue(); 6207 const int64_t UpperBound = Values.rbegin()->getRawValue() + 1; 6208 6209 emitPredicateSpecificOpcodes(*Condition, Table); 6210 6211 Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound) 6212 << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")") 6213 << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default); 6214 6215 int64_t J = LowerBound; 6216 auto VI = Values.begin(); 6217 for (unsigned I = 0, E = Values.size(); I < E; ++I) { 6218 auto V = *VI++; 6219 while (J++ < V.getRawValue()) 6220 Table << MatchTable::IntValue(0); 6221 V.turnIntoComment(); 6222 Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]); 6223 } 6224 Table << MatchTable::LineBreak; 6225 6226 for (unsigned I = 0, E = Values.size(); I < E; ++I) { 6227 Table << MatchTable::Label(LabelIDs[I]); 6228 Matchers[I]->emit(Table); 6229 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak; 6230 } 6231 Table << MatchTable::Label(Default); 6232 } 6233 6234 unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); } 6235 6236 } // end anonymous namespace 6237 6238 //===----------------------------------------------------------------------===// 6239 6240 namespace llvm { 6241 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) { 6242 GlobalISelEmitter(RK).run(OS); 6243 } 6244 } // End llvm namespace 6245