1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 /// \file 11 /// This tablegen backend emits code for use by the GlobalISel instruction 12 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td. 13 /// 14 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen 15 /// backend, filters out the ones that are unsupported, maps 16 /// SelectionDAG-specific constructs to their GlobalISel counterpart 17 /// (when applicable: MVT to LLT; SDNode to generic Instruction). 18 /// 19 /// Not all patterns are supported: pass the tablegen invocation 20 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped, 21 /// as well as why. 22 /// 23 /// The generated file defines a single method: 24 /// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const; 25 /// intended to be used in InstructionSelector::select as the first-step 26 /// selector for the patterns that don't require complex C++. 27 /// 28 /// FIXME: We'll probably want to eventually define a base 29 /// "TargetGenInstructionSelector" class. 30 /// 31 //===----------------------------------------------------------------------===// 32 33 #include "CodeGenDAGPatterns.h" 34 #include "SubtargetFeatureInfo.h" 35 #include "llvm/ADT/Optional.h" 36 #include "llvm/ADT/SmallSet.h" 37 #include "llvm/ADT/Statistic.h" 38 #include "llvm/CodeGen/MachineValueType.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Error.h" 41 #include "llvm/Support/LowLevelTypeImpl.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 <string> 47 #include <numeric> 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(NumPatternEmitted, "Number of patterns emitted"); 56 57 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel"); 58 59 static cl::opt<bool> WarnOnSkippedPatterns( 60 "warn-on-skipped-patterns", 61 cl::desc("Explain why a pattern was skipped for inclusion " 62 "in the GlobalISel selector"), 63 cl::init(false), cl::cat(GlobalISelEmitterCat)); 64 65 namespace { 66 //===- Helper functions ---------------------------------------------------===// 67 68 /// This class stands in for LLT wherever we want to tablegen-erate an 69 /// equivalent at compiler run-time. 70 class LLTCodeGen { 71 private: 72 LLT Ty; 73 74 public: 75 LLTCodeGen(const LLT &Ty) : Ty(Ty) {} 76 77 void emitCxxConstructorCall(raw_ostream &OS) const { 78 if (Ty.isScalar()) { 79 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")"; 80 return; 81 } 82 if (Ty.isVector()) { 83 OS << "LLT::vector(" << Ty.getNumElements() << ", " << Ty.getSizeInBits() 84 << ")"; 85 return; 86 } 87 llvm_unreachable("Unhandled LLT"); 88 } 89 90 const LLT &get() const { return Ty; } 91 }; 92 93 class InstructionMatcher; 94 class OperandPlaceholder { 95 private: 96 enum PlaceholderKind { 97 OP_MatchReference, 98 OP_Temporary, 99 } Kind; 100 101 struct MatchReferenceData { 102 InstructionMatcher *InsnMatcher; 103 StringRef InsnVarName; 104 StringRef SymbolicName; 105 }; 106 107 struct TemporaryData { 108 unsigned OpIdx; 109 }; 110 111 union { 112 struct MatchReferenceData MatchReference; 113 struct TemporaryData Temporary; 114 }; 115 116 OperandPlaceholder(PlaceholderKind Kind) : Kind(Kind) {} 117 118 public: 119 ~OperandPlaceholder() {} 120 121 static OperandPlaceholder 122 CreateMatchReference(InstructionMatcher *InsnMatcher, 123 StringRef InsnVarName, StringRef SymbolicName) { 124 OperandPlaceholder Result(OP_MatchReference); 125 Result.MatchReference.InsnMatcher = InsnMatcher; 126 Result.MatchReference.InsnVarName = InsnVarName; 127 Result.MatchReference.SymbolicName = SymbolicName; 128 return Result; 129 } 130 131 static OperandPlaceholder CreateTemporary(unsigned OpIdx) { 132 OperandPlaceholder Result(OP_Temporary); 133 Result.Temporary.OpIdx = OpIdx; 134 return Result; 135 } 136 137 void emitCxxValueExpr(raw_ostream &OS) const; 138 }; 139 140 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for 141 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...). 142 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) { 143 MVT VT(SVT); 144 if (VT.isVector() && VT.getVectorNumElements() != 1) 145 return LLTCodeGen(LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits())); 146 if (VT.isInteger() || VT.isFloatingPoint()) 147 return LLTCodeGen(LLT::scalar(VT.getSizeInBits())); 148 return None; 149 } 150 151 static std::string explainPredicates(const TreePatternNode *N) { 152 std::string Explanation = ""; 153 StringRef Separator = ""; 154 for (const auto &P : N->getPredicateFns()) { 155 Explanation += 156 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str(); 157 if (P.isAlwaysTrue()) 158 Explanation += " always-true"; 159 if (P.isImmediatePattern()) 160 Explanation += " immediate"; 161 } 162 return Explanation; 163 } 164 165 std::string explainOperator(Record *Operator) { 166 if (Operator->isSubClassOf("SDNode")) 167 return " (" + Operator->getValueAsString("Opcode") + ")"; 168 169 if (Operator->isSubClassOf("Intrinsic")) 170 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str(); 171 172 return " (Operator not understood)"; 173 } 174 175 /// Helper function to let the emitter report skip reason error messages. 176 static Error failedImport(const Twine &Reason) { 177 return make_error<StringError>(Reason, inconvertibleErrorCode()); 178 } 179 180 static Error isTrivialOperatorNode(const TreePatternNode *N) { 181 std::string Explanation = ""; 182 std::string Separator = ""; 183 if (N->isLeaf()) { 184 Explanation = "Is a leaf"; 185 Separator = ", "; 186 } 187 188 if (N->hasAnyPredicate()) { 189 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")"; 190 Separator = ", "; 191 } 192 193 if (N->getTransformFn()) { 194 Explanation += Separator + "Has a transform function"; 195 Separator = ", "; 196 } 197 198 if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn()) 199 return Error::success(); 200 201 return failedImport(Explanation); 202 } 203 204 //===- Matchers -----------------------------------------------------------===// 205 206 class OperandMatcher; 207 class MatchAction; 208 209 /// Generates code to check that a match rule matches. 210 class RuleMatcher { 211 /// A list of matchers that all need to succeed for the current rule to match. 212 /// FIXME: This currently supports a single match position but could be 213 /// extended to support multiple positions to support div/rem fusion or 214 /// load-multiple instructions. 215 std::vector<std::unique_ptr<InstructionMatcher>> Matchers; 216 217 /// A list of actions that need to be taken when all predicates in this rule 218 /// have succeeded. 219 std::vector<std::unique_ptr<MatchAction>> Actions; 220 221 /// A map of instruction matchers to the local variables created by 222 /// emitCxxCaptureStmts(). 223 std::map<const InstructionMatcher *, std::string> InsnVariableNames; 224 225 /// ID for the next instruction variable defined with defineInsnVar() 226 unsigned NextInsnVarID; 227 228 std::vector<Record *> RequiredFeatures; 229 230 public: 231 RuleMatcher() 232 : Matchers(), Actions(), InsnVariableNames(), NextInsnVarID(0) {} 233 RuleMatcher(RuleMatcher &&Other) = default; 234 RuleMatcher &operator=(RuleMatcher &&Other) = default; 235 236 InstructionMatcher &addInstructionMatcher(); 237 void addRequiredFeature(Record *Feature); 238 239 template <class Kind, class... Args> Kind &addAction(Args &&... args); 240 241 std::string defineInsnVar(raw_ostream &OS, const InstructionMatcher &Matcher, 242 StringRef Value); 243 StringRef getInsnVarName(const InstructionMatcher &InsnMatcher) const; 244 245 void emitCxxCapturedInsnList(raw_ostream &OS); 246 void emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr); 247 248 void emit(raw_ostream &OS, 249 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> 250 SubtargetFeatures); 251 252 /// Compare the priority of this object and B. 253 /// 254 /// Returns true if this object is more important than B. 255 bool isHigherPriorityThan(const RuleMatcher &B) const; 256 257 /// Report the maximum number of temporary operands needed by the rule 258 /// matcher. 259 unsigned countTemporaryOperands() const; 260 }; 261 262 template <class PredicateTy> class PredicateListMatcher { 263 private: 264 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec; 265 PredicateVec Predicates; 266 267 public: 268 /// Construct a new operand predicate and add it to the matcher. 269 template <class Kind, class... Args> 270 Kind &addPredicate(Args&&... args) { 271 Predicates.emplace_back( 272 llvm::make_unique<Kind>(std::forward<Args>(args)...)); 273 return *static_cast<Kind *>(Predicates.back().get()); 274 } 275 276 typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); } 277 typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); } 278 iterator_range<typename PredicateVec::const_iterator> predicates() const { 279 return make_range(predicates_begin(), predicates_end()); 280 } 281 typename PredicateVec::size_type predicates_size() const { return Predicates.size(); } 282 283 /// Emit a C++ expression that tests whether all the predicates are met. 284 template <class... Args> 285 void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const { 286 if (Predicates.empty()) { 287 OS << "true"; 288 return; 289 } 290 291 StringRef Separator = ""; 292 for (const auto &Predicate : predicates()) { 293 OS << Separator << "("; 294 Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...); 295 OS << ")"; 296 Separator = " &&\n"; 297 } 298 } 299 }; 300 301 /// Generates code to check a predicate of an operand. 302 /// 303 /// Typical predicates include: 304 /// * Operand is a particular register. 305 /// * Operand is assigned a particular register bank. 306 /// * Operand is an MBB. 307 class OperandPredicateMatcher { 308 public: 309 /// This enum is used for RTTI and also defines the priority that is given to 310 /// the predicate when generating the matcher code. Kinds with higher priority 311 /// must be tested first. 312 /// 313 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter 314 /// but OPM_Int must have priority over OPM_RegBank since constant integers 315 /// are represented by a virtual register defined by a G_CONSTANT instruction. 316 enum PredicateKind { 317 OPM_ComplexPattern, 318 OPM_Instruction, 319 OPM_Int, 320 OPM_LLT, 321 OPM_RegBank, 322 OPM_MBB, 323 }; 324 325 protected: 326 PredicateKind Kind; 327 328 public: 329 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {} 330 virtual ~OperandPredicateMatcher() {} 331 332 PredicateKind getKind() const { return Kind; } 333 334 /// Return the OperandMatcher for the specified operand or nullptr if there 335 /// isn't one by that name in this operand predicate matcher. 336 /// 337 /// InstructionOperandMatcher is the only subclass that can return non-null 338 /// for this. 339 virtual Optional<const OperandMatcher *> 340 getOptionalOperand(StringRef SymbolicName) const { 341 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand"); 342 return None; 343 } 344 345 /// Emit C++ statements to capture instructions into local variables. 346 /// 347 /// Only InstructionOperandMatcher needs to do anything for this method. 348 virtual void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule, 349 StringRef Expr) const {} 350 351 /// Emit a C++ expression that checks the predicate for the given operand. 352 virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 353 StringRef OperandExpr) const = 0; 354 355 /// Compare the priority of this object and B. 356 /// 357 /// Returns true if this object is more important than B. 358 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const { 359 return Kind < B.Kind; 360 }; 361 362 /// Report the maximum number of temporary operands needed by the predicate 363 /// matcher. 364 virtual unsigned countTemporaryOperands() const { return 0; } 365 }; 366 367 /// Generates code to check that an operand is a particular LLT. 368 class LLTOperandMatcher : public OperandPredicateMatcher { 369 protected: 370 LLTCodeGen Ty; 371 372 public: 373 LLTOperandMatcher(const LLTCodeGen &Ty) 374 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {} 375 376 static bool classof(const OperandPredicateMatcher *P) { 377 return P->getKind() == OPM_LLT; 378 } 379 380 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 381 StringRef OperandExpr) const override { 382 OS << "MRI.getType(" << OperandExpr << ".getReg()) == ("; 383 Ty.emitCxxConstructorCall(OS); 384 OS << ")"; 385 } 386 }; 387 388 /// Generates code to check that an operand is a particular target constant. 389 class ComplexPatternOperandMatcher : public OperandPredicateMatcher { 390 protected: 391 const OperandMatcher &Operand; 392 const Record &TheDef; 393 394 unsigned getNumOperands() const { 395 return TheDef.getValueAsDag("Operands")->getNumArgs(); 396 } 397 398 unsigned getAllocatedTemporariesBaseID() const; 399 400 public: 401 ComplexPatternOperandMatcher(const OperandMatcher &Operand, 402 const Record &TheDef) 403 : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand), 404 TheDef(TheDef) {} 405 406 static bool classof(const OperandPredicateMatcher *P) { 407 return P->getKind() == OPM_ComplexPattern; 408 } 409 410 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 411 StringRef OperandExpr) const override { 412 OS << TheDef.getValueAsString("MatcherFn") << "(" << OperandExpr; 413 for (unsigned I = 0; I < getNumOperands(); ++I) { 414 OS << ", "; 415 OperandPlaceholder::CreateTemporary(getAllocatedTemporariesBaseID() + I) 416 .emitCxxValueExpr(OS); 417 } 418 OS << ")"; 419 } 420 421 unsigned countTemporaryOperands() const override { 422 return getNumOperands(); 423 } 424 }; 425 426 /// Generates code to check that an operand is in a particular register bank. 427 class RegisterBankOperandMatcher : public OperandPredicateMatcher { 428 protected: 429 const CodeGenRegisterClass &RC; 430 431 public: 432 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC) 433 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {} 434 435 static bool classof(const OperandPredicateMatcher *P) { 436 return P->getKind() == OPM_RegBank; 437 } 438 439 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 440 StringRef OperandExpr) const override { 441 OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName() 442 << "RegClass) == RBI.getRegBank(" << OperandExpr 443 << ".getReg(), MRI, TRI))"; 444 } 445 }; 446 447 /// Generates code to check that an operand is a basic block. 448 class MBBOperandMatcher : public OperandPredicateMatcher { 449 public: 450 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {} 451 452 static bool classof(const OperandPredicateMatcher *P) { 453 return P->getKind() == OPM_MBB; 454 } 455 456 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 457 StringRef OperandExpr) const override { 458 OS << OperandExpr << ".isMBB()"; 459 } 460 }; 461 462 /// Generates code to check that an operand is a particular int. 463 class IntOperandMatcher : public OperandPredicateMatcher { 464 protected: 465 int64_t Value; 466 467 public: 468 IntOperandMatcher(int64_t Value) 469 : OperandPredicateMatcher(OPM_Int), Value(Value) {} 470 471 static bool classof(const OperandPredicateMatcher *P) { 472 return P->getKind() == OPM_Int; 473 } 474 475 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 476 StringRef OperandExpr) const override { 477 OS << "isOperandImmEqual(" << OperandExpr << ", " << Value << ", MRI)"; 478 } 479 }; 480 481 /// Generates code to check that a set of predicates match for a particular 482 /// operand. 483 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> { 484 protected: 485 InstructionMatcher &Insn; 486 unsigned OpIdx; 487 std::string SymbolicName; 488 489 /// The index of the first temporary variable allocated to this operand. The 490 /// number of allocated temporaries can be found with 491 /// countTemporaryOperands(). 492 unsigned AllocatedTemporariesBaseID; 493 494 public: 495 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx, 496 const std::string &SymbolicName, 497 unsigned AllocatedTemporariesBaseID) 498 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName), 499 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {} 500 501 bool hasSymbolicName() const { return !SymbolicName.empty(); } 502 const StringRef getSymbolicName() const { return SymbolicName; } 503 void setSymbolicName(StringRef Name) { 504 assert(SymbolicName.empty() && "Operand already has a symbolic name"); 505 SymbolicName = Name; 506 } 507 unsigned getOperandIndex() const { return OpIdx; } 508 509 std::string getOperandExpr(StringRef InsnVarName) const { 510 return (InsnVarName + ".getOperand(" + llvm::to_string(OpIdx) + ")").str(); 511 } 512 513 Optional<const OperandMatcher *> 514 getOptionalOperand(StringRef DesiredSymbolicName) const { 515 assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand"); 516 if (DesiredSymbolicName == SymbolicName) 517 return this; 518 for (const auto &OP : predicates()) { 519 const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName); 520 if (MaybeOperand.hasValue()) 521 return MaybeOperand.getValue(); 522 } 523 return None; 524 } 525 526 InstructionMatcher &getInstructionMatcher() const { return Insn; } 527 528 /// Emit C++ statements to capture instructions into local variables. 529 void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule, 530 StringRef OperandExpr) const { 531 for (const auto &Predicate : predicates()) 532 Predicate->emitCxxCaptureStmts(OS, Rule, OperandExpr); 533 } 534 535 /// Emit a C++ expression that tests whether the instruction named in 536 /// InsnVarName matches all the predicate and all the operands. 537 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 538 StringRef InsnVarName) const { 539 OS << "(/* "; 540 if (SymbolicName.empty()) 541 OS << "Operand " << OpIdx; 542 else 543 OS << SymbolicName; 544 OS << " */ "; 545 emitCxxPredicateListExpr(OS, Rule, getOperandExpr(InsnVarName)); 546 OS << ")"; 547 } 548 549 /// Compare the priority of this object and B. 550 /// 551 /// Returns true if this object is more important than B. 552 bool isHigherPriorityThan(const OperandMatcher &B) const { 553 // Operand matchers involving more predicates have higher priority. 554 if (predicates_size() > B.predicates_size()) 555 return true; 556 if (predicates_size() < B.predicates_size()) 557 return false; 558 559 // This assumes that predicates are added in a consistent order. 560 for (const auto &Predicate : zip(predicates(), B.predicates())) { 561 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate))) 562 return true; 563 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate))) 564 return false; 565 } 566 567 return false; 568 }; 569 570 /// Report the maximum number of temporary operands needed by the operand 571 /// matcher. 572 unsigned countTemporaryOperands() const { 573 return std::accumulate( 574 predicates().begin(), predicates().end(), 0, 575 [](unsigned A, 576 const std::unique_ptr<OperandPredicateMatcher> &Predicate) { 577 return A + Predicate->countTemporaryOperands(); 578 }); 579 } 580 581 unsigned getAllocatedTemporariesBaseID() const { 582 return AllocatedTemporariesBaseID; 583 } 584 }; 585 586 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const { 587 return Operand.getAllocatedTemporariesBaseID(); 588 } 589 590 /// Generates code to check a predicate on an instruction. 591 /// 592 /// Typical predicates include: 593 /// * The opcode of the instruction is a particular value. 594 /// * The nsw/nuw flag is/isn't set. 595 class InstructionPredicateMatcher { 596 protected: 597 /// This enum is used for RTTI and also defines the priority that is given to 598 /// the predicate when generating the matcher code. Kinds with higher priority 599 /// must be tested first. 600 enum PredicateKind { 601 IPM_Opcode, 602 }; 603 604 PredicateKind Kind; 605 606 public: 607 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {} 608 virtual ~InstructionPredicateMatcher() {} 609 610 PredicateKind getKind() const { return Kind; } 611 612 /// Emit a C++ expression that tests whether the instruction named in 613 /// InsnVarName matches the predicate. 614 virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 615 StringRef InsnVarName) const = 0; 616 617 /// Compare the priority of this object and B. 618 /// 619 /// Returns true if this object is more important than B. 620 virtual bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const { 621 return Kind < B.Kind; 622 }; 623 624 /// Report the maximum number of temporary operands needed by the predicate 625 /// matcher. 626 virtual unsigned countTemporaryOperands() const { return 0; } 627 }; 628 629 /// Generates code to check the opcode of an instruction. 630 class InstructionOpcodeMatcher : public InstructionPredicateMatcher { 631 protected: 632 const CodeGenInstruction *I; 633 634 public: 635 InstructionOpcodeMatcher(const CodeGenInstruction *I) 636 : InstructionPredicateMatcher(IPM_Opcode), I(I) {} 637 638 static bool classof(const InstructionPredicateMatcher *P) { 639 return P->getKind() == IPM_Opcode; 640 } 641 642 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 643 StringRef InsnVarName) const override { 644 OS << InsnVarName << ".getOpcode() == " << I->Namespace 645 << "::" << I->TheDef->getName(); 646 } 647 648 /// Compare the priority of this object and B. 649 /// 650 /// Returns true if this object is more important than B. 651 bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const override { 652 if (InstructionPredicateMatcher::isHigherPriorityThan(B)) 653 return true; 654 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this)) 655 return false; 656 657 // Prioritize opcodes for cosmetic reasons in the generated source. Although 658 // this is cosmetic at the moment, we may want to drive a similar ordering 659 // using instruction frequency information to improve compile time. 660 if (const InstructionOpcodeMatcher *BO = 661 dyn_cast<InstructionOpcodeMatcher>(&B)) 662 return I->TheDef->getName() < BO->I->TheDef->getName(); 663 664 return false; 665 }; 666 }; 667 668 /// Generates code to check that a set of predicates and operands match for a 669 /// particular instruction. 670 /// 671 /// Typical predicates include: 672 /// * Has a specific opcode. 673 /// * Has an nsw/nuw flag or doesn't. 674 class InstructionMatcher 675 : public PredicateListMatcher<InstructionPredicateMatcher> { 676 protected: 677 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec; 678 679 /// The operands to match. All rendered operands must be present even if the 680 /// condition is always true. 681 OperandVec Operands; 682 683 public: 684 /// Add an operand to the matcher. 685 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName, 686 unsigned AllocatedTemporariesBaseID) { 687 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName, 688 AllocatedTemporariesBaseID)); 689 return *Operands.back(); 690 } 691 692 OperandMatcher &getOperand(unsigned OpIdx) { 693 auto I = std::find_if(Operands.begin(), Operands.end(), 694 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) { 695 return X->getOperandIndex() == OpIdx; 696 }); 697 if (I != Operands.end()) 698 return **I; 699 llvm_unreachable("Failed to lookup operand"); 700 } 701 702 Optional<const OperandMatcher *> 703 getOptionalOperand(StringRef SymbolicName) const { 704 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand"); 705 for (const auto &Operand : Operands) { 706 const auto &OM = Operand->getOptionalOperand(SymbolicName); 707 if (OM.hasValue()) 708 return OM.getValue(); 709 } 710 return None; 711 } 712 713 const OperandMatcher &getOperand(StringRef SymbolicName) const { 714 Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName); 715 if (OM.hasValue()) 716 return *OM.getValue(); 717 llvm_unreachable("Failed to lookup operand"); 718 } 719 720 unsigned getNumOperands() const { return Operands.size(); } 721 OperandVec::iterator operands_begin() { return Operands.begin(); } 722 OperandVec::iterator operands_end() { return Operands.end(); } 723 iterator_range<OperandVec::iterator> operands() { 724 return make_range(operands_begin(), operands_end()); 725 } 726 OperandVec::const_iterator operands_begin() const { return Operands.begin(); } 727 OperandVec::const_iterator operands_end() const { return Operands.end(); } 728 iterator_range<OperandVec::const_iterator> operands() const { 729 return make_range(operands_begin(), operands_end()); 730 } 731 732 /// Emit C++ statements to check the shape of the match and capture 733 /// instructions into local variables. 734 void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule, StringRef Expr) { 735 OS << "if (" << Expr << ".getNumOperands() < " << getNumOperands() << ")\n" 736 << " return false;\n"; 737 for (const auto &Operand : Operands) { 738 Operand->emitCxxCaptureStmts(OS, Rule, Operand->getOperandExpr(Expr)); 739 } 740 } 741 742 /// Emit a C++ expression that tests whether the instruction named in 743 /// InsnVarName matches all the predicates and all the operands. 744 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 745 StringRef InsnVarName) const { 746 emitCxxPredicateListExpr(OS, Rule, InsnVarName); 747 for (const auto &Operand : Operands) { 748 OS << " &&\n("; 749 Operand->emitCxxPredicateExpr(OS, Rule, InsnVarName); 750 OS << ")"; 751 } 752 } 753 754 /// Compare the priority of this object and B. 755 /// 756 /// Returns true if this object is more important than B. 757 bool isHigherPriorityThan(const InstructionMatcher &B) const { 758 // Instruction matchers involving more operands have higher priority. 759 if (Operands.size() > B.Operands.size()) 760 return true; 761 if (Operands.size() < B.Operands.size()) 762 return false; 763 764 for (const auto &Predicate : zip(predicates(), B.predicates())) { 765 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate))) 766 return true; 767 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate))) 768 return false; 769 } 770 771 for (const auto &Operand : zip(Operands, B.Operands)) { 772 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand))) 773 return true; 774 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand))) 775 return false; 776 } 777 778 return false; 779 }; 780 781 /// Report the maximum number of temporary operands needed by the instruction 782 /// matcher. 783 unsigned countTemporaryOperands() const { 784 return std::accumulate(predicates().begin(), predicates().end(), 0, 785 [](unsigned A, 786 const std::unique_ptr<InstructionPredicateMatcher> 787 &Predicate) { 788 return A + Predicate->countTemporaryOperands(); 789 }) + 790 std::accumulate( 791 Operands.begin(), Operands.end(), 0, 792 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) { 793 return A + Operand->countTemporaryOperands(); 794 }); 795 } 796 }; 797 798 /// Generates code to check that the operand is a register defined by an 799 /// instruction that matches the given instruction matcher. 800 /// 801 /// For example, the pattern: 802 /// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3)) 803 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match 804 /// the: 805 /// (G_ADD $src1, $src2) 806 /// subpattern. 807 class InstructionOperandMatcher : public OperandPredicateMatcher { 808 protected: 809 std::unique_ptr<InstructionMatcher> InsnMatcher; 810 811 public: 812 InstructionOperandMatcher() 813 : OperandPredicateMatcher(OPM_Instruction), 814 InsnMatcher(new InstructionMatcher()) {} 815 816 static bool classof(const OperandPredicateMatcher *P) { 817 return P->getKind() == OPM_Instruction; 818 } 819 820 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; } 821 822 Optional<const OperandMatcher *> 823 getOptionalOperand(StringRef SymbolicName) const override { 824 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand"); 825 return InsnMatcher->getOptionalOperand(SymbolicName); 826 } 827 828 void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule, 829 StringRef OperandExpr) const override { 830 OS << "if (!" << OperandExpr + ".isReg())\n" 831 << " return false;\n"; 832 std::string InsnVarName = Rule.defineInsnVar( 833 OS, *InsnMatcher, 834 ("*MRI.getVRegDef(" + OperandExpr + ".getReg())").str()); 835 InsnMatcher->emitCxxCaptureStmts(OS, Rule, InsnVarName); 836 } 837 838 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule, 839 StringRef OperandExpr) const override { 840 OperandExpr = Rule.getInsnVarName(*InsnMatcher); 841 OS << "("; 842 InsnMatcher->emitCxxPredicateExpr(OS, Rule, OperandExpr); 843 OS << ")\n"; 844 } 845 }; 846 847 //===- Actions ------------------------------------------------------------===// 848 void OperandPlaceholder::emitCxxValueExpr(raw_ostream &OS) const { 849 switch (Kind) { 850 case OP_MatchReference: 851 OS << MatchReference.InsnMatcher->getOperand(MatchReference.SymbolicName) 852 .getOperandExpr(MatchReference.InsnVarName); 853 break; 854 case OP_Temporary: 855 OS << "TempOp" << Temporary.OpIdx; 856 break; 857 } 858 } 859 860 class OperandRenderer { 861 public: 862 enum RendererKind { OR_Copy, OR_Imm, OR_Register, OR_ComplexPattern }; 863 864 protected: 865 RendererKind Kind; 866 867 public: 868 OperandRenderer(RendererKind Kind) : Kind(Kind) {} 869 virtual ~OperandRenderer() {} 870 871 RendererKind getKind() const { return Kind; } 872 873 virtual void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const = 0; 874 }; 875 876 /// A CopyRenderer emits code to copy a single operand from an existing 877 /// instruction to the one being built. 878 class CopyRenderer : public OperandRenderer { 879 protected: 880 /// The matcher for the instruction that this operand is copied from. 881 /// This provides the facility for looking up an a operand by it's name so 882 /// that it can be used as a source for the instruction being built. 883 const InstructionMatcher &Matched; 884 /// The name of the operand. 885 const StringRef SymbolicName; 886 887 public: 888 CopyRenderer(const InstructionMatcher &Matched, StringRef SymbolicName) 889 : OperandRenderer(OR_Copy), Matched(Matched), SymbolicName(SymbolicName) { 890 } 891 892 static bool classof(const OperandRenderer *R) { 893 return R->getKind() == OR_Copy; 894 } 895 896 const StringRef getSymbolicName() const { return SymbolicName; } 897 898 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override { 899 const OperandMatcher &Operand = Matched.getOperand(SymbolicName); 900 StringRef InsnVarName = 901 Rule.getInsnVarName(Operand.getInstructionMatcher()); 902 std::string OperandExpr = Operand.getOperandExpr(InsnVarName); 903 OS << " MIB.add(" << OperandExpr << "/*" << SymbolicName << "*/);\n"; 904 } 905 }; 906 907 /// Adds a specific physical register to the instruction being built. 908 /// This is typically useful for WZR/XZR on AArch64. 909 class AddRegisterRenderer : public OperandRenderer { 910 protected: 911 const Record *RegisterDef; 912 913 public: 914 AddRegisterRenderer(const Record *RegisterDef) 915 : OperandRenderer(OR_Register), RegisterDef(RegisterDef) {} 916 917 static bool classof(const OperandRenderer *R) { 918 return R->getKind() == OR_Register; 919 } 920 921 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override { 922 OS << " MIB.addReg(" << RegisterDef->getValueAsString("Namespace") 923 << "::" << RegisterDef->getName() << ");\n"; 924 } 925 }; 926 927 /// Adds a specific immediate to the instruction being built. 928 class ImmRenderer : public OperandRenderer { 929 protected: 930 int64_t Imm; 931 932 public: 933 ImmRenderer(int64_t Imm) 934 : OperandRenderer(OR_Imm), Imm(Imm) {} 935 936 static bool classof(const OperandRenderer *R) { 937 return R->getKind() == OR_Imm; 938 } 939 940 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override { 941 OS << " MIB.addImm(" << Imm << ");\n"; 942 } 943 }; 944 945 class RenderComplexPatternOperand : public OperandRenderer { 946 private: 947 const Record &TheDef; 948 std::vector<OperandPlaceholder> Sources; 949 950 unsigned getNumOperands() const { 951 return TheDef.getValueAsDag("Operands")->getNumArgs(); 952 } 953 954 public: 955 RenderComplexPatternOperand(const Record &TheDef, 956 const ArrayRef<OperandPlaceholder> Sources) 957 : OperandRenderer(OR_ComplexPattern), TheDef(TheDef), Sources(Sources) {} 958 959 static bool classof(const OperandRenderer *R) { 960 return R->getKind() == OR_ComplexPattern; 961 } 962 963 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override { 964 assert(Sources.size() == getNumOperands() && "Inconsistent number of operands"); 965 for (const auto &Source : Sources) { 966 OS << "MIB.add("; 967 Source.emitCxxValueExpr(OS); 968 OS << ");\n"; 969 } 970 } 971 }; 972 973 /// An action taken when all Matcher predicates succeeded for a parent rule. 974 /// 975 /// Typical actions include: 976 /// * Changing the opcode of an instruction. 977 /// * Adding an operand to an instruction. 978 class MatchAction { 979 public: 980 virtual ~MatchAction() {} 981 982 /// Emit the C++ statements to implement the action. 983 /// 984 /// \param RecycleVarName If given, it's an instruction to recycle. The 985 /// requirements on the instruction vary from action to 986 /// action. 987 virtual void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, 988 StringRef RecycleVarName) const = 0; 989 }; 990 991 /// Generates a comment describing the matched rule being acted upon. 992 class DebugCommentAction : public MatchAction { 993 private: 994 const PatternToMatch &P; 995 996 public: 997 DebugCommentAction(const PatternToMatch &P) : P(P) {} 998 999 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, 1000 StringRef RecycleVarName) const override { 1001 OS << "// " << *P.getSrcPattern() << " => " << *P.getDstPattern() << "\n"; 1002 } 1003 }; 1004 1005 /// Generates code to build an instruction or mutate an existing instruction 1006 /// into the desired instruction when this is possible. 1007 class BuildMIAction : public MatchAction { 1008 private: 1009 const CodeGenInstruction *I; 1010 const InstructionMatcher &Matched; 1011 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers; 1012 1013 /// True if the instruction can be built solely by mutating the opcode. 1014 bool canMutate() const { 1015 for (const auto &Renderer : enumerate(OperandRenderers)) { 1016 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) { 1017 if (Matched.getOperand(Copy->getSymbolicName()).getOperandIndex() != 1018 Renderer.index()) 1019 return false; 1020 } else 1021 return false; 1022 } 1023 1024 return true; 1025 } 1026 1027 public: 1028 BuildMIAction(const CodeGenInstruction *I, const InstructionMatcher &Matched) 1029 : I(I), Matched(Matched) {} 1030 1031 template <class Kind, class... Args> 1032 Kind &addRenderer(Args&&... args) { 1033 OperandRenderers.emplace_back( 1034 llvm::make_unique<Kind>(std::forward<Args>(args)...)); 1035 return *static_cast<Kind *>(OperandRenderers.back().get()); 1036 } 1037 1038 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, 1039 StringRef RecycleVarName) const override { 1040 if (canMutate()) { 1041 OS << " " << RecycleVarName << ".setDesc(TII.get(" << I->Namespace 1042 << "::" << I->TheDef->getName() << "));\n"; 1043 1044 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) { 1045 OS << " auto MIB = MachineInstrBuilder(MF, &" << RecycleVarName 1046 << ");\n"; 1047 1048 for (auto Def : I->ImplicitDefs) { 1049 auto Namespace = Def->getValueAsString("Namespace"); 1050 OS << " MIB.addDef(" << Namespace << "::" << Def->getName() 1051 << ", RegState::Implicit);\n"; 1052 } 1053 for (auto Use : I->ImplicitUses) { 1054 auto Namespace = Use->getValueAsString("Namespace"); 1055 OS << " MIB.addUse(" << Namespace << "::" << Use->getName() 1056 << ", RegState::Implicit);\n"; 1057 } 1058 } 1059 1060 OS << " MachineInstr &NewI = " << RecycleVarName << ";\n"; 1061 return; 1062 } 1063 1064 // TODO: Simple permutation looks like it could be almost as common as 1065 // mutation due to commutative operations. 1066 1067 OS << "MachineInstrBuilder MIB = BuildMI(*I.getParent(), I, " 1068 "I.getDebugLoc(), TII.get(" 1069 << I->Namespace << "::" << I->TheDef->getName() << "));\n"; 1070 for (const auto &Renderer : OperandRenderers) 1071 Renderer->emitCxxRenderStmts(OS, Rule); 1072 OS << " for (const auto *FromMI : "; 1073 Rule.emitCxxCapturedInsnList(OS); 1074 OS << ")\n"; 1075 OS << " for (const auto &MMO : FromMI->memoperands())\n"; 1076 OS << " MIB.addMemOperand(MMO);\n"; 1077 OS << " " << RecycleVarName << ".eraseFromParent();\n"; 1078 OS << " MachineInstr &NewI = *MIB;\n"; 1079 } 1080 }; 1081 1082 InstructionMatcher &RuleMatcher::addInstructionMatcher() { 1083 Matchers.emplace_back(new InstructionMatcher()); 1084 return *Matchers.back(); 1085 } 1086 1087 void RuleMatcher::addRequiredFeature(Record *Feature) { 1088 RequiredFeatures.push_back(Feature); 1089 } 1090 1091 template <class Kind, class... Args> 1092 Kind &RuleMatcher::addAction(Args &&... args) { 1093 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...)); 1094 return *static_cast<Kind *>(Actions.back().get()); 1095 } 1096 1097 std::string RuleMatcher::defineInsnVar(raw_ostream &OS, 1098 const InstructionMatcher &Matcher, 1099 StringRef Value) { 1100 std::string InsnVarName = "MI" + llvm::to_string(NextInsnVarID++); 1101 OS << "MachineInstr &" << InsnVarName << " = " << Value << ";\n"; 1102 InsnVariableNames[&Matcher] = InsnVarName; 1103 return InsnVarName; 1104 } 1105 1106 StringRef RuleMatcher::getInsnVarName(const InstructionMatcher &InsnMatcher) const { 1107 const auto &I = InsnVariableNames.find(&InsnMatcher); 1108 if (I != InsnVariableNames.end()) 1109 return I->second; 1110 llvm_unreachable("Matched Insn was not captured in a local variable"); 1111 } 1112 1113 /// Emit a C++ initializer_list containing references to every matched instruction. 1114 void RuleMatcher::emitCxxCapturedInsnList(raw_ostream &OS) { 1115 SmallVector<StringRef, 2> Names; 1116 for (const auto &Pair : InsnVariableNames) 1117 Names.push_back(Pair.second); 1118 std::sort(Names.begin(), Names.end()); 1119 1120 OS << "{"; 1121 for (const auto &Name : Names) 1122 OS << "&" << Name << ", "; 1123 OS << "}"; 1124 } 1125 1126 /// Emit C++ statements to check the shape of the match and capture 1127 /// instructions into local variables. 1128 void RuleMatcher::emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr) { 1129 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet"); 1130 std::string InsnVarName = defineInsnVar(OS, *Matchers.front(), Expr); 1131 Matchers.front()->emitCxxCaptureStmts(OS, *this, InsnVarName); 1132 } 1133 1134 void RuleMatcher::emit(raw_ostream &OS, 1135 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> 1136 SubtargetFeatures) { 1137 if (Matchers.empty()) 1138 llvm_unreachable("Unexpected empty matcher!"); 1139 1140 // The representation supports rules that require multiple roots such as: 1141 // %ptr(p0) = ... 1142 // %elt0(s32) = G_LOAD %ptr 1143 // %1(p0) = G_ADD %ptr, 4 1144 // %elt1(s32) = G_LOAD p0 %1 1145 // which could be usefully folded into: 1146 // %ptr(p0) = ... 1147 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr 1148 // on some targets but we don't need to make use of that yet. 1149 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet"); 1150 1151 OS << "if ("; 1152 OS << "[&]() {\n"; 1153 if (!RequiredFeatures.empty()) { 1154 OS << " PredicateBitset ExpectedFeatures = {"; 1155 StringRef Separator = ""; 1156 for (const auto &Predicate : RequiredFeatures) { 1157 const auto &I = SubtargetFeatures.find(Predicate); 1158 assert(I != SubtargetFeatures.end() && "Didn't import predicate?"); 1159 OS << Separator << I->second.getEnumBitName(); 1160 Separator = ", "; 1161 } 1162 OS << "};\n"; 1163 OS << "if ((AvailableFeatures & ExpectedFeatures) != ExpectedFeatures)\n" 1164 << " return false;\n"; 1165 } 1166 1167 emitCxxCaptureStmts(OS, "I"); 1168 1169 OS << " if ("; 1170 Matchers.front()->emitCxxPredicateExpr(OS, *this, 1171 getInsnVarName(*Matchers.front())); 1172 OS << ") {\n"; 1173 1174 // We must also check if it's safe to fold the matched instructions. 1175 if (InsnVariableNames.size() >= 2) { 1176 for (const auto &Pair : InsnVariableNames) { 1177 // Skip the root node since it isn't moving anywhere. Everything else is 1178 // sinking to meet it. 1179 if (Pair.first == Matchers.front().get()) 1180 continue; 1181 1182 // Reject the difficult cases until we have a more accurate check. 1183 OS << " if (!isObviouslySafeToFold(" << Pair.second 1184 << ")) return false;\n"; 1185 1186 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or 1187 // account for unsafe cases. 1188 // 1189 // Example: 1190 // MI1--> %0 = ... 1191 // %1 = ... %0 1192 // MI0--> %2 = ... %0 1193 // It's not safe to erase MI1. We currently handle this by not 1194 // erasing %0 (even when it's dead). 1195 // 1196 // Example: 1197 // MI1--> %0 = load volatile @a 1198 // %1 = load volatile @a 1199 // MI0--> %2 = ... %0 1200 // It's not safe to sink %0's def past %1. We currently handle 1201 // this by rejecting all loads. 1202 // 1203 // Example: 1204 // MI1--> %0 = load @a 1205 // %1 = store @a 1206 // MI0--> %2 = ... %0 1207 // It's not safe to sink %0's def past %1. We currently handle 1208 // this by rejecting all loads. 1209 // 1210 // Example: 1211 // G_CONDBR %cond, @BB1 1212 // BB0: 1213 // MI1--> %0 = load @a 1214 // G_BR @BB1 1215 // BB1: 1216 // MI0--> %2 = ... %0 1217 // It's not always safe to sink %0 across control flow. In this 1218 // case it may introduce a memory fault. We currentl handle this 1219 // by rejecting all loads. 1220 } 1221 } 1222 1223 for (const auto &MA : Actions) { 1224 MA->emitCxxActionStmts(OS, *this, "I"); 1225 } 1226 1227 OS << " constrainSelectedInstRegOperands(NewI, TII, TRI, RBI);\n"; 1228 OS << " return true;\n"; 1229 OS << " }\n"; 1230 OS << " return false;\n"; 1231 OS << " }()) { return true; }\n\n"; 1232 } 1233 1234 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const { 1235 // Rules involving more match roots have higher priority. 1236 if (Matchers.size() > B.Matchers.size()) 1237 return true; 1238 if (Matchers.size() < B.Matchers.size()) 1239 return false; 1240 1241 for (const auto &Matcher : zip(Matchers, B.Matchers)) { 1242 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher))) 1243 return true; 1244 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher))) 1245 return false; 1246 } 1247 1248 return false; 1249 } 1250 1251 unsigned RuleMatcher::countTemporaryOperands() const { 1252 return std::accumulate( 1253 Matchers.begin(), Matchers.end(), 0, 1254 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) { 1255 return A + Matcher->countTemporaryOperands(); 1256 }); 1257 } 1258 1259 //===- GlobalISelEmitter class --------------------------------------------===// 1260 1261 class GlobalISelEmitter { 1262 public: 1263 explicit GlobalISelEmitter(RecordKeeper &RK); 1264 void run(raw_ostream &OS); 1265 1266 private: 1267 const RecordKeeper &RK; 1268 const CodeGenDAGPatterns CGP; 1269 const CodeGenTarget &Target; 1270 1271 /// Keep track of the equivalence between SDNodes and Instruction. 1272 /// This is defined using 'GINodeEquiv' in the target description. 1273 DenseMap<Record *, const CodeGenInstruction *> NodeEquivs; 1274 1275 /// Keep track of the equivalence between ComplexPattern's and 1276 /// GIComplexOperandMatcher. Map entries are specified by subclassing 1277 /// GIComplexPatternEquiv. 1278 DenseMap<const Record *, const Record *> ComplexPatternEquivs; 1279 1280 // Map of predicates to their subtarget features. 1281 std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures; 1282 1283 void gatherNodeEquivs(); 1284 const CodeGenInstruction *findNodeEquiv(Record *N) const; 1285 1286 Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates); 1287 Expected<InstructionMatcher &> 1288 createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher, 1289 const TreePatternNode *Src) const; 1290 Error importChildMatcher(InstructionMatcher &InsnMatcher, 1291 TreePatternNode *SrcChild, unsigned OpIdx, 1292 unsigned &TempOpIdx) const; 1293 Expected<BuildMIAction &> createAndImportInstructionRenderer( 1294 RuleMatcher &M, const TreePatternNode *Dst, 1295 const InstructionMatcher &InsnMatcher) const; 1296 Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder, 1297 TreePatternNode *DstChild, 1298 const InstructionMatcher &InsnMatcher) const; 1299 Error 1300 importImplicitDefRenderers(BuildMIAction &DstMIBuilder, 1301 const std::vector<Record *> &ImplicitDefs) const; 1302 1303 /// Analyze pattern \p P, returning a matcher for it if possible. 1304 /// Otherwise, return an Error explaining why we don't support it. 1305 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P); 1306 1307 void declareSubtargetFeature(Record *Predicate); 1308 }; 1309 1310 void GlobalISelEmitter::gatherNodeEquivs() { 1311 assert(NodeEquivs.empty()); 1312 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv")) 1313 NodeEquivs[Equiv->getValueAsDef("Node")] = 1314 &Target.getInstruction(Equiv->getValueAsDef("I")); 1315 1316 assert(ComplexPatternEquivs.empty()); 1317 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) { 1318 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent"); 1319 if (!SelDAGEquiv) 1320 continue; 1321 ComplexPatternEquivs[SelDAGEquiv] = Equiv; 1322 } 1323 } 1324 1325 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const { 1326 return NodeEquivs.lookup(N); 1327 } 1328 1329 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK) 1330 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {} 1331 1332 //===- Emitter ------------------------------------------------------------===// 1333 1334 Error 1335 GlobalISelEmitter::importRulePredicates(RuleMatcher &M, 1336 ArrayRef<Init *> Predicates) { 1337 for (const Init *Predicate : Predicates) { 1338 const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate); 1339 declareSubtargetFeature(PredicateDef->getDef()); 1340 M.addRequiredFeature(PredicateDef->getDef()); 1341 } 1342 1343 return Error::success(); 1344 } 1345 1346 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher( 1347 InstructionMatcher &InsnMatcher, const TreePatternNode *Src) const { 1348 // Start with the defined operands (i.e., the results of the root operator). 1349 if (Src->getExtTypes().size() > 1) 1350 return failedImport("Src pattern has multiple results"); 1351 1352 auto SrcGIOrNull = findNodeEquiv(Src->getOperator()); 1353 if (!SrcGIOrNull) 1354 return failedImport("Pattern operator lacks an equivalent Instruction" + 1355 explainOperator(Src->getOperator())); 1356 auto &SrcGI = *SrcGIOrNull; 1357 1358 // The operators look good: match the opcode and mutate it to the new one. 1359 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI); 1360 1361 unsigned OpIdx = 0; 1362 unsigned TempOpIdx = 0; 1363 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) { 1364 auto OpTyOrNone = MVTToLLT(Ty.getConcrete()); 1365 1366 if (!OpTyOrNone) 1367 return failedImport( 1368 "Result of Src pattern operator has an unsupported type"); 1369 1370 // Results don't have a name unless they are the root node. The caller will 1371 // set the name if appropriate. 1372 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx); 1373 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone); 1374 } 1375 1376 // Match the used operands (i.e. the children of the operator). 1377 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) { 1378 if (auto Error = importChildMatcher(InsnMatcher, Src->getChild(i), OpIdx++, 1379 TempOpIdx)) 1380 return std::move(Error); 1381 } 1382 1383 return InsnMatcher; 1384 } 1385 1386 Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher, 1387 TreePatternNode *SrcChild, 1388 unsigned OpIdx, 1389 unsigned &TempOpIdx) const { 1390 OperandMatcher &OM = 1391 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx); 1392 1393 if (SrcChild->hasAnyPredicate()) 1394 return failedImport("Src pattern child has predicate (" + 1395 explainPredicates(SrcChild) + ")"); 1396 1397 ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes(); 1398 if (ChildTypes.size() != 1) 1399 return failedImport("Src pattern child has multiple results"); 1400 1401 // Check MBB's before the type check since they are not a known type. 1402 if (!SrcChild->isLeaf()) { 1403 if (SrcChild->getOperator()->isSubClassOf("SDNode")) { 1404 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator()); 1405 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { 1406 OM.addPredicate<MBBOperandMatcher>(); 1407 return Error::success(); 1408 } 1409 } 1410 } 1411 1412 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete()); 1413 if (!OpTyOrNone) 1414 return failedImport("Src operand has an unsupported type"); 1415 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone); 1416 1417 // Check for nested instructions. 1418 if (!SrcChild->isLeaf()) { 1419 // Map the node to a gMIR instruction. 1420 InstructionOperandMatcher &InsnOperand = 1421 OM.addPredicate<InstructionOperandMatcher>(); 1422 auto InsnMatcherOrError = 1423 createAndImportSelDAGMatcher(InsnOperand.getInsnMatcher(), SrcChild); 1424 if (auto Error = InsnMatcherOrError.takeError()) 1425 return Error; 1426 1427 return Error::success(); 1428 } 1429 1430 // Check for constant immediates. 1431 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) { 1432 OM.addPredicate<IntOperandMatcher>(ChildInt->getValue()); 1433 return Error::success(); 1434 } 1435 1436 // Check for def's like register classes or ComplexPattern's. 1437 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) { 1438 auto *ChildRec = ChildDefInit->getDef(); 1439 1440 // Check for register classes. 1441 if (ChildRec->isSubClassOf("RegisterClass")) { 1442 OM.addPredicate<RegisterBankOperandMatcher>( 1443 Target.getRegisterClass(ChildRec)); 1444 return Error::success(); 1445 } 1446 1447 // Check for ComplexPattern's. 1448 if (ChildRec->isSubClassOf("ComplexPattern")) { 1449 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec); 1450 if (ComplexPattern == ComplexPatternEquivs.end()) 1451 return failedImport("SelectionDAG ComplexPattern (" + 1452 ChildRec->getName() + ") not mapped to GlobalISel"); 1453 1454 const auto &Predicate = OM.addPredicate<ComplexPatternOperandMatcher>( 1455 OM, *ComplexPattern->second); 1456 TempOpIdx += Predicate.countTemporaryOperands(); 1457 return Error::success(); 1458 } 1459 1460 if (ChildRec->isSubClassOf("ImmLeaf")) { 1461 return failedImport( 1462 "Src pattern child def is an unsupported tablegen class (ImmLeaf)"); 1463 } 1464 1465 return failedImport( 1466 "Src pattern child def is an unsupported tablegen class"); 1467 } 1468 1469 return failedImport("Src pattern child is an unsupported kind"); 1470 } 1471 1472 Error GlobalISelEmitter::importExplicitUseRenderer( 1473 BuildMIAction &DstMIBuilder, TreePatternNode *DstChild, 1474 const InstructionMatcher &InsnMatcher) const { 1475 // The only non-leaf child we accept is 'bb': it's an operator because 1476 // BasicBlockSDNode isn't inline, but in MI it's just another operand. 1477 if (!DstChild->isLeaf()) { 1478 if (DstChild->getOperator()->isSubClassOf("SDNode")) { 1479 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator()); 1480 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { 1481 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, 1482 DstChild->getName()); 1483 return Error::success(); 1484 } 1485 } 1486 return failedImport("Dst pattern child isn't a leaf node or an MBB"); 1487 } 1488 1489 // Otherwise, we're looking for a bog-standard RegisterClass operand. 1490 if (DstChild->hasAnyPredicate()) 1491 return failedImport("Dst pattern child has predicate (" + 1492 explainPredicates(DstChild) + ")"); 1493 1494 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) { 1495 auto *ChildRec = ChildDefInit->getDef(); 1496 1497 ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes(); 1498 if (ChildTypes.size() != 1) 1499 return failedImport("Dst pattern child has multiple results"); 1500 1501 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete()); 1502 if (!OpTyOrNone) 1503 return failedImport("Dst operand has an unsupported type"); 1504 1505 if (ChildRec->isSubClassOf("Register")) { 1506 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec); 1507 return Error::success(); 1508 } 1509 1510 if (ChildRec->isSubClassOf("RegisterClass")) { 1511 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstChild->getName()); 1512 return Error::success(); 1513 } 1514 1515 if (ChildRec->isSubClassOf("ComplexPattern")) { 1516 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec); 1517 if (ComplexPattern == ComplexPatternEquivs.end()) 1518 return failedImport( 1519 "SelectionDAG ComplexPattern not mapped to GlobalISel"); 1520 1521 SmallVector<OperandPlaceholder, 2> RenderedOperands; 1522 const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName()); 1523 for (unsigned I = 0; I < OM.countTemporaryOperands(); ++I) 1524 RenderedOperands.push_back(OperandPlaceholder::CreateTemporary( 1525 OM.getAllocatedTemporariesBaseID() + I)); 1526 DstMIBuilder.addRenderer<RenderComplexPatternOperand>( 1527 *ComplexPattern->second, RenderedOperands); 1528 return Error::success(); 1529 } 1530 1531 if (ChildRec->isSubClassOf("SDNodeXForm")) 1532 return failedImport("Dst pattern child def is an unsupported tablegen " 1533 "class (SDNodeXForm)"); 1534 1535 return failedImport( 1536 "Dst pattern child def is an unsupported tablegen class"); 1537 } 1538 1539 return failedImport("Dst pattern child is an unsupported kind"); 1540 } 1541 1542 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer( 1543 RuleMatcher &M, const TreePatternNode *Dst, 1544 const InstructionMatcher &InsnMatcher) const { 1545 Record *DstOp = Dst->getOperator(); 1546 if (!DstOp->isSubClassOf("Instruction")) { 1547 if (DstOp->isSubClassOf("ValueType")) 1548 return failedImport( 1549 "Pattern operator isn't an instruction (it's a ValueType)"); 1550 return failedImport("Pattern operator isn't an instruction"); 1551 } 1552 auto &DstI = Target.getInstruction(DstOp); 1553 1554 auto &DstMIBuilder = M.addAction<BuildMIAction>(&DstI, InsnMatcher); 1555 1556 // Render the explicit defs. 1557 for (unsigned I = 0; I < DstI.Operands.NumDefs; ++I) { 1558 const auto &DstIOperand = DstI.Operands[I]; 1559 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstIOperand.Name); 1560 } 1561 1562 // Figure out which operands need defaults inserted. Operands that subclass 1563 // OperandWithDefaultOps are considered from left to right until we have 1564 // enough operands to render the instruction. 1565 SmallSet<unsigned, 2> DefaultOperands; 1566 unsigned DstINumUses = DstI.Operands.size() - DstI.Operands.NumDefs; 1567 unsigned NumDefaultOperands = 0; 1568 for (unsigned I = 0; I < DstINumUses && 1569 DstINumUses > Dst->getNumChildren() + NumDefaultOperands; 1570 ++I) { 1571 const auto &DstIOperand = DstI.Operands[DstI.Operands.NumDefs + I]; 1572 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) { 1573 DefaultOperands.insert(I); 1574 NumDefaultOperands += 1575 DstIOperand.Rec->getValueAsDag("DefaultOps")->getNumArgs(); 1576 } 1577 } 1578 if (DstINumUses > Dst->getNumChildren() + DefaultOperands.size()) 1579 return failedImport("Insufficient operands supplied and default ops " 1580 "couldn't make up the shortfall"); 1581 if (DstINumUses < Dst->getNumChildren() + DefaultOperands.size()) 1582 return failedImport("Too many operands supplied"); 1583 1584 // Render the explicit uses. 1585 unsigned Child = 0; 1586 for (unsigned I = 0; I != DstINumUses; ++I) { 1587 // If we need to insert default ops here, then do so. 1588 if (DefaultOperands.count(I)) { 1589 const auto &DstIOperand = DstI.Operands[DstI.Operands.NumDefs + I]; 1590 1591 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps"); 1592 for (const auto *DefaultOp : DefaultOps->args()) { 1593 // Look through ValueType operators. 1594 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) { 1595 if (const DefInit *DefaultDagOperator = 1596 dyn_cast<DefInit>(DefaultDagOp->getOperator())) { 1597 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) 1598 DefaultOp = DefaultDagOp->getArg(0); 1599 } 1600 } 1601 1602 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) { 1603 DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef()); 1604 continue; 1605 } 1606 1607 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) { 1608 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue()); 1609 continue; 1610 } 1611 1612 return failedImport("Could not add default op"); 1613 } 1614 1615 continue; 1616 } 1617 1618 if (auto Error = importExplicitUseRenderer( 1619 DstMIBuilder, Dst->getChild(Child), InsnMatcher)) 1620 return std::move(Error); 1621 ++Child; 1622 } 1623 1624 return DstMIBuilder; 1625 } 1626 1627 Error GlobalISelEmitter::importImplicitDefRenderers( 1628 BuildMIAction &DstMIBuilder, 1629 const std::vector<Record *> &ImplicitDefs) const { 1630 if (!ImplicitDefs.empty()) 1631 return failedImport("Pattern defines a physical register"); 1632 return Error::success(); 1633 } 1634 1635 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) { 1636 // Keep track of the matchers and actions to emit. 1637 RuleMatcher M; 1638 M.addAction<DebugCommentAction>(P); 1639 1640 if (auto Error = importRulePredicates(M, P.getPredicates()->getValues())) 1641 return std::move(Error); 1642 1643 // Next, analyze the pattern operators. 1644 TreePatternNode *Src = P.getSrcPattern(); 1645 TreePatternNode *Dst = P.getDstPattern(); 1646 1647 // If the root of either pattern isn't a simple operator, ignore it. 1648 if (auto Err = isTrivialOperatorNode(Dst)) 1649 return failedImport("Dst pattern root isn't a trivial operator (" + 1650 toString(std::move(Err)) + ")"); 1651 if (auto Err = isTrivialOperatorNode(Src)) 1652 return failedImport("Src pattern root isn't a trivial operator (" + 1653 toString(std::move(Err)) + ")"); 1654 1655 // Start with the defined operands (i.e., the results of the root operator). 1656 Record *DstOp = Dst->getOperator(); 1657 if (!DstOp->isSubClassOf("Instruction")) 1658 return failedImport("Pattern operator isn't an instruction"); 1659 1660 auto &DstI = Target.getInstruction(DstOp); 1661 if (DstI.Operands.NumDefs != Src->getExtTypes().size()) 1662 return failedImport("Src pattern results and dst MI defs are different (" + 1663 to_string(Src->getExtTypes().size()) + " def(s) vs " + 1664 to_string(DstI.Operands.NumDefs) + " def(s))"); 1665 1666 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(); 1667 auto InsnMatcherOrError = createAndImportSelDAGMatcher(InsnMatcherTemp, Src); 1668 if (auto Error = InsnMatcherOrError.takeError()) 1669 return std::move(Error); 1670 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get(); 1671 1672 // The root of the match also has constraints on the register bank so that it 1673 // matches the result instruction. 1674 unsigned OpIdx = 0; 1675 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) { 1676 (void)Ty; 1677 1678 const auto &DstIOperand = DstI.Operands[OpIdx]; 1679 Record *DstIOpRec = DstIOperand.Rec; 1680 if (!DstIOpRec->isSubClassOf("RegisterClass")) 1681 return failedImport("Dst MI def isn't a register class"); 1682 1683 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx); 1684 OM.setSymbolicName(DstIOperand.Name); 1685 OM.addPredicate<RegisterBankOperandMatcher>( 1686 Target.getRegisterClass(DstIOpRec)); 1687 ++OpIdx; 1688 } 1689 1690 auto DstMIBuilderOrError = 1691 createAndImportInstructionRenderer(M, Dst, InsnMatcher); 1692 if (auto Error = DstMIBuilderOrError.takeError()) 1693 return std::move(Error); 1694 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get(); 1695 1696 // Render the implicit defs. 1697 // These are only added to the root of the result. 1698 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs())) 1699 return std::move(Error); 1700 1701 // We're done with this pattern! It's eligible for GISel emission; return it. 1702 ++NumPatternImported; 1703 return std::move(M); 1704 } 1705 1706 void GlobalISelEmitter::run(raw_ostream &OS) { 1707 // Track the GINodeEquiv definitions. 1708 gatherNodeEquivs(); 1709 1710 emitSourceFileHeader(("Global Instruction Selector for the " + 1711 Target.getName() + " target").str(), OS); 1712 std::vector<RuleMatcher> Rules; 1713 // Look through the SelectionDAG patterns we found, possibly emitting some. 1714 for (const PatternToMatch &Pat : CGP.ptms()) { 1715 ++NumPatternTotal; 1716 auto MatcherOrErr = runOnPattern(Pat); 1717 1718 // The pattern analysis can fail, indicating an unsupported pattern. 1719 // Report that if we've been asked to do so. 1720 if (auto Err = MatcherOrErr.takeError()) { 1721 if (WarnOnSkippedPatterns) { 1722 PrintWarning(Pat.getSrcRecord()->getLoc(), 1723 "Skipped pattern: " + toString(std::move(Err))); 1724 } else { 1725 consumeError(std::move(Err)); 1726 } 1727 ++NumPatternImportsSkipped; 1728 continue; 1729 } 1730 1731 Rules.push_back(std::move(MatcherOrErr.get())); 1732 } 1733 1734 std::stable_sort(Rules.begin(), Rules.end(), 1735 [&](const RuleMatcher &A, const RuleMatcher &B) { 1736 if (A.isHigherPriorityThan(B)) { 1737 assert(!B.isHigherPriorityThan(A) && "Cannot be more important " 1738 "and less important at " 1739 "the same time"); 1740 return true; 1741 } 1742 return false; 1743 }); 1744 1745 unsigned MaxTemporaries = 0; 1746 for (const auto &Rule : Rules) 1747 MaxTemporaries = std::max(MaxTemporaries, Rule.countTemporaryOperands()); 1748 1749 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n" 1750 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size() 1751 << ";\n" 1752 << "using PredicateBitset = " 1753 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n" 1754 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n"; 1755 1756 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"; 1757 for (unsigned I = 0; I < MaxTemporaries; ++I) 1758 OS << " mutable MachineOperand TempOp" << I << ";\n"; 1759 OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n"; 1760 1761 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"; 1762 for (unsigned I = 0; I < MaxTemporaries; ++I) 1763 OS << ", TempOp" << I << "(MachineOperand::CreatePlaceholder())\n"; 1764 OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n"; 1765 1766 OS << "#ifdef GET_GLOBALISEL_IMPL\n"; 1767 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures, 1768 OS); 1769 SubtargetFeatureInfo::emitNameTable(SubtargetFeatures, OS); 1770 SubtargetFeatureInfo::emitComputeAvailableFeatures( 1771 Target.getName(), "InstructionSelector", "computeAvailableFeatures", 1772 SubtargetFeatures, OS); 1773 1774 OS << "bool " << Target.getName() 1775 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n" 1776 << " MachineFunction &MF = *I.getParent()->getParent();\n" 1777 << " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"; 1778 1779 for (auto &Rule : Rules) { 1780 Rule.emit(OS, SubtargetFeatures); 1781 ++NumPatternEmitted; 1782 } 1783 1784 OS << " return false;\n" 1785 << "}\n" 1786 << "#endif // ifdef GET_GLOBALISEL_IMPL\n"; 1787 } 1788 1789 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) { 1790 if (SubtargetFeatures.count(Predicate) == 0) 1791 SubtargetFeatures.emplace( 1792 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size())); 1793 } 1794 1795 } // end anonymous namespace 1796 1797 //===----------------------------------------------------------------------===// 1798 1799 namespace llvm { 1800 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) { 1801 GlobalISelEmitter(RK).run(OS); 1802 } 1803 } // End llvm namespace 1804