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 /// A unique identifier for a MatchTable. 57 static unsigned CurrentMatchTableID = 0; 58 59 cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel"); 60 61 static cl::opt<bool> WarnOnSkippedPatterns( 62 "warn-on-skipped-patterns", 63 cl::desc("Explain why a pattern was skipped for inclusion " 64 "in the GlobalISel selector"), 65 cl::init(false), cl::cat(GlobalISelEmitterCat)); 66 67 namespace { 68 //===- Helper functions ---------------------------------------------------===// 69 70 /// This class stands in for LLT wherever we want to tablegen-erate an 71 /// equivalent at compiler run-time. 72 class LLTCodeGen { 73 private: 74 LLT Ty; 75 76 public: 77 LLTCodeGen(const LLT &Ty) : Ty(Ty) {} 78 79 void emitCxxEnumValue(raw_ostream &OS) const { 80 if (Ty.isScalar()) { 81 OS << "GILLT_s" << Ty.getSizeInBits(); 82 return; 83 } 84 if (Ty.isVector()) { 85 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits(); 86 return; 87 } 88 llvm_unreachable("Unhandled LLT"); 89 } 90 91 void emitCxxConstructorCall(raw_ostream &OS) const { 92 if (Ty.isScalar()) { 93 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")"; 94 return; 95 } 96 if (Ty.isVector()) { 97 OS << "LLT::vector(" << Ty.getNumElements() << ", " 98 << Ty.getScalarSizeInBits() << ")"; 99 return; 100 } 101 llvm_unreachable("Unhandled LLT"); 102 } 103 104 const LLT &get() const { return Ty; } 105 106 /// This ordering is used for std::unique() and std::sort(). There's no 107 /// particular logic behind the order. 108 bool operator<(const LLTCodeGen &Other) const { 109 if (!Ty.isValid()) 110 return Other.Ty.isValid(); 111 if (Ty.isScalar()) { 112 if (!Other.Ty.isValid()) 113 return false; 114 if (Other.Ty.isScalar()) 115 return Ty.getSizeInBits() < Other.Ty.getSizeInBits(); 116 return false; 117 } 118 if (Ty.isVector()) { 119 if (!Other.Ty.isValid() || Other.Ty.isScalar()) 120 return false; 121 if (Other.Ty.isVector()) { 122 if (Ty.getNumElements() < Other.Ty.getNumElements()) 123 return true; 124 if (Ty.getNumElements() > Other.Ty.getNumElements()) 125 return false; 126 return Ty.getSizeInBits() < Other.Ty.getSizeInBits(); 127 } 128 return false; 129 } 130 llvm_unreachable("Unhandled LLT"); 131 } 132 }; 133 134 class InstructionMatcher; 135 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for 136 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...). 137 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) { 138 MVT VT(SVT); 139 if (VT.isVector() && VT.getVectorNumElements() != 1) 140 return LLTCodeGen( 141 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits())); 142 if (VT.isInteger() || VT.isFloatingPoint()) 143 return LLTCodeGen(LLT::scalar(VT.getSizeInBits())); 144 return None; 145 } 146 147 static std::string explainPredicates(const TreePatternNode *N) { 148 std::string Explanation = ""; 149 StringRef Separator = ""; 150 for (const auto &P : N->getPredicateFns()) { 151 Explanation += 152 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str(); 153 if (P.isAlwaysTrue()) 154 Explanation += " always-true"; 155 if (P.isImmediatePattern()) 156 Explanation += " immediate"; 157 } 158 return Explanation; 159 } 160 161 std::string explainOperator(Record *Operator) { 162 if (Operator->isSubClassOf("SDNode")) 163 return (" (" + Operator->getValueAsString("Opcode") + ")").str(); 164 165 if (Operator->isSubClassOf("Intrinsic")) 166 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str(); 167 168 return " (Operator not understood)"; 169 } 170 171 /// Helper function to let the emitter report skip reason error messages. 172 static Error failedImport(const Twine &Reason) { 173 return make_error<StringError>(Reason, inconvertibleErrorCode()); 174 } 175 176 static Error isTrivialOperatorNode(const TreePatternNode *N) { 177 std::string Explanation = ""; 178 std::string Separator = ""; 179 if (N->isLeaf()) { 180 if (isa<IntInit>(N->getLeafValue())) 181 return Error::success(); 182 183 Explanation = "Is a leaf"; 184 Separator = ", "; 185 } 186 187 if (N->hasAnyPredicate()) { 188 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")"; 189 Separator = ", "; 190 } 191 192 if (N->getTransformFn()) { 193 Explanation += Separator + "Has a transform function"; 194 Separator = ", "; 195 } 196 197 if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn()) 198 return Error::success(); 199 200 return failedImport(Explanation); 201 } 202 203 static Record *getInitValueAsRegClass(Init *V) { 204 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) { 205 if (VDefInit->getDef()->isSubClassOf("RegisterOperand")) 206 return VDefInit->getDef()->getValueAsDef("RegClass"); 207 if (VDefInit->getDef()->isSubClassOf("RegisterClass")) 208 return VDefInit->getDef(); 209 } 210 return nullptr; 211 } 212 213 std::string 214 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) { 215 std::string Name = "GIFBS"; 216 for (const auto &Feature : FeatureBitset) 217 Name += ("_" + Feature->getName()).str(); 218 return Name; 219 } 220 //===- Matchers -----------------------------------------------------------===// 221 222 class OperandMatcher; 223 class MatchAction; 224 225 /// Generates code to check that a match rule matches. 226 class RuleMatcher { 227 /// A list of matchers that all need to succeed for the current rule to match. 228 /// FIXME: This currently supports a single match position but could be 229 /// extended to support multiple positions to support div/rem fusion or 230 /// load-multiple instructions. 231 std::vector<std::unique_ptr<InstructionMatcher>> Matchers; 232 233 /// A list of actions that need to be taken when all predicates in this rule 234 /// have succeeded. 235 std::vector<std::unique_ptr<MatchAction>> Actions; 236 237 /// A map of instruction matchers to the local variables created by 238 /// emitCaptureOpcodes(). 239 std::map<const InstructionMatcher *, unsigned> InsnVariableIDs; 240 241 /// ID for the next instruction variable defined with defineInsnVar() 242 unsigned NextInsnVarID; 243 244 std::vector<Record *> RequiredFeatures; 245 246 public: 247 RuleMatcher() 248 : Matchers(), Actions(), InsnVariableIDs(), NextInsnVarID(0) {} 249 RuleMatcher(RuleMatcher &&Other) = default; 250 RuleMatcher &operator=(RuleMatcher &&Other) = default; 251 252 InstructionMatcher &addInstructionMatcher(); 253 void addRequiredFeature(Record *Feature); 254 const std::vector<Record *> &getRequiredFeatures() const; 255 256 template <class Kind, class... Args> Kind &addAction(Args &&... args); 257 258 /// Define an instruction without emitting any code to do so. 259 /// This is used for the root of the match. 260 unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher); 261 /// Define an instruction and emit corresponding state-machine opcodes. 262 unsigned defineInsnVar(raw_ostream &OS, const InstructionMatcher &Matcher, 263 unsigned InsnVarID, unsigned OpIdx); 264 unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const; 265 266 void emitCaptureOpcodes(raw_ostream &OS); 267 268 void emit(raw_ostream &OS); 269 270 /// Compare the priority of this object and B. 271 /// 272 /// Returns true if this object is more important than B. 273 bool isHigherPriorityThan(const RuleMatcher &B) const; 274 275 /// Report the maximum number of temporary operands needed by the rule 276 /// matcher. 277 unsigned countRendererFns() const; 278 279 // FIXME: Remove this as soon as possible 280 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); } 281 }; 282 283 template <class PredicateTy> class PredicateListMatcher { 284 private: 285 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec; 286 PredicateVec Predicates; 287 288 public: 289 /// Construct a new operand predicate and add it to the matcher. 290 template <class Kind, class... Args> 291 Kind &addPredicate(Args&&... args) { 292 Predicates.emplace_back( 293 llvm::make_unique<Kind>(std::forward<Args>(args)...)); 294 return *static_cast<Kind *>(Predicates.back().get()); 295 } 296 297 typename PredicateVec::const_iterator predicates_begin() const { 298 return Predicates.begin(); 299 } 300 typename PredicateVec::const_iterator predicates_end() const { 301 return Predicates.end(); 302 } 303 iterator_range<typename PredicateVec::const_iterator> predicates() const { 304 return make_range(predicates_begin(), predicates_end()); 305 } 306 typename PredicateVec::size_type predicates_size() const { 307 return Predicates.size(); 308 } 309 310 /// Emit MatchTable opcodes that tests whether all the predicates are met. 311 template <class... Args> 312 void emitPredicateListOpcodes(raw_ostream &OS, Args &&... args) const { 313 if (Predicates.empty()) { 314 OS << "// No predicates\n"; 315 return; 316 } 317 318 for (const auto &Predicate : predicates()) 319 Predicate->emitPredicateOpcodes(OS, std::forward<Args>(args)...); 320 } 321 }; 322 323 /// Generates code to check a predicate of an operand. 324 /// 325 /// Typical predicates include: 326 /// * Operand is a particular register. 327 /// * Operand is assigned a particular register bank. 328 /// * Operand is an MBB. 329 class OperandPredicateMatcher { 330 public: 331 /// This enum is used for RTTI and also defines the priority that is given to 332 /// the predicate when generating the matcher code. Kinds with higher priority 333 /// must be tested first. 334 /// 335 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter 336 /// but OPM_Int must have priority over OPM_RegBank since constant integers 337 /// are represented by a virtual register defined by a G_CONSTANT instruction. 338 enum PredicateKind { 339 OPM_ComplexPattern, 340 OPM_Instruction, 341 OPM_Int, 342 OPM_LiteralInt, 343 OPM_LLT, 344 OPM_RegBank, 345 OPM_MBB, 346 }; 347 348 protected: 349 PredicateKind Kind; 350 351 public: 352 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {} 353 virtual ~OperandPredicateMatcher() {} 354 355 PredicateKind getKind() const { return Kind; } 356 357 /// Return the OperandMatcher for the specified operand or nullptr if there 358 /// isn't one by that name in this operand predicate matcher. 359 /// 360 /// InstructionOperandMatcher is the only subclass that can return non-null 361 /// for this. 362 virtual Optional<const OperandMatcher *> 363 getOptionalOperand(StringRef SymbolicName) const { 364 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand"); 365 return None; 366 } 367 368 /// Emit MatchTable opcodes to capture instructions into the MIs table. 369 /// 370 /// Only InstructionOperandMatcher needs to do anything for this method the 371 /// rest just walk the tree. 372 virtual void emitCaptureOpcodes(raw_ostream &OS, RuleMatcher &Rule, 373 unsigned InsnVarID, unsigned OpIdx) const {} 374 375 /// Emit MatchTable opcodes that check the predicate for the given operand. 376 virtual void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 377 unsigned InsnVarID, 378 unsigned OpIdx) const = 0; 379 380 /// Compare the priority of this object and B. 381 /// 382 /// Returns true if this object is more important than B. 383 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const { 384 return Kind < B.Kind; 385 }; 386 387 /// Report the maximum number of temporary operands needed by the predicate 388 /// matcher. 389 virtual unsigned countRendererFns() const { return 0; } 390 }; 391 392 /// Generates code to check that an operand is a particular LLT. 393 class LLTOperandMatcher : public OperandPredicateMatcher { 394 protected: 395 LLTCodeGen Ty; 396 397 public: 398 LLTOperandMatcher(const LLTCodeGen &Ty) 399 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {} 400 401 static bool classof(const OperandPredicateMatcher *P) { 402 return P->getKind() == OPM_LLT; 403 } 404 405 void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 406 unsigned InsnVarID, unsigned OpIdx) const override { 407 OS << " GIM_CheckType, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx 408 << ", /*Type*/"; 409 Ty.emitCxxEnumValue(OS); 410 OS << ", \n"; 411 } 412 }; 413 414 /// Generates code to check that an operand is a particular target constant. 415 class ComplexPatternOperandMatcher : public OperandPredicateMatcher { 416 protected: 417 const OperandMatcher &Operand; 418 const Record &TheDef; 419 420 unsigned getAllocatedTemporariesBaseID() const; 421 422 public: 423 ComplexPatternOperandMatcher(const OperandMatcher &Operand, 424 const Record &TheDef) 425 : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand), 426 TheDef(TheDef) {} 427 428 static bool classof(const OperandPredicateMatcher *P) { 429 return P->getKind() == OPM_ComplexPattern; 430 } 431 432 void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 433 unsigned InsnVarID, unsigned OpIdx) const override { 434 unsigned ID = getAllocatedTemporariesBaseID(); 435 OS << " GIM_CheckComplexPattern, /*MI*/" << InsnVarID << ", /*Op*/" 436 << OpIdx << ", /*Renderer*/" << ID << ", GICP_" 437 << TheDef.getName() << ",\n"; 438 } 439 440 unsigned countRendererFns() const override { 441 return 1; 442 } 443 }; 444 445 /// Generates code to check that an operand is in a particular register bank. 446 class RegisterBankOperandMatcher : public OperandPredicateMatcher { 447 protected: 448 const CodeGenRegisterClass &RC; 449 450 public: 451 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC) 452 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {} 453 454 static bool classof(const OperandPredicateMatcher *P) { 455 return P->getKind() == OPM_RegBank; 456 } 457 458 void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 459 unsigned InsnVarID, unsigned OpIdx) const override { 460 OS << " GIM_CheckRegBankForClass, /*MI*/" << InsnVarID << ", /*Op*/" 461 << OpIdx << ", /*RC*/" << RC.getQualifiedName() << "RegClassID,\n"; 462 } 463 }; 464 465 /// Generates code to check that an operand is a basic block. 466 class MBBOperandMatcher : public OperandPredicateMatcher { 467 public: 468 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {} 469 470 static bool classof(const OperandPredicateMatcher *P) { 471 return P->getKind() == OPM_MBB; 472 } 473 474 void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 475 unsigned InsnVarID, unsigned OpIdx) const override { 476 OS << " GIM_CheckIsMBB, /*MI*/" << InsnVarID << ", /*Op*/" << OpIdx << ",\n"; 477 } 478 }; 479 480 /// Generates code to check that an operand is a G_CONSTANT with a particular 481 /// int. 482 class ConstantIntOperandMatcher : public OperandPredicateMatcher { 483 protected: 484 int64_t Value; 485 486 public: 487 ConstantIntOperandMatcher(int64_t Value) 488 : OperandPredicateMatcher(OPM_Int), Value(Value) {} 489 490 static bool classof(const OperandPredicateMatcher *P) { 491 return P->getKind() == OPM_Int; 492 } 493 494 void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 495 unsigned InsnVarID, unsigned OpIdx) const override { 496 OS << " GIM_CheckConstantInt, /*MI*/" << InsnVarID << ", /*Op*/" 497 << OpIdx << ", " << Value << ",\n"; 498 } 499 }; 500 501 /// Generates code to check that an operand is a raw int (where MO.isImm() or 502 /// MO.isCImm() is true). 503 class LiteralIntOperandMatcher : public OperandPredicateMatcher { 504 protected: 505 int64_t Value; 506 507 public: 508 LiteralIntOperandMatcher(int64_t Value) 509 : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {} 510 511 static bool classof(const OperandPredicateMatcher *P) { 512 return P->getKind() == OPM_LiteralInt; 513 } 514 515 void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 516 unsigned InsnVarID, unsigned OpIdx) const override { 517 OS << " GIM_CheckLiteralInt, /*MI*/" << InsnVarID << ", /*Op*/" 518 << OpIdx << ", " << Value << ",\n"; 519 } 520 }; 521 522 /// Generates code to check that a set of predicates match for a particular 523 /// operand. 524 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> { 525 protected: 526 InstructionMatcher &Insn; 527 unsigned OpIdx; 528 std::string SymbolicName; 529 530 /// The index of the first temporary variable allocated to this operand. The 531 /// number of allocated temporaries can be found with 532 /// countRendererFns(). 533 unsigned AllocatedTemporariesBaseID; 534 535 public: 536 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx, 537 const std::string &SymbolicName, 538 unsigned AllocatedTemporariesBaseID) 539 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName), 540 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {} 541 542 bool hasSymbolicName() const { return !SymbolicName.empty(); } 543 const StringRef getSymbolicName() const { return SymbolicName; } 544 void setSymbolicName(StringRef Name) { 545 assert(SymbolicName.empty() && "Operand already has a symbolic name"); 546 SymbolicName = Name; 547 } 548 unsigned getOperandIndex() const { return OpIdx; } 549 550 std::string getOperandExpr(unsigned InsnVarID) const { 551 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" + 552 llvm::to_string(OpIdx) + ")"; 553 } 554 555 Optional<const OperandMatcher *> 556 getOptionalOperand(StringRef DesiredSymbolicName) const { 557 assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand"); 558 if (DesiredSymbolicName == SymbolicName) 559 return this; 560 for (const auto &OP : predicates()) { 561 const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName); 562 if (MaybeOperand.hasValue()) 563 return MaybeOperand.getValue(); 564 } 565 return None; 566 } 567 568 InstructionMatcher &getInstructionMatcher() const { return Insn; } 569 570 /// Emit MatchTable opcodes to capture instructions into the MIs table. 571 void emitCaptureOpcodes(raw_ostream &OS, RuleMatcher &Rule, 572 unsigned InsnVarID) const { 573 for (const auto &Predicate : predicates()) 574 Predicate->emitCaptureOpcodes(OS, Rule, InsnVarID, OpIdx); 575 } 576 577 /// Emit MatchTable opcodes that test whether the instruction named in 578 /// InsnVarID matches all the predicates and all the operands. 579 void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 580 unsigned InsnVarID) const { 581 OS << " // MIs[" << InsnVarID << "] "; 582 if (SymbolicName.empty()) 583 OS << "Operand " << OpIdx; 584 else 585 OS << SymbolicName; 586 OS << "\n"; 587 emitPredicateListOpcodes(OS, Rule, InsnVarID, OpIdx); 588 } 589 590 /// Compare the priority of this object and B. 591 /// 592 /// Returns true if this object is more important than B. 593 bool isHigherPriorityThan(const OperandMatcher &B) const { 594 // Operand matchers involving more predicates have higher priority. 595 if (predicates_size() > B.predicates_size()) 596 return true; 597 if (predicates_size() < B.predicates_size()) 598 return false; 599 600 // This assumes that predicates are added in a consistent order. 601 for (const auto &Predicate : zip(predicates(), B.predicates())) { 602 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate))) 603 return true; 604 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate))) 605 return false; 606 } 607 608 return false; 609 }; 610 611 /// Report the maximum number of temporary operands needed by the operand 612 /// matcher. 613 unsigned countRendererFns() const { 614 return std::accumulate( 615 predicates().begin(), predicates().end(), 0, 616 [](unsigned A, 617 const std::unique_ptr<OperandPredicateMatcher> &Predicate) { 618 return A + Predicate->countRendererFns(); 619 }); 620 } 621 622 unsigned getAllocatedTemporariesBaseID() const { 623 return AllocatedTemporariesBaseID; 624 } 625 }; 626 627 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const { 628 return Operand.getAllocatedTemporariesBaseID(); 629 } 630 631 /// Generates code to check a predicate on an instruction. 632 /// 633 /// Typical predicates include: 634 /// * The opcode of the instruction is a particular value. 635 /// * The nsw/nuw flag is/isn't set. 636 class InstructionPredicateMatcher { 637 protected: 638 /// This enum is used for RTTI and also defines the priority that is given to 639 /// the predicate when generating the matcher code. Kinds with higher priority 640 /// must be tested first. 641 enum PredicateKind { 642 IPM_Opcode, 643 }; 644 645 PredicateKind Kind; 646 647 public: 648 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {} 649 virtual ~InstructionPredicateMatcher() {} 650 651 PredicateKind getKind() const { return Kind; } 652 653 /// Emit MatchTable opcodes that test whether the instruction named in 654 /// InsnVarID matches the predicate. 655 virtual void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 656 unsigned InsnVarID) const = 0; 657 658 /// Compare the priority of this object and B. 659 /// 660 /// Returns true if this object is more important than B. 661 virtual bool 662 isHigherPriorityThan(const InstructionPredicateMatcher &B) const { 663 return Kind < B.Kind; 664 }; 665 666 /// Report the maximum number of temporary operands needed by the predicate 667 /// matcher. 668 virtual unsigned countRendererFns() const { return 0; } 669 }; 670 671 /// Generates code to check the opcode of an instruction. 672 class InstructionOpcodeMatcher : public InstructionPredicateMatcher { 673 protected: 674 const CodeGenInstruction *I; 675 676 public: 677 InstructionOpcodeMatcher(const CodeGenInstruction *I) 678 : InstructionPredicateMatcher(IPM_Opcode), I(I) {} 679 680 static bool classof(const InstructionPredicateMatcher *P) { 681 return P->getKind() == IPM_Opcode; 682 } 683 684 void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 685 unsigned InsnVarID) const override { 686 OS << " GIM_CheckOpcode, /*MI*/" << InsnVarID << ", " << I->Namespace 687 << "::" << I->TheDef->getName() << ",\n"; 688 } 689 690 /// Compare the priority of this object and B. 691 /// 692 /// Returns true if this object is more important than B. 693 bool 694 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override { 695 if (InstructionPredicateMatcher::isHigherPriorityThan(B)) 696 return true; 697 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this)) 698 return false; 699 700 // Prioritize opcodes for cosmetic reasons in the generated source. Although 701 // this is cosmetic at the moment, we may want to drive a similar ordering 702 // using instruction frequency information to improve compile time. 703 if (const InstructionOpcodeMatcher *BO = 704 dyn_cast<InstructionOpcodeMatcher>(&B)) 705 return I->TheDef->getName() < BO->I->TheDef->getName(); 706 707 return false; 708 }; 709 }; 710 711 /// Generates code to check that a set of predicates and operands match for a 712 /// particular instruction. 713 /// 714 /// Typical predicates include: 715 /// * Has a specific opcode. 716 /// * Has an nsw/nuw flag or doesn't. 717 class InstructionMatcher 718 : public PredicateListMatcher<InstructionPredicateMatcher> { 719 protected: 720 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec; 721 722 /// The operands to match. All rendered operands must be present even if the 723 /// condition is always true. 724 OperandVec Operands; 725 726 public: 727 /// Add an operand to the matcher. 728 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName, 729 unsigned AllocatedTemporariesBaseID) { 730 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName, 731 AllocatedTemporariesBaseID)); 732 return *Operands.back(); 733 } 734 735 OperandMatcher &getOperand(unsigned OpIdx) { 736 auto I = std::find_if(Operands.begin(), Operands.end(), 737 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) { 738 return X->getOperandIndex() == OpIdx; 739 }); 740 if (I != Operands.end()) 741 return **I; 742 llvm_unreachable("Failed to lookup operand"); 743 } 744 745 Optional<const OperandMatcher *> 746 getOptionalOperand(StringRef SymbolicName) const { 747 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand"); 748 for (const auto &Operand : Operands) { 749 const auto &OM = Operand->getOptionalOperand(SymbolicName); 750 if (OM.hasValue()) 751 return OM.getValue(); 752 } 753 return None; 754 } 755 756 const OperandMatcher &getOperand(StringRef SymbolicName) const { 757 Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName); 758 if (OM.hasValue()) 759 return *OM.getValue(); 760 llvm_unreachable("Failed to lookup operand"); 761 } 762 763 unsigned getNumOperands() const { return Operands.size(); } 764 OperandVec::iterator operands_begin() { return Operands.begin(); } 765 OperandVec::iterator operands_end() { return Operands.end(); } 766 iterator_range<OperandVec::iterator> operands() { 767 return make_range(operands_begin(), operands_end()); 768 } 769 OperandVec::const_iterator operands_begin() const { return Operands.begin(); } 770 OperandVec::const_iterator operands_end() const { return Operands.end(); } 771 iterator_range<OperandVec::const_iterator> operands() const { 772 return make_range(operands_begin(), operands_end()); 773 } 774 775 /// Emit MatchTable opcodes to check the shape of the match and capture 776 /// instructions into the MIs table. 777 void emitCaptureOpcodes(raw_ostream &OS, RuleMatcher &Rule, 778 unsigned InsnID) { 779 OS << " GIM_CheckNumOperands, /*MI*/" << InsnID << ", /*Expected*/" 780 << getNumOperands() << ",\n"; 781 for (const auto &Operand : Operands) 782 Operand->emitCaptureOpcodes(OS, Rule, InsnID); 783 } 784 785 /// Emit MatchTable opcodes that test whether the instruction named in 786 /// InsnVarName matches all the predicates and all the operands. 787 void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 788 unsigned InsnVarID) const { 789 emitPredicateListOpcodes(OS, Rule, InsnVarID); 790 for (const auto &Operand : Operands) 791 Operand->emitPredicateOpcodes(OS, Rule, InsnVarID); 792 } 793 794 /// Compare the priority of this object and B. 795 /// 796 /// Returns true if this object is more important than B. 797 bool isHigherPriorityThan(const InstructionMatcher &B) const { 798 // Instruction matchers involving more operands have higher priority. 799 if (Operands.size() > B.Operands.size()) 800 return true; 801 if (Operands.size() < B.Operands.size()) 802 return false; 803 804 for (const auto &Predicate : zip(predicates(), B.predicates())) { 805 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate))) 806 return true; 807 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate))) 808 return false; 809 } 810 811 for (const auto &Operand : zip(Operands, B.Operands)) { 812 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand))) 813 return true; 814 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand))) 815 return false; 816 } 817 818 return false; 819 }; 820 821 /// Report the maximum number of temporary operands needed by the instruction 822 /// matcher. 823 unsigned countRendererFns() const { 824 return std::accumulate(predicates().begin(), predicates().end(), 0, 825 [](unsigned A, 826 const std::unique_ptr<InstructionPredicateMatcher> 827 &Predicate) { 828 return A + Predicate->countRendererFns(); 829 }) + 830 std::accumulate( 831 Operands.begin(), Operands.end(), 0, 832 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) { 833 return A + Operand->countRendererFns(); 834 }); 835 } 836 }; 837 838 /// Generates code to check that the operand is a register defined by an 839 /// instruction that matches the given instruction matcher. 840 /// 841 /// For example, the pattern: 842 /// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3)) 843 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match 844 /// the: 845 /// (G_ADD $src1, $src2) 846 /// subpattern. 847 class InstructionOperandMatcher : public OperandPredicateMatcher { 848 protected: 849 std::unique_ptr<InstructionMatcher> InsnMatcher; 850 851 public: 852 InstructionOperandMatcher() 853 : OperandPredicateMatcher(OPM_Instruction), 854 InsnMatcher(new InstructionMatcher()) {} 855 856 static bool classof(const OperandPredicateMatcher *P) { 857 return P->getKind() == OPM_Instruction; 858 } 859 860 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; } 861 862 Optional<const OperandMatcher *> 863 getOptionalOperand(StringRef SymbolicName) const override { 864 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand"); 865 return InsnMatcher->getOptionalOperand(SymbolicName); 866 } 867 868 void emitCaptureOpcodes(raw_ostream &OS, RuleMatcher &Rule, 869 unsigned InsnID, unsigned OpIdx) const override { 870 unsigned InsnVarID = Rule.defineInsnVar(OS, *InsnMatcher, InsnID, OpIdx); 871 InsnMatcher->emitCaptureOpcodes(OS, Rule, InsnVarID); 872 } 873 874 void emitPredicateOpcodes(raw_ostream &OS, RuleMatcher &Rule, 875 unsigned InsnVarID_, 876 unsigned OpIdx_) const override { 877 unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher); 878 InsnMatcher->emitPredicateOpcodes(OS, Rule, InsnVarID); 879 } 880 }; 881 882 //===- Actions ------------------------------------------------------------===// 883 class OperandRenderer { 884 public: 885 enum RendererKind { 886 OR_Copy, 887 OR_CopySubReg, 888 OR_Imm, 889 OR_Register, 890 OR_ComplexPattern 891 }; 892 893 protected: 894 RendererKind Kind; 895 896 public: 897 OperandRenderer(RendererKind Kind) : Kind(Kind) {} 898 virtual ~OperandRenderer() {} 899 900 RendererKind getKind() const { return Kind; } 901 902 virtual void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const = 0; 903 }; 904 905 /// A CopyRenderer emits code to copy a single operand from an existing 906 /// instruction to the one being built. 907 class CopyRenderer : public OperandRenderer { 908 protected: 909 unsigned NewInsnID; 910 /// The matcher for the instruction that this operand is copied from. 911 /// This provides the facility for looking up an a operand by it's name so 912 /// that it can be used as a source for the instruction being built. 913 const InstructionMatcher &Matched; 914 /// The name of the operand. 915 const StringRef SymbolicName; 916 917 public: 918 CopyRenderer(unsigned NewInsnID, const InstructionMatcher &Matched, 919 StringRef SymbolicName) 920 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), Matched(Matched), 921 SymbolicName(SymbolicName) {} 922 923 static bool classof(const OperandRenderer *R) { 924 return R->getKind() == OR_Copy; 925 } 926 927 const StringRef getSymbolicName() const { return SymbolicName; } 928 929 void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const override { 930 const OperandMatcher &Operand = Matched.getOperand(SymbolicName); 931 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); 932 OS << " GIR_Copy, /*NewInsnID*/" << NewInsnID << ", /*OldInsnID*/" 933 << OldInsnVarID << ", /*OpIdx*/" << Operand.getOperandIndex() << ", // " 934 << SymbolicName << "\n"; 935 } 936 }; 937 938 /// A CopySubRegRenderer emits code to copy a single register operand from an 939 /// existing instruction to the one being built and indicate that only a 940 /// subregister should be copied. 941 class CopySubRegRenderer : public OperandRenderer { 942 protected: 943 unsigned NewInsnID; 944 /// The matcher for the instruction that this operand is copied from. 945 /// This provides the facility for looking up an a operand by it's name so 946 /// that it can be used as a source for the instruction being built. 947 const InstructionMatcher &Matched; 948 /// The name of the operand. 949 const StringRef SymbolicName; 950 /// The subregister to extract. 951 const CodeGenSubRegIndex *SubReg; 952 953 public: 954 CopySubRegRenderer(unsigned NewInsnID, const InstructionMatcher &Matched, 955 StringRef SymbolicName, const CodeGenSubRegIndex *SubReg) 956 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), Matched(Matched), 957 SymbolicName(SymbolicName), SubReg(SubReg) {} 958 959 static bool classof(const OperandRenderer *R) { 960 return R->getKind() == OR_CopySubReg; 961 } 962 963 const StringRef getSymbolicName() const { return SymbolicName; } 964 965 void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const override { 966 const OperandMatcher &Operand = Matched.getOperand(SymbolicName); 967 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); 968 OS << " GIR_CopySubReg, /*NewInsnID*/" << NewInsnID 969 << ", /*OldInsnID*/" << OldInsnVarID << ", /*OpIdx*/" 970 << Operand.getOperandIndex() << ", /*SubRegIdx*/" << SubReg->EnumValue 971 << ", // " << SymbolicName << "\n"; 972 } 973 }; 974 975 /// Adds a specific physical register to the instruction being built. 976 /// This is typically useful for WZR/XZR on AArch64. 977 class AddRegisterRenderer : public OperandRenderer { 978 protected: 979 unsigned InsnID; 980 const Record *RegisterDef; 981 982 public: 983 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef) 984 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) { 985 } 986 987 static bool classof(const OperandRenderer *R) { 988 return R->getKind() == OR_Register; 989 } 990 991 void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const override { 992 OS << " GIR_AddRegister, /*InsnID*/" << InsnID << ", " 993 << (RegisterDef->getValue("Namespace") 994 ? RegisterDef->getValueAsString("Namespace") 995 : "") 996 << "::" << RegisterDef->getName() << ",\n"; 997 } 998 }; 999 1000 /// Adds a specific immediate to the instruction being built. 1001 class ImmRenderer : public OperandRenderer { 1002 protected: 1003 unsigned InsnID; 1004 int64_t Imm; 1005 1006 public: 1007 ImmRenderer(unsigned InsnID, int64_t Imm) 1008 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {} 1009 1010 static bool classof(const OperandRenderer *R) { 1011 return R->getKind() == OR_Imm; 1012 } 1013 1014 void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const override { 1015 OS << " GIR_AddImm, /*InsnID*/" << InsnID << ", /*Imm*/" << Imm 1016 << ",\n"; 1017 } 1018 }; 1019 1020 /// Adds operands by calling a renderer function supplied by the ComplexPattern 1021 /// matcher function. 1022 class RenderComplexPatternOperand : public OperandRenderer { 1023 private: 1024 unsigned InsnID; 1025 const Record &TheDef; 1026 /// The name of the operand. 1027 const StringRef SymbolicName; 1028 /// The renderer number. This must be unique within a rule since it's used to 1029 /// identify a temporary variable to hold the renderer function. 1030 unsigned RendererID; 1031 1032 unsigned getNumOperands() const { 1033 return TheDef.getValueAsDag("Operands")->getNumArgs(); 1034 } 1035 1036 public: 1037 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef, 1038 StringRef SymbolicName, unsigned RendererID) 1039 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef), 1040 SymbolicName(SymbolicName), RendererID(RendererID) {} 1041 1042 static bool classof(const OperandRenderer *R) { 1043 return R->getKind() == OR_ComplexPattern; 1044 } 1045 1046 void emitRenderOpcodes(raw_ostream &OS, RuleMatcher &Rule) const override { 1047 OS << " GIR_ComplexRenderer, /*InsnID*/" << InsnID << ", /*RendererID*/" 1048 << RendererID << ",\n"; 1049 } 1050 }; 1051 1052 /// An action taken when all Matcher predicates succeeded for a parent rule. 1053 /// 1054 /// Typical actions include: 1055 /// * Changing the opcode of an instruction. 1056 /// * Adding an operand to an instruction. 1057 class MatchAction { 1058 public: 1059 virtual ~MatchAction() {} 1060 1061 /// Emit the C++ statements to implement the action. 1062 /// 1063 /// \param RecycleInsnID If given, it's an instruction to recycle. The 1064 /// requirements on the instruction vary from action to 1065 /// action. 1066 virtual void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, 1067 unsigned RecycleInsnID) const = 0; 1068 }; 1069 1070 /// Generates a comment describing the matched rule being acted upon. 1071 class DebugCommentAction : public MatchAction { 1072 private: 1073 const PatternToMatch &P; 1074 1075 public: 1076 DebugCommentAction(const PatternToMatch &P) : P(P) {} 1077 1078 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, 1079 unsigned RecycleInsnID) const override { 1080 OS << " // " << *P.getSrcPattern() << " => " << *P.getDstPattern() 1081 << "\n"; 1082 } 1083 }; 1084 1085 /// Generates code to build an instruction or mutate an existing instruction 1086 /// into the desired instruction when this is possible. 1087 class BuildMIAction : public MatchAction { 1088 private: 1089 unsigned InsnID; 1090 const CodeGenInstruction *I; 1091 const InstructionMatcher &Matched; 1092 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers; 1093 1094 /// True if the instruction can be built solely by mutating the opcode. 1095 bool canMutate() const { 1096 if (OperandRenderers.size() != Matched.getNumOperands()) 1097 return false; 1098 1099 for (const auto &Renderer : enumerate(OperandRenderers)) { 1100 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) { 1101 const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName()); 1102 if (&Matched != &OM.getInstructionMatcher() || 1103 OM.getOperandIndex() != Renderer.index()) 1104 return false; 1105 } else 1106 return false; 1107 } 1108 1109 return true; 1110 } 1111 1112 public: 1113 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I, 1114 const InstructionMatcher &Matched) 1115 : InsnID(InsnID), I(I), Matched(Matched) {} 1116 1117 template <class Kind, class... Args> 1118 Kind &addRenderer(Args&&... args) { 1119 OperandRenderers.emplace_back( 1120 llvm::make_unique<Kind>(std::forward<Args>(args)...)); 1121 return *static_cast<Kind *>(OperandRenderers.back().get()); 1122 } 1123 1124 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, 1125 unsigned RecycleInsnID) const override { 1126 if (canMutate()) { 1127 OS << " GIR_MutateOpcode, /*InsnID*/" << InsnID 1128 << ", /*RecycleInsnID*/ " << RecycleInsnID << ", /*Opcode*/" 1129 << I->Namespace << "::" << I->TheDef->getName() << ",\n"; 1130 1131 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) { 1132 for (auto Def : I->ImplicitDefs) { 1133 auto Namespace = Def->getValue("Namespace") 1134 ? Def->getValueAsString("Namespace") 1135 : ""; 1136 OS << " GIR_AddImplicitDef, " << InsnID << ", " << Namespace 1137 << "::" << Def->getName() << ",\n"; 1138 } 1139 for (auto Use : I->ImplicitUses) { 1140 auto Namespace = Use->getValue("Namespace") 1141 ? Use->getValueAsString("Namespace") 1142 : ""; 1143 OS << " GIR_AddImplicitUse, " << InsnID << ", " << Namespace 1144 << "::" << Use->getName() << ",\n"; 1145 } 1146 } 1147 return; 1148 } 1149 1150 // TODO: Simple permutation looks like it could be almost as common as 1151 // mutation due to commutative operations. 1152 1153 OS << " GIR_BuildMI, /*InsnID*/" << InsnID << ", /*Opcode*/" 1154 << I->Namespace << "::" << I->TheDef->getName() << ",\n"; 1155 for (const auto &Renderer : OperandRenderers) 1156 Renderer->emitRenderOpcodes(OS, Rule); 1157 1158 OS << " GIR_MergeMemOperands, /*InsnID*/" << InsnID << ",\n" 1159 << " GIR_EraseFromParent, /*InsnID*/" << RecycleInsnID << ",\n"; 1160 } 1161 }; 1162 1163 /// Generates code to constrain the operands of an output instruction to the 1164 /// register classes specified by the definition of that instruction. 1165 class ConstrainOperandsToDefinitionAction : public MatchAction { 1166 unsigned InsnID; 1167 1168 public: 1169 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {} 1170 1171 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, 1172 unsigned RecycleInsnID) const override { 1173 OS << " GIR_ConstrainSelectedInstOperands, /*InsnID*/" << InsnID << ",\n"; 1174 } 1175 }; 1176 1177 /// Generates code to constrain the specified operand of an output instruction 1178 /// to the specified register class. 1179 class ConstrainOperandToRegClassAction : public MatchAction { 1180 unsigned InsnID; 1181 unsigned OpIdx; 1182 const CodeGenRegisterClass &RC; 1183 1184 public: 1185 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx, 1186 const CodeGenRegisterClass &RC) 1187 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {} 1188 1189 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule, 1190 unsigned RecycleInsnID) const override { 1191 OS << " GIR_ConstrainOperandRC, /*InsnID*/" << InsnID << ", /*Op*/" 1192 << OpIdx << ", /*RC " << RC.getName() << "*/ " << RC.EnumValue << ",\n"; 1193 } 1194 }; 1195 1196 InstructionMatcher &RuleMatcher::addInstructionMatcher() { 1197 Matchers.emplace_back(new InstructionMatcher()); 1198 return *Matchers.back(); 1199 } 1200 1201 void RuleMatcher::addRequiredFeature(Record *Feature) { 1202 RequiredFeatures.push_back(Feature); 1203 } 1204 1205 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const { 1206 return RequiredFeatures; 1207 } 1208 1209 template <class Kind, class... Args> 1210 Kind &RuleMatcher::addAction(Args &&... args) { 1211 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...)); 1212 return *static_cast<Kind *>(Actions.back().get()); 1213 } 1214 1215 unsigned 1216 RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) { 1217 unsigned NewInsnVarID = NextInsnVarID++; 1218 InsnVariableIDs[&Matcher] = NewInsnVarID; 1219 return NewInsnVarID; 1220 } 1221 1222 unsigned RuleMatcher::defineInsnVar(raw_ostream &OS, 1223 const InstructionMatcher &Matcher, 1224 unsigned InsnID, unsigned OpIdx) { 1225 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher); 1226 OS << " GIM_RecordInsn, /*DefineMI*/" << NewInsnVarID << ", /*MI*/" 1227 << InsnID << ", /*OpIdx*/" << OpIdx << ", // MIs[" << NewInsnVarID 1228 << "]\n"; 1229 return NewInsnVarID; 1230 } 1231 1232 unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const { 1233 const auto &I = InsnVariableIDs.find(&InsnMatcher); 1234 if (I != InsnVariableIDs.end()) 1235 return I->second; 1236 llvm_unreachable("Matched Insn was not captured in a local variable"); 1237 } 1238 1239 /// Emit MatchTable opcodes to check the shape of the match and capture 1240 /// instructions into local variables. 1241 void RuleMatcher::emitCaptureOpcodes(raw_ostream &OS) { 1242 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet"); 1243 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front()); 1244 Matchers.front()->emitCaptureOpcodes(OS, *this, InsnVarID); 1245 } 1246 1247 void RuleMatcher::emit(raw_ostream &OS) { 1248 if (Matchers.empty()) 1249 llvm_unreachable("Unexpected empty matcher!"); 1250 1251 // The representation supports rules that require multiple roots such as: 1252 // %ptr(p0) = ... 1253 // %elt0(s32) = G_LOAD %ptr 1254 // %1(p0) = G_ADD %ptr, 4 1255 // %elt1(s32) = G_LOAD p0 %1 1256 // which could be usefully folded into: 1257 // %ptr(p0) = ... 1258 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr 1259 // on some targets but we don't need to make use of that yet. 1260 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet"); 1261 1262 OS << " const static int64_t MatchTable" << CurrentMatchTableID << "[] = {\n"; 1263 if (!RequiredFeatures.empty()) { 1264 OS << " GIM_CheckFeatures, " << getNameForFeatureBitset(RequiredFeatures) 1265 << ",\n"; 1266 } 1267 1268 emitCaptureOpcodes(OS); 1269 1270 Matchers.front()->emitPredicateOpcodes(OS, *this, 1271 getInsnVarID(*Matchers.front())); 1272 1273 // We must also check if it's safe to fold the matched instructions. 1274 if (InsnVariableIDs.size() >= 2) { 1275 // Invert the map to create stable ordering (by var names) 1276 SmallVector<unsigned, 2> InsnIDs; 1277 for (const auto &Pair : InsnVariableIDs) { 1278 // Skip the root node since it isn't moving anywhere. Everything else is 1279 // sinking to meet it. 1280 if (Pair.first == Matchers.front().get()) 1281 continue; 1282 1283 InsnIDs.push_back(Pair.second); 1284 } 1285 std::sort(InsnIDs.begin(), InsnIDs.end()); 1286 1287 for (const auto &InsnID : InsnIDs) { 1288 // Reject the difficult cases until we have a more accurate check. 1289 OS << " GIM_CheckIsSafeToFold, /*InsnID*/" << InsnID << ",\n"; 1290 1291 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or 1292 // account for unsafe cases. 1293 // 1294 // Example: 1295 // MI1--> %0 = ... 1296 // %1 = ... %0 1297 // MI0--> %2 = ... %0 1298 // It's not safe to erase MI1. We currently handle this by not 1299 // erasing %0 (even when it's dead). 1300 // 1301 // Example: 1302 // MI1--> %0 = load volatile @a 1303 // %1 = load volatile @a 1304 // MI0--> %2 = ... %0 1305 // It's not safe to sink %0's def past %1. We currently handle 1306 // this by rejecting all loads. 1307 // 1308 // Example: 1309 // MI1--> %0 = load @a 1310 // %1 = store @a 1311 // MI0--> %2 = ... %0 1312 // It's not safe to sink %0's def past %1. We currently handle 1313 // this by rejecting all loads. 1314 // 1315 // Example: 1316 // G_CONDBR %cond, @BB1 1317 // BB0: 1318 // MI1--> %0 = load @a 1319 // G_BR @BB1 1320 // BB1: 1321 // MI0--> %2 = ... %0 1322 // It's not always safe to sink %0 across control flow. In this 1323 // case it may introduce a memory fault. We currentl handle this 1324 // by rejecting all loads. 1325 } 1326 } 1327 1328 for (const auto &MA : Actions) 1329 MA->emitCxxActionStmts(OS, *this, 0); 1330 OS << " GIR_Done,\n" 1331 << " };\n" 1332 << " State.MIs.resize(1);\n" 1333 << " DEBUG(dbgs() << \"Processing MatchTable" << CurrentMatchTableID 1334 << "\\n\");\n" 1335 << " if (executeMatchTable(*this, OutMIs, State, MatcherInfo, MatchTable" 1336 << CurrentMatchTableID << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n" 1337 << " return true;\n" 1338 << " }\n\n"; 1339 } 1340 1341 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const { 1342 // Rules involving more match roots have higher priority. 1343 if (Matchers.size() > B.Matchers.size()) 1344 return true; 1345 if (Matchers.size() < B.Matchers.size()) 1346 return false; 1347 1348 for (const auto &Matcher : zip(Matchers, B.Matchers)) { 1349 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher))) 1350 return true; 1351 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher))) 1352 return false; 1353 } 1354 1355 return false; 1356 } 1357 1358 unsigned RuleMatcher::countRendererFns() const { 1359 return std::accumulate( 1360 Matchers.begin(), Matchers.end(), 0, 1361 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) { 1362 return A + Matcher->countRendererFns(); 1363 }); 1364 } 1365 1366 //===- GlobalISelEmitter class --------------------------------------------===// 1367 1368 class GlobalISelEmitter { 1369 public: 1370 explicit GlobalISelEmitter(RecordKeeper &RK); 1371 void run(raw_ostream &OS); 1372 1373 private: 1374 const RecordKeeper &RK; 1375 const CodeGenDAGPatterns CGP; 1376 const CodeGenTarget &Target; 1377 CodeGenRegBank CGRegs; 1378 1379 /// Keep track of the equivalence between SDNodes and Instruction. 1380 /// This is defined using 'GINodeEquiv' in the target description. 1381 DenseMap<Record *, const CodeGenInstruction *> NodeEquivs; 1382 1383 /// Keep track of the equivalence between ComplexPattern's and 1384 /// GIComplexOperandMatcher. Map entries are specified by subclassing 1385 /// GIComplexPatternEquiv. 1386 DenseMap<const Record *, const Record *> ComplexPatternEquivs; 1387 1388 // Map of predicates to their subtarget features. 1389 SubtargetFeatureInfoMap SubtargetFeatures; 1390 1391 void gatherNodeEquivs(); 1392 const CodeGenInstruction *findNodeEquiv(Record *N) const; 1393 1394 Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates); 1395 Expected<InstructionMatcher &> 1396 createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher, 1397 const TreePatternNode *Src) const; 1398 Error importChildMatcher(InstructionMatcher &InsnMatcher, 1399 const TreePatternNode *SrcChild, unsigned OpIdx, 1400 unsigned &TempOpIdx) const; 1401 Expected<BuildMIAction &> 1402 createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst, 1403 const InstructionMatcher &InsnMatcher); 1404 Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder, 1405 TreePatternNode *DstChild, 1406 const InstructionMatcher &InsnMatcher) const; 1407 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder, 1408 DagInit *DefaultOps) const; 1409 Error 1410 importImplicitDefRenderers(BuildMIAction &DstMIBuilder, 1411 const std::vector<Record *> &ImplicitDefs) const; 1412 1413 /// Analyze pattern \p P, returning a matcher for it if possible. 1414 /// Otherwise, return an Error explaining why we don't support it. 1415 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P); 1416 1417 void declareSubtargetFeature(Record *Predicate); 1418 }; 1419 1420 void GlobalISelEmitter::gatherNodeEquivs() { 1421 assert(NodeEquivs.empty()); 1422 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv")) 1423 NodeEquivs[Equiv->getValueAsDef("Node")] = 1424 &Target.getInstruction(Equiv->getValueAsDef("I")); 1425 1426 assert(ComplexPatternEquivs.empty()); 1427 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) { 1428 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent"); 1429 if (!SelDAGEquiv) 1430 continue; 1431 ComplexPatternEquivs[SelDAGEquiv] = Equiv; 1432 } 1433 } 1434 1435 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const { 1436 return NodeEquivs.lookup(N); 1437 } 1438 1439 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK) 1440 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()), CGRegs(RK) {} 1441 1442 //===- Emitter ------------------------------------------------------------===// 1443 1444 Error 1445 GlobalISelEmitter::importRulePredicates(RuleMatcher &M, 1446 ArrayRef<Init *> Predicates) { 1447 for (const Init *Predicate : Predicates) { 1448 const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate); 1449 declareSubtargetFeature(PredicateDef->getDef()); 1450 M.addRequiredFeature(PredicateDef->getDef()); 1451 } 1452 1453 return Error::success(); 1454 } 1455 1456 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher( 1457 InstructionMatcher &InsnMatcher, const TreePatternNode *Src) const { 1458 const CodeGenInstruction *SrcGIOrNull = nullptr; 1459 1460 // Start with the defined operands (i.e., the results of the root operator). 1461 if (Src->getExtTypes().size() > 1) 1462 return failedImport("Src pattern has multiple results"); 1463 1464 if (Src->isLeaf()) { 1465 Init *SrcInit = Src->getLeafValue(); 1466 if (isa<IntInit>(SrcInit)) { 1467 InsnMatcher.addPredicate<InstructionOpcodeMatcher>( 1468 &Target.getInstruction(RK.getDef("G_CONSTANT"))); 1469 } else 1470 return failedImport( 1471 "Unable to deduce gMIR opcode to handle Src (which is a leaf)"); 1472 } else { 1473 SrcGIOrNull = findNodeEquiv(Src->getOperator()); 1474 if (!SrcGIOrNull) 1475 return failedImport("Pattern operator lacks an equivalent Instruction" + 1476 explainOperator(Src->getOperator())); 1477 auto &SrcGI = *SrcGIOrNull; 1478 1479 // The operators look good: match the opcode 1480 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI); 1481 } 1482 1483 unsigned OpIdx = 0; 1484 unsigned TempOpIdx = 0; 1485 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) { 1486 auto OpTyOrNone = MVTToLLT(Ty.getConcrete()); 1487 1488 if (!OpTyOrNone) 1489 return failedImport( 1490 "Result of Src pattern operator has an unsupported type"); 1491 1492 // Results don't have a name unless they are the root node. The caller will 1493 // set the name if appropriate. 1494 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx); 1495 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone); 1496 } 1497 1498 if (Src->isLeaf()) { 1499 Init *SrcInit = Src->getLeafValue(); 1500 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) { 1501 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx); 1502 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue()); 1503 } else 1504 return failedImport( 1505 "Unable to deduce gMIR opcode to handle Src (which is a leaf)"); 1506 } else { 1507 assert(SrcGIOrNull && 1508 "Expected to have already found an equivalent Instruction"); 1509 // Match the used operands (i.e. the children of the operator). 1510 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) { 1511 TreePatternNode *SrcChild = Src->getChild(i); 1512 1513 // For G_INTRINSIC, the operand immediately following the defs is an 1514 // intrinsic ID. 1515 if (SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" && i == 0) { 1516 if (!SrcChild->isLeaf()) 1517 return failedImport("Expected IntInit containing intrinsic ID"); 1518 1519 if (IntInit *SrcChildIntInit = 1520 dyn_cast<IntInit>(SrcChild->getLeafValue())) { 1521 OperandMatcher &OM = 1522 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx); 1523 OM.addPredicate<LiteralIntOperandMatcher>(SrcChildIntInit->getValue()); 1524 continue; 1525 } 1526 1527 return failedImport("Expected IntInit containing instrinsic ID)"); 1528 } 1529 1530 if (auto Error = 1531 importChildMatcher(InsnMatcher, SrcChild, OpIdx++, TempOpIdx)) 1532 return std::move(Error); 1533 } 1534 } 1535 1536 return InsnMatcher; 1537 } 1538 1539 Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher, 1540 const TreePatternNode *SrcChild, 1541 unsigned OpIdx, 1542 unsigned &TempOpIdx) const { 1543 OperandMatcher &OM = 1544 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx); 1545 1546 if (SrcChild->hasAnyPredicate()) 1547 return failedImport("Src pattern child has predicate (" + 1548 explainPredicates(SrcChild) + ")"); 1549 1550 ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes(); 1551 if (ChildTypes.size() != 1) 1552 return failedImport("Src pattern child has multiple results"); 1553 1554 // Check MBB's before the type check since they are not a known type. 1555 if (!SrcChild->isLeaf()) { 1556 if (SrcChild->getOperator()->isSubClassOf("SDNode")) { 1557 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator()); 1558 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { 1559 OM.addPredicate<MBBOperandMatcher>(); 1560 return Error::success(); 1561 } 1562 } 1563 } 1564 1565 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete()); 1566 if (!OpTyOrNone) 1567 return failedImport("Src operand has an unsupported type (" + to_string(*SrcChild) + ")"); 1568 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone); 1569 1570 // Check for nested instructions. 1571 if (!SrcChild->isLeaf()) { 1572 // Map the node to a gMIR instruction. 1573 InstructionOperandMatcher &InsnOperand = 1574 OM.addPredicate<InstructionOperandMatcher>(); 1575 auto InsnMatcherOrError = 1576 createAndImportSelDAGMatcher(InsnOperand.getInsnMatcher(), SrcChild); 1577 if (auto Error = InsnMatcherOrError.takeError()) 1578 return Error; 1579 1580 return Error::success(); 1581 } 1582 1583 // Check for constant immediates. 1584 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) { 1585 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue()); 1586 return Error::success(); 1587 } 1588 1589 // Check for def's like register classes or ComplexPattern's. 1590 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) { 1591 auto *ChildRec = ChildDefInit->getDef(); 1592 1593 // Check for register classes. 1594 if (ChildRec->isSubClassOf("RegisterClass") || 1595 ChildRec->isSubClassOf("RegisterOperand")) { 1596 OM.addPredicate<RegisterBankOperandMatcher>( 1597 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit))); 1598 return Error::success(); 1599 } 1600 1601 // Check for ComplexPattern's. 1602 if (ChildRec->isSubClassOf("ComplexPattern")) { 1603 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec); 1604 if (ComplexPattern == ComplexPatternEquivs.end()) 1605 return failedImport("SelectionDAG ComplexPattern (" + 1606 ChildRec->getName() + ") not mapped to GlobalISel"); 1607 1608 OM.addPredicate<ComplexPatternOperandMatcher>(OM, 1609 *ComplexPattern->second); 1610 TempOpIdx++; 1611 return Error::success(); 1612 } 1613 1614 if (ChildRec->isSubClassOf("ImmLeaf")) { 1615 return failedImport( 1616 "Src pattern child def is an unsupported tablegen class (ImmLeaf)"); 1617 } 1618 1619 return failedImport( 1620 "Src pattern child def is an unsupported tablegen class"); 1621 } 1622 1623 return failedImport("Src pattern child is an unsupported kind"); 1624 } 1625 1626 Error GlobalISelEmitter::importExplicitUseRenderer( 1627 BuildMIAction &DstMIBuilder, TreePatternNode *DstChild, 1628 const InstructionMatcher &InsnMatcher) const { 1629 // The only non-leaf child we accept is 'bb': it's an operator because 1630 // BasicBlockSDNode isn't inline, but in MI it's just another operand. 1631 if (!DstChild->isLeaf()) { 1632 if (DstChild->getOperator()->isSubClassOf("SDNode")) { 1633 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator()); 1634 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { 1635 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, 1636 DstChild->getName()); 1637 return Error::success(); 1638 } 1639 } 1640 return failedImport("Dst pattern child isn't a leaf node or an MBB"); 1641 } 1642 1643 // Otherwise, we're looking for a bog-standard RegisterClass operand. 1644 if (DstChild->hasAnyPredicate()) 1645 return failedImport("Dst pattern child has predicate (" + 1646 explainPredicates(DstChild) + ")"); 1647 1648 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) { 1649 auto *ChildRec = ChildDefInit->getDef(); 1650 1651 ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes(); 1652 if (ChildTypes.size() != 1) 1653 return failedImport("Dst pattern child has multiple results"); 1654 1655 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete()); 1656 if (!OpTyOrNone) 1657 return failedImport("Dst operand has an unsupported type"); 1658 1659 if (ChildRec->isSubClassOf("Register")) { 1660 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec); 1661 return Error::success(); 1662 } 1663 1664 if (ChildRec->isSubClassOf("RegisterClass") || 1665 ChildRec->isSubClassOf("RegisterOperand")) { 1666 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, 1667 DstChild->getName()); 1668 return Error::success(); 1669 } 1670 1671 if (ChildRec->isSubClassOf("ComplexPattern")) { 1672 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec); 1673 if (ComplexPattern == ComplexPatternEquivs.end()) 1674 return failedImport( 1675 "SelectionDAG ComplexPattern not mapped to GlobalISel"); 1676 1677 const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName()); 1678 DstMIBuilder.addRenderer<RenderComplexPatternOperand>( 1679 0, *ComplexPattern->second, DstChild->getName(), 1680 OM.getAllocatedTemporariesBaseID()); 1681 return Error::success(); 1682 } 1683 1684 if (ChildRec->isSubClassOf("SDNodeXForm")) 1685 return failedImport("Dst pattern child def is an unsupported tablegen " 1686 "class (SDNodeXForm)"); 1687 1688 return failedImport( 1689 "Dst pattern child def is an unsupported tablegen class"); 1690 } 1691 1692 return failedImport("Dst pattern child is an unsupported kind"); 1693 } 1694 1695 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer( 1696 RuleMatcher &M, const TreePatternNode *Dst, 1697 const InstructionMatcher &InsnMatcher) { 1698 Record *DstOp = Dst->getOperator(); 1699 if (!DstOp->isSubClassOf("Instruction")) { 1700 if (DstOp->isSubClassOf("ValueType")) 1701 return failedImport( 1702 "Pattern operator isn't an instruction (it's a ValueType)"); 1703 return failedImport("Pattern operator isn't an instruction"); 1704 } 1705 CodeGenInstruction *DstI = &Target.getInstruction(DstOp); 1706 1707 unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs; 1708 unsigned ExpectedDstINumUses = Dst->getNumChildren(); 1709 bool IsExtractSubReg = false; 1710 1711 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction 1712 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy. 1713 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") { 1714 DstI = &Target.getInstruction(RK.getDef("COPY")); 1715 DstINumUses--; // Ignore the class constraint. 1716 ExpectedDstINumUses--; 1717 } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") { 1718 DstI = &Target.getInstruction(RK.getDef("COPY")); 1719 IsExtractSubReg = true; 1720 } 1721 1722 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, InsnMatcher); 1723 1724 // Render the explicit defs. 1725 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) { 1726 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I]; 1727 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name); 1728 } 1729 1730 // EXTRACT_SUBREG needs to use a subregister COPY. 1731 if (IsExtractSubReg) { 1732 if (!Dst->getChild(0)->isLeaf()) 1733 return failedImport("EXTRACT_SUBREG child #1 is not a leaf"); 1734 1735 if (DefInit *SubRegInit = 1736 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) { 1737 CodeGenRegisterClass *RC = CGRegs.getRegClass( 1738 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue())); 1739 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef()); 1740 1741 const auto &SrcRCDstRCPair = 1742 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx); 1743 if (SrcRCDstRCPair.hasValue()) { 1744 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass"); 1745 if (SrcRCDstRCPair->first != RC) 1746 return failedImport("EXTRACT_SUBREG requires an additional COPY"); 1747 } 1748 1749 DstMIBuilder.addRenderer<CopySubRegRenderer>( 1750 0, InsnMatcher, Dst->getChild(0)->getName(), SubIdx); 1751 return DstMIBuilder; 1752 } 1753 1754 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index"); 1755 } 1756 1757 // Render the explicit uses. 1758 unsigned Child = 0; 1759 unsigned NumDefaultOps = 0; 1760 for (unsigned I = 0; I != DstINumUses; ++I) { 1761 const CGIOperandList::OperandInfo &DstIOperand = 1762 DstI->Operands[DstI->Operands.NumDefs + I]; 1763 1764 // If the operand has default values, introduce them now. 1765 // FIXME: Until we have a decent test case that dictates we should do 1766 // otherwise, we're going to assume that operands with default values cannot 1767 // be specified in the patterns. Therefore, adding them will not cause us to 1768 // end up with too many rendered operands. 1769 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) { 1770 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps"); 1771 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps)) 1772 return std::move(Error); 1773 ++NumDefaultOps; 1774 continue; 1775 } 1776 1777 if (auto Error = importExplicitUseRenderer( 1778 DstMIBuilder, Dst->getChild(Child), InsnMatcher)) 1779 return std::move(Error); 1780 ++Child; 1781 } 1782 1783 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses) 1784 return failedImport("Expected " + llvm::to_string(DstINumUses) + 1785 " used operands but found " + 1786 llvm::to_string(ExpectedDstINumUses) + 1787 " explicit ones and " + llvm::to_string(NumDefaultOps) + 1788 " default ones"); 1789 1790 return DstMIBuilder; 1791 } 1792 1793 Error GlobalISelEmitter::importDefaultOperandRenderers( 1794 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const { 1795 for (const auto *DefaultOp : DefaultOps->getArgs()) { 1796 // Look through ValueType operators. 1797 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) { 1798 if (const DefInit *DefaultDagOperator = 1799 dyn_cast<DefInit>(DefaultDagOp->getOperator())) { 1800 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) 1801 DefaultOp = DefaultDagOp->getArg(0); 1802 } 1803 } 1804 1805 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) { 1806 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef()); 1807 continue; 1808 } 1809 1810 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) { 1811 DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue()); 1812 continue; 1813 } 1814 1815 return failedImport("Could not add default op"); 1816 } 1817 1818 return Error::success(); 1819 } 1820 1821 Error GlobalISelEmitter::importImplicitDefRenderers( 1822 BuildMIAction &DstMIBuilder, 1823 const std::vector<Record *> &ImplicitDefs) const { 1824 if (!ImplicitDefs.empty()) 1825 return failedImport("Pattern defines a physical register"); 1826 return Error::success(); 1827 } 1828 1829 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) { 1830 // Keep track of the matchers and actions to emit. 1831 RuleMatcher M; 1832 M.addAction<DebugCommentAction>(P); 1833 1834 if (auto Error = importRulePredicates(M, P.getPredicates()->getValues())) 1835 return std::move(Error); 1836 1837 // Next, analyze the pattern operators. 1838 TreePatternNode *Src = P.getSrcPattern(); 1839 TreePatternNode *Dst = P.getDstPattern(); 1840 1841 // If the root of either pattern isn't a simple operator, ignore it. 1842 if (auto Err = isTrivialOperatorNode(Dst)) 1843 return failedImport("Dst pattern root isn't a trivial operator (" + 1844 toString(std::move(Err)) + ")"); 1845 if (auto Err = isTrivialOperatorNode(Src)) 1846 return failedImport("Src pattern root isn't a trivial operator (" + 1847 toString(std::move(Err)) + ")"); 1848 1849 if (Dst->isLeaf()) 1850 return failedImport("Dst pattern root isn't a known leaf"); 1851 1852 // Start with the defined operands (i.e., the results of the root operator). 1853 Record *DstOp = Dst->getOperator(); 1854 if (!DstOp->isSubClassOf("Instruction")) 1855 return failedImport("Pattern operator isn't an instruction"); 1856 1857 auto &DstI = Target.getInstruction(DstOp); 1858 if (DstI.Operands.NumDefs != Src->getExtTypes().size()) 1859 return failedImport("Src pattern results and dst MI defs are different (" + 1860 to_string(Src->getExtTypes().size()) + " def(s) vs " + 1861 to_string(DstI.Operands.NumDefs) + " def(s))"); 1862 1863 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(); 1864 auto InsnMatcherOrError = createAndImportSelDAGMatcher(InsnMatcherTemp, Src); 1865 if (auto Error = InsnMatcherOrError.takeError()) 1866 return std::move(Error); 1867 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get(); 1868 1869 // The root of the match also has constraints on the register bank so that it 1870 // matches the result instruction. 1871 unsigned OpIdx = 0; 1872 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) { 1873 (void)Ty; 1874 1875 const auto &DstIOperand = DstI.Operands[OpIdx]; 1876 Record *DstIOpRec = DstIOperand.Rec; 1877 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") { 1878 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue()); 1879 1880 if (DstIOpRec == nullptr) 1881 return failedImport( 1882 "COPY_TO_REGCLASS operand #1 isn't a register class"); 1883 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") { 1884 if (!Dst->getChild(0)->isLeaf()) 1885 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf"); 1886 1887 // We can assume that a subregister is in the same bank as it's super 1888 // register. 1889 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()); 1890 1891 if (DstIOpRec == nullptr) 1892 return failedImport( 1893 "EXTRACT_SUBREG operand #0 isn't a register class"); 1894 } else if (DstIOpRec->isSubClassOf("RegisterOperand")) 1895 DstIOpRec = DstIOpRec->getValueAsDef("RegClass"); 1896 else if (!DstIOpRec->isSubClassOf("RegisterClass")) 1897 return failedImport("Dst MI def isn't a register class" + 1898 to_string(*Dst)); 1899 1900 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx); 1901 OM.setSymbolicName(DstIOperand.Name); 1902 OM.addPredicate<RegisterBankOperandMatcher>( 1903 Target.getRegisterClass(DstIOpRec)); 1904 ++OpIdx; 1905 } 1906 1907 auto DstMIBuilderOrError = 1908 createAndImportInstructionRenderer(M, Dst, InsnMatcher); 1909 if (auto Error = DstMIBuilderOrError.takeError()) 1910 return std::move(Error); 1911 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get(); 1912 1913 // Render the implicit defs. 1914 // These are only added to the root of the result. 1915 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs())) 1916 return std::move(Error); 1917 1918 // Constrain the registers to classes. This is normally derived from the 1919 // emitted instruction but a few instructions require special handling. 1920 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") { 1921 // COPY_TO_REGCLASS does not provide operand constraints itself but the 1922 // result is constrained to the class given by the second child. 1923 Record *DstIOpRec = 1924 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue()); 1925 1926 if (DstIOpRec == nullptr) 1927 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class"); 1928 1929 M.addAction<ConstrainOperandToRegClassAction>( 1930 0, 0, Target.getRegisterClass(DstIOpRec)); 1931 1932 // We're done with this pattern! It's eligible for GISel emission; return 1933 // it. 1934 ++NumPatternImported; 1935 return std::move(M); 1936 } 1937 1938 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") { 1939 // EXTRACT_SUBREG selects into a subregister COPY but unlike most 1940 // instructions, the result register class is controlled by the 1941 // subregisters of the operand. As a result, we must constrain the result 1942 // class rather than check that it's already the right one. 1943 if (!Dst->getChild(0)->isLeaf()) 1944 return failedImport("EXTRACT_SUBREG child #1 is not a leaf"); 1945 1946 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue()); 1947 if (!SubRegInit) 1948 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index"); 1949 1950 // Constrain the result to the same register bank as the operand. 1951 Record *DstIOpRec = 1952 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()); 1953 1954 if (DstIOpRec == nullptr) 1955 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class"); 1956 1957 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef()); 1958 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec); 1959 1960 // It would be nice to leave this constraint implicit but we're required 1961 // to pick a register class so constrain the result to a register class 1962 // that can hold the correct MVT. 1963 // 1964 // FIXME: This may introduce an extra copy if the chosen class doesn't 1965 // actually contain the subregisters. 1966 assert(Src->getExtTypes().size() == 1 && 1967 "Expected Src of EXTRACT_SUBREG to have one result type"); 1968 1969 const auto &SrcRCDstRCPair = 1970 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx); 1971 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass"); 1972 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second); 1973 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first); 1974 1975 // We're done with this pattern! It's eligible for GISel emission; return 1976 // it. 1977 ++NumPatternImported; 1978 return std::move(M); 1979 } 1980 1981 M.addAction<ConstrainOperandsToDefinitionAction>(0); 1982 1983 // We're done with this pattern! It's eligible for GISel emission; return it. 1984 ++NumPatternImported; 1985 return std::move(M); 1986 } 1987 1988 void GlobalISelEmitter::run(raw_ostream &OS) { 1989 // Track the GINodeEquiv definitions. 1990 gatherNodeEquivs(); 1991 1992 emitSourceFileHeader(("Global Instruction Selector for the " + 1993 Target.getName() + " target").str(), OS); 1994 std::vector<RuleMatcher> Rules; 1995 // Look through the SelectionDAG patterns we found, possibly emitting some. 1996 for (const PatternToMatch &Pat : CGP.ptms()) { 1997 ++NumPatternTotal; 1998 auto MatcherOrErr = runOnPattern(Pat); 1999 2000 // The pattern analysis can fail, indicating an unsupported pattern. 2001 // Report that if we've been asked to do so. 2002 if (auto Err = MatcherOrErr.takeError()) { 2003 if (WarnOnSkippedPatterns) { 2004 PrintWarning(Pat.getSrcRecord()->getLoc(), 2005 "Skipped pattern: " + toString(std::move(Err))); 2006 } else { 2007 consumeError(std::move(Err)); 2008 } 2009 ++NumPatternImportsSkipped; 2010 continue; 2011 } 2012 2013 Rules.push_back(std::move(MatcherOrErr.get())); 2014 } 2015 2016 std::stable_sort(Rules.begin(), Rules.end(), 2017 [&](const RuleMatcher &A, const RuleMatcher &B) { 2018 if (A.isHigherPriorityThan(B)) { 2019 assert(!B.isHigherPriorityThan(A) && "Cannot be more important " 2020 "and less important at " 2021 "the same time"); 2022 return true; 2023 } 2024 return false; 2025 }); 2026 2027 std::vector<Record *> ComplexPredicates = 2028 RK.getAllDerivedDefinitions("GIComplexOperandMatcher"); 2029 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(), 2030 [](const Record *A, const Record *B) { 2031 if (A->getName() < B->getName()) 2032 return true; 2033 return false; 2034 }); 2035 unsigned MaxTemporaries = 0; 2036 for (const auto &Rule : Rules) 2037 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns()); 2038 2039 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n" 2040 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size() 2041 << ";\n" 2042 << "using PredicateBitset = " 2043 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n" 2044 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n"; 2045 2046 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n" 2047 << " mutable MatcherState State;\n" 2048 << " typedef " 2049 "ComplexRendererFn(" 2050 << Target.getName() 2051 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n" 2052 << "const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> " 2053 "MatcherInfo;\n" 2054 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n"; 2055 2056 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n" 2057 << ", State(" << MaxTemporaries << "),\n" 2058 << "MatcherInfo({TypeObjects, FeatureBitsets, {\n" 2059 << " nullptr, // GICP_Invalid\n"; 2060 for (const auto &Record : ComplexPredicates) 2061 OS << " &" << Target.getName() 2062 << "InstructionSelector::" << Record->getValueAsString("MatcherFn") 2063 << ", // " << Record->getName() << "\n"; 2064 OS << "}})\n" 2065 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n"; 2066 2067 OS << "#ifdef GET_GLOBALISEL_IMPL\n"; 2068 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures, 2069 OS); 2070 2071 // Separate subtarget features by how often they must be recomputed. 2072 SubtargetFeatureInfoMap ModuleFeatures; 2073 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(), 2074 std::inserter(ModuleFeatures, ModuleFeatures.end()), 2075 [](const SubtargetFeatureInfoMap::value_type &X) { 2076 return !X.second.mustRecomputePerFunction(); 2077 }); 2078 SubtargetFeatureInfoMap FunctionFeatures; 2079 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(), 2080 std::inserter(FunctionFeatures, FunctionFeatures.end()), 2081 [](const SubtargetFeatureInfoMap::value_type &X) { 2082 return X.second.mustRecomputePerFunction(); 2083 }); 2084 2085 SubtargetFeatureInfo::emitComputeAvailableFeatures( 2086 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures", 2087 ModuleFeatures, OS); 2088 SubtargetFeatureInfo::emitComputeAvailableFeatures( 2089 Target.getName(), "InstructionSelector", 2090 "computeAvailableFunctionFeatures", FunctionFeatures, OS, 2091 "const MachineFunction *MF"); 2092 2093 // Emit a table containing the LLT objects needed by the matcher and an enum 2094 // for the matcher to reference them with. 2095 std::vector<LLTCodeGen> TypeObjects = { 2096 LLT::scalar(8), LLT::scalar(16), LLT::scalar(32), 2097 LLT::scalar(64), LLT::scalar(80), LLT::vector(8, 1), 2098 LLT::vector(16, 1), LLT::vector(32, 1), LLT::vector(64, 1), 2099 LLT::vector(8, 8), LLT::vector(16, 8), LLT::vector(32, 8), 2100 LLT::vector(64, 8), LLT::vector(4, 16), LLT::vector(8, 16), 2101 LLT::vector(16, 16), LLT::vector(32, 16), LLT::vector(2, 32), 2102 LLT::vector(4, 32), LLT::vector(8, 32), LLT::vector(16, 32), 2103 LLT::vector(2, 64), LLT::vector(4, 64), LLT::vector(8, 64), 2104 }; 2105 std::sort(TypeObjects.begin(), TypeObjects.end()); 2106 OS << "enum {\n"; 2107 for (const auto &TypeObject : TypeObjects) { 2108 OS << " "; 2109 TypeObject.emitCxxEnumValue(OS); 2110 OS << ",\n"; 2111 } 2112 OS << "};\n" 2113 << "const static LLT TypeObjects[] = {\n"; 2114 for (const auto &TypeObject : TypeObjects) { 2115 OS << " "; 2116 TypeObject.emitCxxConstructorCall(OS); 2117 OS << ",\n"; 2118 } 2119 OS << "};\n\n"; 2120 2121 // Emit a table containing the PredicateBitsets objects needed by the matcher 2122 // and an enum for the matcher to reference them with. 2123 std::vector<std::vector<Record *>> FeatureBitsets; 2124 for (auto &Rule : Rules) 2125 FeatureBitsets.push_back(Rule.getRequiredFeatures()); 2126 std::sort( 2127 FeatureBitsets.begin(), FeatureBitsets.end(), 2128 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) { 2129 if (A.size() < B.size()) 2130 return true; 2131 if (A.size() > B.size()) 2132 return false; 2133 for (const auto &Pair : zip(A, B)) { 2134 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName()) 2135 return true; 2136 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName()) 2137 return false; 2138 } 2139 return false; 2140 }); 2141 FeatureBitsets.erase( 2142 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()), 2143 FeatureBitsets.end()); 2144 OS << "enum {\n" 2145 << " GIFBS_Invalid,\n"; 2146 for (const auto &FeatureBitset : FeatureBitsets) { 2147 if (FeatureBitset.empty()) 2148 continue; 2149 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n"; 2150 } 2151 OS << "};\n" 2152 << "const static PredicateBitset FeatureBitsets[] {\n" 2153 << " {}, // GIFBS_Invalid\n"; 2154 for (const auto &FeatureBitset : FeatureBitsets) { 2155 if (FeatureBitset.empty()) 2156 continue; 2157 OS << " {"; 2158 for (const auto &Feature : FeatureBitset) { 2159 const auto &I = SubtargetFeatures.find(Feature); 2160 assert(I != SubtargetFeatures.end() && "Didn't import predicate?"); 2161 OS << I->second.getEnumBitName() << ", "; 2162 } 2163 OS << "},\n"; 2164 } 2165 OS << "};\n\n"; 2166 2167 // Emit complex predicate table and an enum to reference them with. 2168 OS << "enum {\n" 2169 << " GICP_Invalid,\n"; 2170 for (const auto &Record : ComplexPredicates) 2171 OS << " GICP_" << Record->getName() << ",\n"; 2172 OS << "};\n" 2173 << "// See constructor for table contents\n\n"; 2174 2175 OS << "bool " << Target.getName() 2176 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n" 2177 << " MachineFunction &MF = *I.getParent()->getParent();\n" 2178 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n" 2179 << " // FIXME: This should be computed on a per-function basis rather " 2180 "than per-insn.\n" 2181 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, " 2182 "&MF);\n" 2183 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n" 2184 << " NewMIVector OutMIs;\n" 2185 << " State.MIs.clear();\n" 2186 << " State.MIs.push_back(&I);\n\n"; 2187 2188 for (auto &Rule : Rules) { 2189 Rule.emit(OS); 2190 ++CurrentMatchTableID; 2191 ++NumPatternEmitted; 2192 assert(CurrentMatchTableID == NumPatternEmitted && 2193 "Statistic deviates from number of emitted tables"); 2194 } 2195 2196 OS << " return false;\n" 2197 << "}\n" 2198 << "#endif // ifdef GET_GLOBALISEL_IMPL\n"; 2199 2200 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n" 2201 << "PredicateBitset AvailableModuleFeatures;\n" 2202 << "mutable PredicateBitset AvailableFunctionFeatures;\n" 2203 << "PredicateBitset getAvailableFeatures() const {\n" 2204 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n" 2205 << "}\n" 2206 << "PredicateBitset\n" 2207 << "computeAvailableModuleFeatures(const " << Target.getName() 2208 << "Subtarget *Subtarget) const;\n" 2209 << "PredicateBitset\n" 2210 << "computeAvailableFunctionFeatures(const " << Target.getName() 2211 << "Subtarget *Subtarget,\n" 2212 << " const MachineFunction *MF) const;\n" 2213 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n"; 2214 2215 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n" 2216 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n" 2217 << "AvailableFunctionFeatures()\n" 2218 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n"; 2219 } 2220 2221 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) { 2222 if (SubtargetFeatures.count(Predicate) == 0) 2223 SubtargetFeatures.emplace( 2224 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size())); 2225 } 2226 2227 } // end anonymous namespace 2228 2229 //===----------------------------------------------------------------------===// 2230 2231 namespace llvm { 2232 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) { 2233 GlobalISelEmitter(RK).run(OS); 2234 } 2235 } // End llvm namespace 2236