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 69 /// Get the name of the enum value used to number the predicate function. 70 std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) { 71 return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" + 72 Predicate.getFnName(); 73 } 74 75 /// Get the opcode used to check this predicate. 76 std::string getMatchOpcodeForPredicate(const TreePredicateFn &Predicate) { 77 return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate"; 78 } 79 80 /// This class stands in for LLT wherever we want to tablegen-erate an 81 /// equivalent at compiler run-time. 82 class LLTCodeGen { 83 private: 84 LLT Ty; 85 86 public: 87 LLTCodeGen(const LLT &Ty) : Ty(Ty) {} 88 89 std::string getCxxEnumValue() const { 90 std::string Str; 91 raw_string_ostream OS(Str); 92 93 emitCxxEnumValue(OS); 94 return OS.str(); 95 } 96 97 void emitCxxEnumValue(raw_ostream &OS) const { 98 if (Ty.isScalar()) { 99 OS << "GILLT_s" << Ty.getSizeInBits(); 100 return; 101 } 102 if (Ty.isVector()) { 103 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits(); 104 return; 105 } 106 if (Ty.isPointer()) { 107 OS << "GILLT_p" << Ty.getAddressSpace(); 108 if (Ty.getSizeInBits() > 0) 109 OS << "s" << Ty.getSizeInBits(); 110 return; 111 } 112 llvm_unreachable("Unhandled LLT"); 113 } 114 115 void emitCxxConstructorCall(raw_ostream &OS) const { 116 if (Ty.isScalar()) { 117 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")"; 118 return; 119 } 120 if (Ty.isVector()) { 121 OS << "LLT::vector(" << Ty.getNumElements() << ", " 122 << Ty.getScalarSizeInBits() << ")"; 123 return; 124 } 125 if (Ty.isPointer() && Ty.getSizeInBits() > 0) { 126 OS << "LLT::pointer(" << Ty.getAddressSpace() << ", " 127 << Ty.getSizeInBits() << ")"; 128 return; 129 } 130 llvm_unreachable("Unhandled LLT"); 131 } 132 133 const LLT &get() const { return Ty; } 134 135 /// This ordering is used for std::unique() and std::sort(). There's no 136 /// particular logic behind the order but either A < B or B < A must be 137 /// true if A != B. 138 bool operator<(const LLTCodeGen &Other) const { 139 if (Ty.isValid() != Other.Ty.isValid()) 140 return Ty.isValid() < Other.Ty.isValid(); 141 if (!Ty.isValid()) 142 return false; 143 144 if (Ty.isVector() != Other.Ty.isVector()) 145 return Ty.isVector() < Other.Ty.isVector(); 146 if (Ty.isScalar() != Other.Ty.isScalar()) 147 return Ty.isScalar() < Other.Ty.isScalar(); 148 if (Ty.isPointer() != Other.Ty.isPointer()) 149 return Ty.isPointer() < Other.Ty.isPointer(); 150 151 if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace()) 152 return Ty.getAddressSpace() < Other.Ty.getAddressSpace(); 153 154 if (Ty.isVector() && Ty.getNumElements() != Other.Ty.getNumElements()) 155 return Ty.getNumElements() < Other.Ty.getNumElements(); 156 157 return Ty.getSizeInBits() < Other.Ty.getSizeInBits(); 158 } 159 }; 160 161 class InstructionMatcher; 162 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for 163 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...). 164 static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) { 165 MVT VT(SVT); 166 167 if (VT.isVector() && VT.getVectorNumElements() != 1) 168 return LLTCodeGen( 169 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits())); 170 171 if (VT.isInteger() || VT.isFloatingPoint()) 172 return LLTCodeGen(LLT::scalar(VT.getSizeInBits())); 173 return None; 174 } 175 176 static std::string explainPredicates(const TreePatternNode *N) { 177 std::string Explanation = ""; 178 StringRef Separator = ""; 179 for (const auto &P : N->getPredicateFns()) { 180 Explanation += 181 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str(); 182 if (P.isAlwaysTrue()) 183 Explanation += " always-true"; 184 if (P.isImmediatePattern()) 185 Explanation += " immediate"; 186 187 if (P.isUnindexed()) 188 Explanation += " unindexed"; 189 190 if (P.isNonExtLoad()) 191 Explanation += " non-extload"; 192 if (P.isAnyExtLoad()) 193 Explanation += " extload"; 194 if (P.isSignExtLoad()) 195 Explanation += " sextload"; 196 if (P.isZeroExtLoad()) 197 Explanation += " zextload"; 198 199 if (P.isNonTruncStore()) 200 Explanation += " non-truncstore"; 201 if (P.isTruncStore()) 202 Explanation += " truncstore"; 203 204 if (Record *VT = P.getMemoryVT()) 205 Explanation += (" MemVT=" + VT->getName()).str(); 206 if (Record *VT = P.getScalarMemoryVT()) 207 Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str(); 208 } 209 return Explanation; 210 } 211 212 std::string explainOperator(Record *Operator) { 213 if (Operator->isSubClassOf("SDNode")) 214 return (" (" + Operator->getValueAsString("Opcode") + ")").str(); 215 216 if (Operator->isSubClassOf("Intrinsic")) 217 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str(); 218 219 if (Operator->isSubClassOf("ComplexPattern")) 220 return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() + 221 ")") 222 .str(); 223 224 return (" (Operator " + Operator->getName() + " not understood)").str(); 225 } 226 227 /// Helper function to let the emitter report skip reason error messages. 228 static Error failedImport(const Twine &Reason) { 229 return make_error<StringError>(Reason, inconvertibleErrorCode()); 230 } 231 232 static Error isTrivialOperatorNode(const TreePatternNode *N) { 233 std::string Explanation = ""; 234 std::string Separator = ""; 235 236 bool HasUnsupportedPredicate = false; 237 for (const auto &Predicate : N->getPredicateFns()) { 238 if (Predicate.isAlwaysTrue()) 239 continue; 240 241 if (Predicate.isImmediatePattern()) 242 continue; 243 244 if (Predicate.isLoad() && Predicate.isUnindexed()) 245 continue; 246 247 if (Predicate.isNonExtLoad()) 248 continue; 249 250 if (Predicate.isStore() && Predicate.isUnindexed()) 251 continue; 252 253 if (Predicate.isNonTruncStore()) 254 continue; 255 256 HasUnsupportedPredicate = true; 257 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")"; 258 Separator = ", "; 259 Explanation += (Separator + "first-failing:" + 260 Predicate.getOrigPatFragRecord()->getRecord()->getName()) 261 .str(); 262 break; 263 } 264 265 if (N->getTransformFn()) { 266 Explanation += Separator + "Has a transform function"; 267 Separator = ", "; 268 } 269 270 if (!HasUnsupportedPredicate && !N->getTransformFn()) 271 return Error::success(); 272 273 return failedImport(Explanation); 274 } 275 276 static Record *getInitValueAsRegClass(Init *V) { 277 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) { 278 if (VDefInit->getDef()->isSubClassOf("RegisterOperand")) 279 return VDefInit->getDef()->getValueAsDef("RegClass"); 280 if (VDefInit->getDef()->isSubClassOf("RegisterClass")) 281 return VDefInit->getDef(); 282 } 283 return nullptr; 284 } 285 286 std::string 287 getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) { 288 std::string Name = "GIFBS"; 289 for (const auto &Feature : FeatureBitset) 290 Name += ("_" + Feature->getName()).str(); 291 return Name; 292 } 293 294 //===- MatchTable Helpers -------------------------------------------------===// 295 296 class MatchTable; 297 298 /// A record to be stored in a MatchTable. 299 /// 300 /// This class represents any and all output that may be required to emit the 301 /// MatchTable. Instances are most often configured to represent an opcode or 302 /// value that will be emitted to the table with some formatting but it can also 303 /// represent commas, comments, and other formatting instructions. 304 struct MatchTableRecord { 305 enum RecordFlagsBits { 306 MTRF_None = 0x0, 307 /// Causes EmitStr to be formatted as comment when emitted. 308 MTRF_Comment = 0x1, 309 /// Causes the record value to be followed by a comma when emitted. 310 MTRF_CommaFollows = 0x2, 311 /// Causes the record value to be followed by a line break when emitted. 312 MTRF_LineBreakFollows = 0x4, 313 /// Indicates that the record defines a label and causes an additional 314 /// comment to be emitted containing the index of the label. 315 MTRF_Label = 0x8, 316 /// Causes the record to be emitted as the index of the label specified by 317 /// LabelID along with a comment indicating where that label is. 318 MTRF_JumpTarget = 0x10, 319 /// Causes the formatter to add a level of indentation before emitting the 320 /// record. 321 MTRF_Indent = 0x20, 322 /// Causes the formatter to remove a level of indentation after emitting the 323 /// record. 324 MTRF_Outdent = 0x40, 325 }; 326 327 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to 328 /// reference or define. 329 unsigned LabelID; 330 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a 331 /// value, a label name. 332 std::string EmitStr; 333 334 private: 335 /// The number of MatchTable elements described by this record. Comments are 0 336 /// while values are typically 1. Values >1 may occur when we need to emit 337 /// values that exceed the size of a MatchTable element. 338 unsigned NumElements; 339 340 public: 341 /// A bitfield of RecordFlagsBits flags. 342 unsigned Flags; 343 344 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr, 345 unsigned NumElements, unsigned Flags) 346 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u), 347 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) { 348 assert((!LabelID_.hasValue() || LabelID != ~0u) && 349 "This value is reserved for non-labels"); 350 } 351 352 void emit(raw_ostream &OS, bool LineBreakNextAfterThis, 353 const MatchTable &Table) const; 354 unsigned size() const { return NumElements; } 355 }; 356 357 /// Holds the contents of a generated MatchTable to enable formatting and the 358 /// necessary index tracking needed to support GIM_Try. 359 class MatchTable { 360 /// An unique identifier for the table. The generated table will be named 361 /// MatchTable${ID}. 362 unsigned ID; 363 /// The records that make up the table. Also includes comments describing the 364 /// values being emitted and line breaks to format it. 365 std::vector<MatchTableRecord> Contents; 366 /// The currently defined labels. 367 DenseMap<unsigned, unsigned> LabelMap; 368 /// Tracks the sum of MatchTableRecord::NumElements as the table is built. 369 unsigned CurrentSize; 370 371 /// A unique identifier for a MatchTable label. 372 static unsigned CurrentLabelID; 373 374 public: 375 static MatchTableRecord LineBreak; 376 static MatchTableRecord Comment(StringRef Comment) { 377 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment); 378 } 379 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) { 380 unsigned ExtraFlags = 0; 381 if (IndentAdjust > 0) 382 ExtraFlags |= MatchTableRecord::MTRF_Indent; 383 if (IndentAdjust < 0) 384 ExtraFlags |= MatchTableRecord::MTRF_Outdent; 385 386 return MatchTableRecord(None, Opcode, 1, 387 MatchTableRecord::MTRF_CommaFollows | ExtraFlags); 388 } 389 static MatchTableRecord NamedValue(StringRef NamedValue) { 390 return MatchTableRecord(None, NamedValue, 1, 391 MatchTableRecord::MTRF_CommaFollows); 392 } 393 static MatchTableRecord NamedValue(StringRef Namespace, 394 StringRef NamedValue) { 395 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1, 396 MatchTableRecord::MTRF_CommaFollows); 397 } 398 static MatchTableRecord IntValue(int64_t IntValue) { 399 return MatchTableRecord(None, llvm::to_string(IntValue), 1, 400 MatchTableRecord::MTRF_CommaFollows); 401 } 402 static MatchTableRecord Label(unsigned LabelID) { 403 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0, 404 MatchTableRecord::MTRF_Label | 405 MatchTableRecord::MTRF_Comment | 406 MatchTableRecord::MTRF_LineBreakFollows); 407 } 408 static MatchTableRecord JumpTarget(unsigned LabelID) { 409 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1, 410 MatchTableRecord::MTRF_JumpTarget | 411 MatchTableRecord::MTRF_Comment | 412 MatchTableRecord::MTRF_CommaFollows); 413 } 414 415 MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {} 416 417 void push_back(const MatchTableRecord &Value) { 418 if (Value.Flags & MatchTableRecord::MTRF_Label) 419 defineLabel(Value.LabelID); 420 Contents.push_back(Value); 421 CurrentSize += Value.size(); 422 } 423 424 unsigned allocateLabelID() const { return CurrentLabelID++; } 425 426 void defineLabel(unsigned LabelID) { 427 LabelMap.insert(std::make_pair(LabelID, CurrentSize)); 428 } 429 430 unsigned getLabelIndex(unsigned LabelID) const { 431 const auto I = LabelMap.find(LabelID); 432 assert(I != LabelMap.end() && "Use of undeclared label"); 433 return I->second; 434 } 435 436 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; } 437 438 void emitDeclaration(raw_ostream &OS) const { 439 unsigned Indentation = 4; 440 OS << " constexpr static int64_t MatchTable" << ID << "[] = {"; 441 LineBreak.emit(OS, true, *this); 442 OS << std::string(Indentation, ' '); 443 444 for (auto I = Contents.begin(), E = Contents.end(); I != E; 445 ++I) { 446 bool LineBreakIsNext = false; 447 const auto &NextI = std::next(I); 448 449 if (NextI != E) { 450 if (NextI->EmitStr == "" && 451 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows) 452 LineBreakIsNext = true; 453 } 454 455 if (I->Flags & MatchTableRecord::MTRF_Indent) 456 Indentation += 2; 457 458 I->emit(OS, LineBreakIsNext, *this); 459 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows) 460 OS << std::string(Indentation, ' '); 461 462 if (I->Flags & MatchTableRecord::MTRF_Outdent) 463 Indentation -= 2; 464 } 465 OS << "};\n"; 466 } 467 }; 468 469 unsigned MatchTable::CurrentLabelID = 0; 470 471 MatchTableRecord MatchTable::LineBreak = { 472 None, "" /* Emit String */, 0 /* Elements */, 473 MatchTableRecord::MTRF_LineBreakFollows}; 474 475 void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis, 476 const MatchTable &Table) const { 477 bool UseLineComment = 478 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows); 479 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows)) 480 UseLineComment = false; 481 482 if (Flags & MTRF_Comment) 483 OS << (UseLineComment ? "// " : "/*"); 484 485 OS << EmitStr; 486 if (Flags & MTRF_Label) 487 OS << ": @" << Table.getLabelIndex(LabelID); 488 489 if (Flags & MTRF_Comment && !UseLineComment) 490 OS << "*/"; 491 492 if (Flags & MTRF_JumpTarget) { 493 if (Flags & MTRF_Comment) 494 OS << " "; 495 OS << Table.getLabelIndex(LabelID); 496 } 497 498 if (Flags & MTRF_CommaFollows) { 499 OS << ","; 500 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows)) 501 OS << " "; 502 } 503 504 if (Flags & MTRF_LineBreakFollows) 505 OS << "\n"; 506 } 507 508 MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) { 509 Table.push_back(Value); 510 return Table; 511 } 512 513 //===- Matchers -----------------------------------------------------------===// 514 515 class OperandMatcher; 516 class MatchAction; 517 518 /// Generates code to check that a match rule matches. 519 class RuleMatcher { 520 public: 521 using ActionVec = std::vector<std::unique_ptr<MatchAction>>; 522 using action_iterator = ActionVec::iterator; 523 524 protected: 525 /// A list of matchers that all need to succeed for the current rule to match. 526 /// FIXME: This currently supports a single match position but could be 527 /// extended to support multiple positions to support div/rem fusion or 528 /// load-multiple instructions. 529 std::vector<std::unique_ptr<InstructionMatcher>> Matchers; 530 531 /// A list of actions that need to be taken when all predicates in this rule 532 /// have succeeded. 533 ActionVec Actions; 534 535 using DefinedInsnVariablesMap = 536 std::map<const InstructionMatcher *, unsigned>; 537 538 /// A map of instruction matchers to the local variables created by 539 /// emitCaptureOpcodes(). 540 DefinedInsnVariablesMap InsnVariableIDs; 541 542 using MutatableInsnSet = SmallPtrSet<const InstructionMatcher *, 4>; 543 544 // The set of instruction matchers that have not yet been claimed for mutation 545 // by a BuildMI. 546 MutatableInsnSet MutatableInsns; 547 548 /// A map of named operands defined by the matchers that may be referenced by 549 /// the renderers. 550 StringMap<OperandMatcher *> DefinedOperands; 551 552 /// ID for the next instruction variable defined with defineInsnVar() 553 unsigned NextInsnVarID; 554 555 /// ID for the next output instruction allocated with allocateOutputInsnID() 556 unsigned NextOutputInsnID; 557 558 std::vector<Record *> RequiredFeatures; 559 560 ArrayRef<SMLoc> SrcLoc; 561 562 typedef std::tuple<Record *, unsigned, unsigned> 563 DefinedComplexPatternSubOperand; 564 typedef StringMap<DefinedComplexPatternSubOperand> 565 DefinedComplexPatternSubOperandMap; 566 /// A map of Symbolic Names to ComplexPattern sub-operands. 567 DefinedComplexPatternSubOperandMap ComplexSubOperands; 568 569 public: 570 RuleMatcher(ArrayRef<SMLoc> SrcLoc) 571 : Matchers(), Actions(), InsnVariableIDs(), MutatableInsns(), 572 DefinedOperands(), NextInsnVarID(0), NextOutputInsnID(0), 573 SrcLoc(SrcLoc), ComplexSubOperands() {} 574 RuleMatcher(RuleMatcher &&Other) = default; 575 RuleMatcher &operator=(RuleMatcher &&Other) = default; 576 577 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName); 578 void addRequiredFeature(Record *Feature); 579 const std::vector<Record *> &getRequiredFeatures() const; 580 581 template <class Kind, class... Args> Kind &addAction(Args &&... args); 582 template <class Kind, class... Args> 583 action_iterator insertAction(action_iterator InsertPt, Args &&... args); 584 585 /// Define an instruction without emitting any code to do so. 586 /// This is used for the root of the match. 587 unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher); 588 /// Define an instruction and emit corresponding state-machine opcodes. 589 unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher, 590 unsigned InsnVarID, unsigned OpIdx); 591 unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const; 592 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const { 593 return InsnVariableIDs.begin(); 594 } 595 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const { 596 return InsnVariableIDs.end(); 597 } 598 iterator_range<typename DefinedInsnVariablesMap::const_iterator> 599 defined_insn_vars() const { 600 return make_range(defined_insn_vars_begin(), defined_insn_vars_end()); 601 } 602 603 MutatableInsnSet::const_iterator mutatable_insns_begin() const { 604 return MutatableInsns.begin(); 605 } 606 MutatableInsnSet::const_iterator mutatable_insns_end() const { 607 return MutatableInsns.end(); 608 } 609 iterator_range<typename MutatableInsnSet::const_iterator> 610 mutatable_insns() const { 611 return make_range(mutatable_insns_begin(), mutatable_insns_end()); 612 } 613 void reserveInsnMatcherForMutation(const InstructionMatcher *InsnMatcher) { 614 bool R = MutatableInsns.erase(InsnMatcher); 615 assert(R && "Reserving a mutatable insn that isn't available"); 616 (void)R; 617 } 618 619 action_iterator actions_begin() { return Actions.begin(); } 620 action_iterator actions_end() { return Actions.end(); } 621 iterator_range<action_iterator> actions() { 622 return make_range(actions_begin(), actions_end()); 623 } 624 625 void defineOperand(StringRef SymbolicName, OperandMatcher &OM); 626 627 void defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern, 628 unsigned RendererID, unsigned SubOperandID) { 629 assert(ComplexSubOperands.count(SymbolicName) == 0 && "Already defined"); 630 ComplexSubOperands[SymbolicName] = 631 std::make_tuple(ComplexPattern, RendererID, SubOperandID); 632 } 633 Optional<DefinedComplexPatternSubOperand> 634 getComplexSubOperand(StringRef SymbolicName) const { 635 const auto &I = ComplexSubOperands.find(SymbolicName); 636 if (I == ComplexSubOperands.end()) 637 return None; 638 return I->second; 639 } 640 641 const InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const; 642 const OperandMatcher &getOperandMatcher(StringRef Name) const; 643 644 void emitCaptureOpcodes(MatchTable &Table); 645 646 void emit(MatchTable &Table); 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 RuleMatcher &B) const; 652 653 /// Report the maximum number of temporary operands needed by the rule 654 /// matcher. 655 unsigned countRendererFns() const; 656 657 // FIXME: Remove this as soon as possible 658 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); } 659 660 unsigned allocateOutputInsnID() { return NextOutputInsnID++; } 661 }; 662 663 using action_iterator = RuleMatcher::action_iterator; 664 665 template <class PredicateTy> class PredicateListMatcher { 666 private: 667 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec; 668 PredicateVec Predicates; 669 670 /// Template instantiations should specialize this to return a string to use 671 /// for the comment emitted when there are no predicates. 672 std::string getNoPredicateComment() const; 673 674 public: 675 /// Construct a new operand predicate and add it to the matcher. 676 template <class Kind, class... Args> 677 Optional<Kind *> addPredicate(Args&&... args) { 678 Predicates.emplace_back( 679 llvm::make_unique<Kind>(std::forward<Args>(args)...)); 680 return static_cast<Kind *>(Predicates.back().get()); 681 } 682 683 typename PredicateVec::const_iterator predicates_begin() const { 684 return Predicates.begin(); 685 } 686 typename PredicateVec::const_iterator predicates_end() const { 687 return Predicates.end(); 688 } 689 iterator_range<typename PredicateVec::const_iterator> predicates() const { 690 return make_range(predicates_begin(), predicates_end()); 691 } 692 typename PredicateVec::size_type predicates_size() const { 693 return Predicates.size(); 694 } 695 696 /// Emit MatchTable opcodes that tests whether all the predicates are met. 697 template <class... Args> 698 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const { 699 if (Predicates.empty()) { 700 Table << MatchTable::Comment(getNoPredicateComment()) 701 << MatchTable::LineBreak; 702 return; 703 } 704 705 for (const auto &Predicate : predicates()) 706 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...); 707 } 708 }; 709 710 /// Generates code to check a predicate of an operand. 711 /// 712 /// Typical predicates include: 713 /// * Operand is a particular register. 714 /// * Operand is assigned a particular register bank. 715 /// * Operand is an MBB. 716 class OperandPredicateMatcher { 717 public: 718 /// This enum is used for RTTI and also defines the priority that is given to 719 /// the predicate when generating the matcher code. Kinds with higher priority 720 /// must be tested first. 721 /// 722 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter 723 /// but OPM_Int must have priority over OPM_RegBank since constant integers 724 /// are represented by a virtual register defined by a G_CONSTANT instruction. 725 enum PredicateKind { 726 OPM_SameOperand, 727 OPM_ComplexPattern, 728 OPM_IntrinsicID, 729 OPM_Instruction, 730 OPM_Int, 731 OPM_LiteralInt, 732 OPM_LLT, 733 OPM_PointerToAny, 734 OPM_RegBank, 735 OPM_MBB, 736 }; 737 738 protected: 739 PredicateKind Kind; 740 741 public: 742 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {} 743 virtual ~OperandPredicateMatcher() {} 744 745 PredicateKind getKind() const { return Kind; } 746 747 /// Emit MatchTable opcodes to capture instructions into the MIs table. 748 /// 749 /// Only InstructionOperandMatcher needs to do anything for this method the 750 /// rest just walk the tree. 751 virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule, 752 unsigned InsnVarID, unsigned OpIdx) const {} 753 754 /// Emit MatchTable opcodes that check the predicate for the given operand. 755 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 756 unsigned InsnVarID, 757 unsigned OpIdx) const = 0; 758 759 /// Compare the priority of this object and B. 760 /// 761 /// Returns true if this object is more important than B. 762 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const; 763 764 /// Report the maximum number of temporary operands needed by the predicate 765 /// matcher. 766 virtual unsigned countRendererFns() const { return 0; } 767 }; 768 769 template <> 770 std::string 771 PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const { 772 return "No operand predicates"; 773 } 774 775 /// Generates code to check that a register operand is defined by the same exact 776 /// one as another. 777 class SameOperandMatcher : public OperandPredicateMatcher { 778 std::string MatchingName; 779 780 public: 781 SameOperandMatcher(StringRef MatchingName) 782 : OperandPredicateMatcher(OPM_SameOperand), MatchingName(MatchingName) {} 783 784 static bool classof(const OperandPredicateMatcher *P) { 785 return P->getKind() == OPM_SameOperand; 786 } 787 788 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 789 unsigned InsnVarID, unsigned OpIdx) const override; 790 }; 791 792 /// Generates code to check that an operand is a particular LLT. 793 class LLTOperandMatcher : public OperandPredicateMatcher { 794 protected: 795 LLTCodeGen Ty; 796 797 public: 798 static std::set<LLTCodeGen> KnownTypes; 799 800 LLTOperandMatcher(const LLTCodeGen &Ty) 801 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) { 802 KnownTypes.insert(Ty); 803 } 804 805 static bool classof(const OperandPredicateMatcher *P) { 806 return P->getKind() == OPM_LLT; 807 } 808 809 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 810 unsigned InsnVarID, unsigned OpIdx) const override { 811 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI") 812 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op") 813 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type") 814 << MatchTable::NamedValue(Ty.getCxxEnumValue()) 815 << MatchTable::LineBreak; 816 } 817 }; 818 819 std::set<LLTCodeGen> LLTOperandMatcher::KnownTypes; 820 821 /// Generates code to check that an operand is a pointer to any address space. 822 /// 823 /// In SelectionDAG, the types did not describe pointers or address spaces. As a 824 /// result, iN is used to describe a pointer of N bits to any address space and 825 /// PatFrag predicates are typically used to constrain the address space. There's 826 /// no reliable means to derive the missing type information from the pattern so 827 /// imported rules must test the components of a pointer separately. 828 /// 829 /// If SizeInBits is zero, then the pointer size will be obtained from the 830 /// subtarget. 831 class PointerToAnyOperandMatcher : public OperandPredicateMatcher { 832 protected: 833 unsigned SizeInBits; 834 835 public: 836 PointerToAnyOperandMatcher(unsigned SizeInBits) 837 : OperandPredicateMatcher(OPM_PointerToAny), SizeInBits(SizeInBits) {} 838 839 static bool classof(const OperandPredicateMatcher *P) { 840 return P->getKind() == OPM_PointerToAny; 841 } 842 843 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 844 unsigned InsnVarID, unsigned OpIdx) const override { 845 Table << MatchTable::Opcode("GIM_CheckPointerToAny") << MatchTable::Comment("MI") 846 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op") 847 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("SizeInBits") 848 << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak; 849 } 850 }; 851 852 /// Generates code to check that an operand is a particular target constant. 853 class ComplexPatternOperandMatcher : public OperandPredicateMatcher { 854 protected: 855 const OperandMatcher &Operand; 856 const Record &TheDef; 857 858 unsigned getAllocatedTemporariesBaseID() const; 859 860 public: 861 ComplexPatternOperandMatcher(const OperandMatcher &Operand, 862 const Record &TheDef) 863 : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand), 864 TheDef(TheDef) {} 865 866 static bool classof(const OperandPredicateMatcher *P) { 867 return P->getKind() == OPM_ComplexPattern; 868 } 869 870 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 871 unsigned InsnVarID, unsigned OpIdx) const override { 872 unsigned ID = getAllocatedTemporariesBaseID(); 873 Table << MatchTable::Opcode("GIM_CheckComplexPattern") 874 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 875 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 876 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID) 877 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str()) 878 << MatchTable::LineBreak; 879 } 880 881 unsigned countRendererFns() const override { 882 return 1; 883 } 884 }; 885 886 /// Generates code to check that an operand is in a particular register bank. 887 class RegisterBankOperandMatcher : public OperandPredicateMatcher { 888 protected: 889 const CodeGenRegisterClass &RC; 890 891 public: 892 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC) 893 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {} 894 895 static bool classof(const OperandPredicateMatcher *P) { 896 return P->getKind() == OPM_RegBank; 897 } 898 899 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 900 unsigned InsnVarID, unsigned OpIdx) const override { 901 Table << MatchTable::Opcode("GIM_CheckRegBankForClass") 902 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 903 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 904 << MatchTable::Comment("RC") 905 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID") 906 << MatchTable::LineBreak; 907 } 908 }; 909 910 /// Generates code to check that an operand is a basic block. 911 class MBBOperandMatcher : public OperandPredicateMatcher { 912 public: 913 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {} 914 915 static bool classof(const OperandPredicateMatcher *P) { 916 return P->getKind() == OPM_MBB; 917 } 918 919 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 920 unsigned InsnVarID, unsigned OpIdx) const override { 921 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI") 922 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op") 923 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak; 924 } 925 }; 926 927 /// Generates code to check that an operand is a G_CONSTANT with a particular 928 /// int. 929 class ConstantIntOperandMatcher : public OperandPredicateMatcher { 930 protected: 931 int64_t Value; 932 933 public: 934 ConstantIntOperandMatcher(int64_t Value) 935 : OperandPredicateMatcher(OPM_Int), Value(Value) {} 936 937 static bool classof(const OperandPredicateMatcher *P) { 938 return P->getKind() == OPM_Int; 939 } 940 941 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 942 unsigned InsnVarID, unsigned OpIdx) const override { 943 Table << MatchTable::Opcode("GIM_CheckConstantInt") 944 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 945 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 946 << MatchTable::IntValue(Value) << MatchTable::LineBreak; 947 } 948 }; 949 950 /// Generates code to check that an operand is a raw int (where MO.isImm() or 951 /// MO.isCImm() is true). 952 class LiteralIntOperandMatcher : public OperandPredicateMatcher { 953 protected: 954 int64_t Value; 955 956 public: 957 LiteralIntOperandMatcher(int64_t Value) 958 : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {} 959 960 static bool classof(const OperandPredicateMatcher *P) { 961 return P->getKind() == OPM_LiteralInt; 962 } 963 964 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 965 unsigned InsnVarID, unsigned OpIdx) const override { 966 Table << MatchTable::Opcode("GIM_CheckLiteralInt") 967 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 968 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 969 << MatchTable::IntValue(Value) << MatchTable::LineBreak; 970 } 971 }; 972 973 /// Generates code to check that an operand is an intrinsic ID. 974 class IntrinsicIDOperandMatcher : public OperandPredicateMatcher { 975 protected: 976 const CodeGenIntrinsic *II; 977 978 public: 979 IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II) 980 : OperandPredicateMatcher(OPM_IntrinsicID), II(II) {} 981 982 static bool classof(const OperandPredicateMatcher *P) { 983 return P->getKind() == OPM_IntrinsicID; 984 } 985 986 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 987 unsigned InsnVarID, unsigned OpIdx) const override { 988 Table << MatchTable::Opcode("GIM_CheckIntrinsicID") 989 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 990 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 991 << MatchTable::NamedValue("Intrinsic::" + II->EnumName) 992 << MatchTable::LineBreak; 993 } 994 }; 995 996 /// Generates code to check that a set of predicates match for a particular 997 /// operand. 998 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> { 999 protected: 1000 InstructionMatcher &Insn; 1001 unsigned OpIdx; 1002 std::string SymbolicName; 1003 1004 /// The index of the first temporary variable allocated to this operand. The 1005 /// number of allocated temporaries can be found with 1006 /// countRendererFns(). 1007 unsigned AllocatedTemporariesBaseID; 1008 1009 public: 1010 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx, 1011 const std::string &SymbolicName, 1012 unsigned AllocatedTemporariesBaseID) 1013 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName), 1014 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {} 1015 1016 bool hasSymbolicName() const { return !SymbolicName.empty(); } 1017 const StringRef getSymbolicName() const { return SymbolicName; } 1018 void setSymbolicName(StringRef Name) { 1019 assert(SymbolicName.empty() && "Operand already has a symbolic name"); 1020 SymbolicName = Name; 1021 } 1022 unsigned getOperandIndex() const { return OpIdx; } 1023 1024 std::string getOperandExpr(unsigned InsnVarID) const { 1025 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" + 1026 llvm::to_string(OpIdx) + ")"; 1027 } 1028 1029 InstructionMatcher &getInstructionMatcher() const { return Insn; } 1030 1031 Error addTypeCheckPredicate(const TypeSetByHwMode &VTy, 1032 bool OperandIsAPointer); 1033 1034 /// Emit MatchTable opcodes to capture instructions into the MIs table. 1035 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule, 1036 unsigned InsnVarID) const { 1037 for (const auto &Predicate : predicates()) 1038 Predicate->emitCaptureOpcodes(Table, Rule, InsnVarID, OpIdx); 1039 } 1040 1041 /// Emit MatchTable opcodes that test whether the instruction named in 1042 /// InsnVarID matches all the predicates and all the operands. 1043 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 1044 unsigned InsnVarID) const { 1045 std::string Comment; 1046 raw_string_ostream CommentOS(Comment); 1047 CommentOS << "MIs[" << InsnVarID << "] "; 1048 if (SymbolicName.empty()) 1049 CommentOS << "Operand " << OpIdx; 1050 else 1051 CommentOS << SymbolicName; 1052 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak; 1053 1054 emitPredicateListOpcodes(Table, Rule, InsnVarID, OpIdx); 1055 } 1056 1057 /// Compare the priority of this object and B. 1058 /// 1059 /// Returns true if this object is more important than B. 1060 bool isHigherPriorityThan(const OperandMatcher &B) const { 1061 // Operand matchers involving more predicates have higher priority. 1062 if (predicates_size() > B.predicates_size()) 1063 return true; 1064 if (predicates_size() < B.predicates_size()) 1065 return false; 1066 1067 // This assumes that predicates are added in a consistent order. 1068 for (const auto &Predicate : zip(predicates(), B.predicates())) { 1069 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate))) 1070 return true; 1071 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate))) 1072 return false; 1073 } 1074 1075 return false; 1076 }; 1077 1078 /// Report the maximum number of temporary operands needed by the operand 1079 /// matcher. 1080 unsigned countRendererFns() const { 1081 return std::accumulate( 1082 predicates().begin(), predicates().end(), 0, 1083 [](unsigned A, 1084 const std::unique_ptr<OperandPredicateMatcher> &Predicate) { 1085 return A + Predicate->countRendererFns(); 1086 }); 1087 } 1088 1089 unsigned getAllocatedTemporariesBaseID() const { 1090 return AllocatedTemporariesBaseID; 1091 } 1092 1093 bool isSameAsAnotherOperand() const { 1094 for (const auto &Predicate : predicates()) 1095 if (isa<SameOperandMatcher>(Predicate)) 1096 return true; 1097 return false; 1098 } 1099 }; 1100 1101 // Specialize OperandMatcher::addPredicate() to refrain from adding redundant 1102 // predicates. 1103 template <> 1104 template <class Kind, class... Args> 1105 Optional<Kind *> 1106 PredicateListMatcher<OperandPredicateMatcher>::addPredicate(Args &&... args) { 1107 if (static_cast<OperandMatcher *>(this)->isSameAsAnotherOperand()) 1108 return None; 1109 Predicates.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...)); 1110 return static_cast<Kind *>(Predicates.back().get()); 1111 } 1112 1113 Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy, 1114 bool OperandIsAPointer) { 1115 if (!VTy.isMachineValueType()) 1116 return failedImport("unsupported typeset"); 1117 1118 if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) { 1119 addPredicate<PointerToAnyOperandMatcher>(0); 1120 return Error::success(); 1121 } 1122 1123 auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy); 1124 if (!OpTyOrNone) 1125 return failedImport("unsupported type"); 1126 1127 if (OperandIsAPointer) 1128 addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits()); 1129 else 1130 addPredicate<LLTOperandMatcher>(*OpTyOrNone); 1131 return Error::success(); 1132 } 1133 1134 unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const { 1135 return Operand.getAllocatedTemporariesBaseID(); 1136 } 1137 1138 /// Generates code to check a predicate on an instruction. 1139 /// 1140 /// Typical predicates include: 1141 /// * The opcode of the instruction is a particular value. 1142 /// * The nsw/nuw flag is/isn't set. 1143 class InstructionPredicateMatcher { 1144 protected: 1145 /// This enum is used for RTTI and also defines the priority that is given to 1146 /// the predicate when generating the matcher code. Kinds with higher priority 1147 /// must be tested first. 1148 enum PredicateKind { 1149 IPM_Opcode, 1150 IPM_ImmPredicate, 1151 IPM_NonAtomicMMO, 1152 }; 1153 1154 PredicateKind Kind; 1155 1156 public: 1157 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {} 1158 virtual ~InstructionPredicateMatcher() {} 1159 1160 PredicateKind getKind() const { return Kind; } 1161 1162 /// Emit MatchTable opcodes that test whether the instruction named in 1163 /// InsnVarID matches the predicate. 1164 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 1165 unsigned InsnVarID) const = 0; 1166 1167 /// Compare the priority of this object and B. 1168 /// 1169 /// Returns true if this object is more important than B. 1170 virtual bool 1171 isHigherPriorityThan(const InstructionPredicateMatcher &B) const { 1172 return Kind < B.Kind; 1173 }; 1174 1175 /// Report the maximum number of temporary operands needed by the predicate 1176 /// matcher. 1177 virtual unsigned countRendererFns() const { return 0; } 1178 }; 1179 1180 template <> 1181 std::string 1182 PredicateListMatcher<InstructionPredicateMatcher>::getNoPredicateComment() const { 1183 return "No instruction predicates"; 1184 } 1185 1186 /// Generates code to check the opcode of an instruction. 1187 class InstructionOpcodeMatcher : public InstructionPredicateMatcher { 1188 protected: 1189 const CodeGenInstruction *I; 1190 1191 public: 1192 InstructionOpcodeMatcher(const CodeGenInstruction *I) 1193 : InstructionPredicateMatcher(IPM_Opcode), I(I) {} 1194 1195 static bool classof(const InstructionPredicateMatcher *P) { 1196 return P->getKind() == IPM_Opcode; 1197 } 1198 1199 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 1200 unsigned InsnVarID) const override { 1201 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI") 1202 << MatchTable::IntValue(InsnVarID) 1203 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName()) 1204 << MatchTable::LineBreak; 1205 } 1206 1207 /// Compare the priority of this object and B. 1208 /// 1209 /// Returns true if this object is more important than B. 1210 bool 1211 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override { 1212 if (InstructionPredicateMatcher::isHigherPriorityThan(B)) 1213 return true; 1214 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this)) 1215 return false; 1216 1217 // Prioritize opcodes for cosmetic reasons in the generated source. Although 1218 // this is cosmetic at the moment, we may want to drive a similar ordering 1219 // using instruction frequency information to improve compile time. 1220 if (const InstructionOpcodeMatcher *BO = 1221 dyn_cast<InstructionOpcodeMatcher>(&B)) 1222 return I->TheDef->getName() < BO->I->TheDef->getName(); 1223 1224 return false; 1225 }; 1226 1227 bool isConstantInstruction() const { 1228 return I->TheDef->getName() == "G_CONSTANT"; 1229 } 1230 }; 1231 1232 /// Generates code to check that this instruction is a constant whose value 1233 /// meets an immediate predicate. 1234 /// 1235 /// Immediates are slightly odd since they are typically used like an operand 1236 /// but are represented as an operator internally. We typically write simm8:$src 1237 /// in a tablegen pattern, but this is just syntactic sugar for 1238 /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes 1239 /// that will be matched and the predicate (which is attached to the imm 1240 /// operator) that will be tested. In SelectionDAG this describes a 1241 /// ConstantSDNode whose internal value will be tested using the simm8 predicate. 1242 /// 1243 /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In 1244 /// this representation, the immediate could be tested with an 1245 /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a 1246 /// OperandPredicateMatcher-subclass to check the Value meets the predicate but 1247 /// there are two implementation issues with producing that matcher 1248 /// configuration from the SelectionDAG pattern: 1249 /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that 1250 /// were we to sink the immediate predicate to the operand we would have to 1251 /// have two partial implementations of PatFrag support, one for immediates 1252 /// and one for non-immediates. 1253 /// * At the point we handle the predicate, the OperandMatcher hasn't been 1254 /// created yet. If we were to sink the predicate to the OperandMatcher we 1255 /// would also have to complicate (or duplicate) the code that descends and 1256 /// creates matchers for the subtree. 1257 /// Overall, it's simpler to handle it in the place it was found. 1258 class InstructionImmPredicateMatcher : public InstructionPredicateMatcher { 1259 protected: 1260 TreePredicateFn Predicate; 1261 1262 public: 1263 InstructionImmPredicateMatcher(const TreePredicateFn &Predicate) 1264 : InstructionPredicateMatcher(IPM_ImmPredicate), Predicate(Predicate) {} 1265 1266 static bool classof(const InstructionPredicateMatcher *P) { 1267 return P->getKind() == IPM_ImmPredicate; 1268 } 1269 1270 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 1271 unsigned InsnVarID) const override { 1272 Table << MatchTable::Opcode(getMatchOpcodeForPredicate(Predicate)) 1273 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1274 << MatchTable::Comment("Predicate") 1275 << MatchTable::NamedValue(getEnumNameForPredicate(Predicate)) 1276 << MatchTable::LineBreak; 1277 } 1278 }; 1279 1280 /// Generates code to check that a memory instruction has a non-atomic MachineMemoryOperand. 1281 class NonAtomicMMOPredicateMatcher : public InstructionPredicateMatcher { 1282 public: 1283 NonAtomicMMOPredicateMatcher() 1284 : InstructionPredicateMatcher(IPM_NonAtomicMMO) {} 1285 1286 static bool classof(const InstructionPredicateMatcher *P) { 1287 return P->getKind() == IPM_NonAtomicMMO; 1288 } 1289 1290 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 1291 unsigned InsnVarID) const override { 1292 Table << MatchTable::Opcode("GIM_CheckNonAtomic") 1293 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 1294 << MatchTable::LineBreak; 1295 } 1296 }; 1297 1298 /// Generates code to check that a set of predicates and operands match for a 1299 /// particular instruction. 1300 /// 1301 /// Typical predicates include: 1302 /// * Has a specific opcode. 1303 /// * Has an nsw/nuw flag or doesn't. 1304 class InstructionMatcher 1305 : public PredicateListMatcher<InstructionPredicateMatcher> { 1306 protected: 1307 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec; 1308 1309 RuleMatcher &Rule; 1310 1311 /// The operands to match. All rendered operands must be present even if the 1312 /// condition is always true. 1313 OperandVec Operands; 1314 1315 std::string SymbolicName; 1316 1317 public: 1318 InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName) 1319 : Rule(Rule), SymbolicName(SymbolicName) {} 1320 1321 RuleMatcher &getRuleMatcher() const { return Rule; } 1322 1323 /// Add an operand to the matcher. 1324 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName, 1325 unsigned AllocatedTemporariesBaseID) { 1326 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName, 1327 AllocatedTemporariesBaseID)); 1328 if (!SymbolicName.empty()) 1329 Rule.defineOperand(SymbolicName, *Operands.back()); 1330 1331 return *Operands.back(); 1332 } 1333 1334 OperandMatcher &getOperand(unsigned OpIdx) { 1335 auto I = std::find_if(Operands.begin(), Operands.end(), 1336 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) { 1337 return X->getOperandIndex() == OpIdx; 1338 }); 1339 if (I != Operands.end()) 1340 return **I; 1341 llvm_unreachable("Failed to lookup operand"); 1342 } 1343 1344 StringRef getSymbolicName() const { return SymbolicName; } 1345 unsigned getNumOperands() const { return Operands.size(); } 1346 OperandVec::iterator operands_begin() { return Operands.begin(); } 1347 OperandVec::iterator operands_end() { return Operands.end(); } 1348 iterator_range<OperandVec::iterator> operands() { 1349 return make_range(operands_begin(), operands_end()); 1350 } 1351 OperandVec::const_iterator operands_begin() const { return Operands.begin(); } 1352 OperandVec::const_iterator operands_end() const { return Operands.end(); } 1353 iterator_range<OperandVec::const_iterator> operands() const { 1354 return make_range(operands_begin(), operands_end()); 1355 } 1356 1357 /// Emit MatchTable opcodes to check the shape of the match and capture 1358 /// instructions into the MIs table. 1359 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule, 1360 unsigned InsnID) { 1361 Table << MatchTable::Opcode("GIM_CheckNumOperands") 1362 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID) 1363 << MatchTable::Comment("Expected") 1364 << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak; 1365 for (const auto &Operand : Operands) 1366 Operand->emitCaptureOpcodes(Table, Rule, InsnID); 1367 } 1368 1369 /// Emit MatchTable opcodes that test whether the instruction named in 1370 /// InsnVarName matches all the predicates and all the operands. 1371 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 1372 unsigned InsnVarID) const { 1373 emitPredicateListOpcodes(Table, Rule, InsnVarID); 1374 for (const auto &Operand : Operands) 1375 Operand->emitPredicateOpcodes(Table, Rule, InsnVarID); 1376 } 1377 1378 /// Compare the priority of this object and B. 1379 /// 1380 /// Returns true if this object is more important than B. 1381 bool isHigherPriorityThan(const InstructionMatcher &B) const { 1382 // Instruction matchers involving more operands have higher priority. 1383 if (Operands.size() > B.Operands.size()) 1384 return true; 1385 if (Operands.size() < B.Operands.size()) 1386 return false; 1387 1388 for (const auto &Predicate : zip(predicates(), B.predicates())) { 1389 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate))) 1390 return true; 1391 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate))) 1392 return false; 1393 } 1394 1395 for (const auto &Operand : zip(Operands, B.Operands)) { 1396 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand))) 1397 return true; 1398 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand))) 1399 return false; 1400 } 1401 1402 return false; 1403 }; 1404 1405 /// Report the maximum number of temporary operands needed by the instruction 1406 /// matcher. 1407 unsigned countRendererFns() const { 1408 return std::accumulate(predicates().begin(), predicates().end(), 0, 1409 [](unsigned A, 1410 const std::unique_ptr<InstructionPredicateMatcher> 1411 &Predicate) { 1412 return A + Predicate->countRendererFns(); 1413 }) + 1414 std::accumulate( 1415 Operands.begin(), Operands.end(), 0, 1416 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) { 1417 return A + Operand->countRendererFns(); 1418 }); 1419 } 1420 1421 bool isConstantInstruction() const { 1422 for (const auto &P : predicates()) 1423 if (const InstructionOpcodeMatcher *Opcode = 1424 dyn_cast<InstructionOpcodeMatcher>(P.get())) 1425 return Opcode->isConstantInstruction(); 1426 return false; 1427 } 1428 }; 1429 1430 /// Generates code to check that the operand is a register defined by an 1431 /// instruction that matches the given instruction matcher. 1432 /// 1433 /// For example, the pattern: 1434 /// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3)) 1435 /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match 1436 /// the: 1437 /// (G_ADD $src1, $src2) 1438 /// subpattern. 1439 class InstructionOperandMatcher : public OperandPredicateMatcher { 1440 protected: 1441 std::unique_ptr<InstructionMatcher> InsnMatcher; 1442 1443 public: 1444 InstructionOperandMatcher(RuleMatcher &Rule, StringRef SymbolicName) 1445 : OperandPredicateMatcher(OPM_Instruction), 1446 InsnMatcher(new InstructionMatcher(Rule, SymbolicName)) {} 1447 1448 static bool classof(const OperandPredicateMatcher *P) { 1449 return P->getKind() == OPM_Instruction; 1450 } 1451 1452 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; } 1453 1454 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule, 1455 unsigned InsnID, unsigned OpIdx) const override { 1456 unsigned InsnVarID = Rule.defineInsnVar(Table, *InsnMatcher, InsnID, OpIdx); 1457 InsnMatcher->emitCaptureOpcodes(Table, Rule, InsnVarID); 1458 } 1459 1460 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule, 1461 unsigned InsnVarID_, 1462 unsigned OpIdx_) const override { 1463 unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher); 1464 InsnMatcher->emitPredicateOpcodes(Table, Rule, InsnVarID); 1465 } 1466 }; 1467 1468 //===- Actions ------------------------------------------------------------===// 1469 class OperandRenderer { 1470 public: 1471 enum RendererKind { 1472 OR_Copy, 1473 OR_CopyOrAddZeroReg, 1474 OR_CopySubReg, 1475 OR_CopyConstantAsImm, 1476 OR_CopyFConstantAsFPImm, 1477 OR_Imm, 1478 OR_Register, 1479 OR_ComplexPattern 1480 }; 1481 1482 protected: 1483 RendererKind Kind; 1484 1485 public: 1486 OperandRenderer(RendererKind Kind) : Kind(Kind) {} 1487 virtual ~OperandRenderer() {} 1488 1489 RendererKind getKind() const { return Kind; } 1490 1491 virtual void emitRenderOpcodes(MatchTable &Table, 1492 RuleMatcher &Rule) const = 0; 1493 }; 1494 1495 /// A CopyRenderer emits code to copy a single operand from an existing 1496 /// instruction to the one being built. 1497 class CopyRenderer : public OperandRenderer { 1498 protected: 1499 unsigned NewInsnID; 1500 /// The name of the operand. 1501 const StringRef SymbolicName; 1502 1503 public: 1504 CopyRenderer(unsigned NewInsnID, StringRef SymbolicName) 1505 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), 1506 SymbolicName(SymbolicName) { 1507 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source"); 1508 } 1509 1510 static bool classof(const OperandRenderer *R) { 1511 return R->getKind() == OR_Copy; 1512 } 1513 1514 const StringRef getSymbolicName() const { return SymbolicName; } 1515 1516 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1517 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName); 1518 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); 1519 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID") 1520 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID") 1521 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx") 1522 << MatchTable::IntValue(Operand.getOperandIndex()) 1523 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 1524 } 1525 }; 1526 1527 /// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an 1528 /// existing instruction to the one being built. If the operand turns out to be 1529 /// a 'G_CONSTANT 0' then it replaces the operand with a zero register. 1530 class CopyOrAddZeroRegRenderer : public OperandRenderer { 1531 protected: 1532 unsigned NewInsnID; 1533 /// The name of the operand. 1534 const StringRef SymbolicName; 1535 const Record *ZeroRegisterDef; 1536 1537 public: 1538 CopyOrAddZeroRegRenderer(unsigned NewInsnID, 1539 StringRef SymbolicName, Record *ZeroRegisterDef) 1540 : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID), 1541 SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) { 1542 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source"); 1543 } 1544 1545 static bool classof(const OperandRenderer *R) { 1546 return R->getKind() == OR_CopyOrAddZeroReg; 1547 } 1548 1549 const StringRef getSymbolicName() const { return SymbolicName; } 1550 1551 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1552 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName); 1553 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); 1554 Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg") 1555 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID) 1556 << MatchTable::Comment("OldInsnID") 1557 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx") 1558 << MatchTable::IntValue(Operand.getOperandIndex()) 1559 << MatchTable::NamedValue( 1560 (ZeroRegisterDef->getValue("Namespace") 1561 ? ZeroRegisterDef->getValueAsString("Namespace") 1562 : ""), 1563 ZeroRegisterDef->getName()) 1564 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 1565 } 1566 }; 1567 1568 /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to 1569 /// an extended immediate operand. 1570 class CopyConstantAsImmRenderer : public OperandRenderer { 1571 protected: 1572 unsigned NewInsnID; 1573 /// The name of the operand. 1574 const std::string SymbolicName; 1575 bool Signed; 1576 1577 public: 1578 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName) 1579 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID), 1580 SymbolicName(SymbolicName), Signed(true) {} 1581 1582 static bool classof(const OperandRenderer *R) { 1583 return R->getKind() == OR_CopyConstantAsImm; 1584 } 1585 1586 const StringRef getSymbolicName() const { return SymbolicName; } 1587 1588 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1589 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName); 1590 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher); 1591 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm" 1592 : "GIR_CopyConstantAsUImm") 1593 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID) 1594 << MatchTable::Comment("OldInsnID") 1595 << MatchTable::IntValue(OldInsnVarID) 1596 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 1597 } 1598 }; 1599 1600 /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT 1601 /// instruction to an extended immediate operand. 1602 class CopyFConstantAsFPImmRenderer : public OperandRenderer { 1603 protected: 1604 unsigned NewInsnID; 1605 /// The name of the operand. 1606 const std::string SymbolicName; 1607 1608 public: 1609 CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName) 1610 : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID), 1611 SymbolicName(SymbolicName) {} 1612 1613 static bool classof(const OperandRenderer *R) { 1614 return R->getKind() == OR_CopyFConstantAsFPImm; 1615 } 1616 1617 const StringRef getSymbolicName() const { return SymbolicName; } 1618 1619 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1620 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName); 1621 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher); 1622 Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm") 1623 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID) 1624 << MatchTable::Comment("OldInsnID") 1625 << MatchTable::IntValue(OldInsnVarID) 1626 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 1627 } 1628 }; 1629 1630 /// A CopySubRegRenderer emits code to copy a single register operand from an 1631 /// existing instruction to the one being built and indicate that only a 1632 /// subregister should be copied. 1633 class CopySubRegRenderer : public OperandRenderer { 1634 protected: 1635 unsigned NewInsnID; 1636 /// The name of the operand. 1637 const StringRef SymbolicName; 1638 /// The subregister to extract. 1639 const CodeGenSubRegIndex *SubReg; 1640 1641 public: 1642 CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName, 1643 const CodeGenSubRegIndex *SubReg) 1644 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), 1645 SymbolicName(SymbolicName), SubReg(SubReg) {} 1646 1647 static bool classof(const OperandRenderer *R) { 1648 return R->getKind() == OR_CopySubReg; 1649 } 1650 1651 const StringRef getSymbolicName() const { return SymbolicName; } 1652 1653 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1654 const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName); 1655 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher()); 1656 Table << MatchTable::Opcode("GIR_CopySubReg") 1657 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID) 1658 << MatchTable::Comment("OldInsnID") 1659 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx") 1660 << MatchTable::IntValue(Operand.getOperandIndex()) 1661 << MatchTable::Comment("SubRegIdx") 1662 << MatchTable::IntValue(SubReg->EnumValue) 1663 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 1664 } 1665 }; 1666 1667 /// Adds a specific physical register to the instruction being built. 1668 /// This is typically useful for WZR/XZR on AArch64. 1669 class AddRegisterRenderer : public OperandRenderer { 1670 protected: 1671 unsigned InsnID; 1672 const Record *RegisterDef; 1673 1674 public: 1675 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef) 1676 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) { 1677 } 1678 1679 static bool classof(const OperandRenderer *R) { 1680 return R->getKind() == OR_Register; 1681 } 1682 1683 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1684 Table << MatchTable::Opcode("GIR_AddRegister") 1685 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 1686 << MatchTable::NamedValue( 1687 (RegisterDef->getValue("Namespace") 1688 ? RegisterDef->getValueAsString("Namespace") 1689 : ""), 1690 RegisterDef->getName()) 1691 << MatchTable::LineBreak; 1692 } 1693 }; 1694 1695 /// Adds a specific immediate to the instruction being built. 1696 class ImmRenderer : public OperandRenderer { 1697 protected: 1698 unsigned InsnID; 1699 int64_t Imm; 1700 1701 public: 1702 ImmRenderer(unsigned InsnID, int64_t Imm) 1703 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {} 1704 1705 static bool classof(const OperandRenderer *R) { 1706 return R->getKind() == OR_Imm; 1707 } 1708 1709 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1710 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID") 1711 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm") 1712 << MatchTable::IntValue(Imm) << MatchTable::LineBreak; 1713 } 1714 }; 1715 1716 /// Adds operands by calling a renderer function supplied by the ComplexPattern 1717 /// matcher function. 1718 class RenderComplexPatternOperand : public OperandRenderer { 1719 private: 1720 unsigned InsnID; 1721 const Record &TheDef; 1722 /// The name of the operand. 1723 const StringRef SymbolicName; 1724 /// The renderer number. This must be unique within a rule since it's used to 1725 /// identify a temporary variable to hold the renderer function. 1726 unsigned RendererID; 1727 /// When provided, this is the suboperand of the ComplexPattern operand to 1728 /// render. Otherwise all the suboperands will be rendered. 1729 Optional<unsigned> SubOperand; 1730 1731 unsigned getNumOperands() const { 1732 return TheDef.getValueAsDag("Operands")->getNumArgs(); 1733 } 1734 1735 public: 1736 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef, 1737 StringRef SymbolicName, unsigned RendererID, 1738 Optional<unsigned> SubOperand = None) 1739 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef), 1740 SymbolicName(SymbolicName), RendererID(RendererID), 1741 SubOperand(SubOperand) {} 1742 1743 static bool classof(const OperandRenderer *R) { 1744 return R->getKind() == OR_ComplexPattern; 1745 } 1746 1747 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1748 Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer" 1749 : "GIR_ComplexRenderer") 1750 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 1751 << MatchTable::Comment("RendererID") 1752 << MatchTable::IntValue(RendererID); 1753 if (SubOperand.hasValue()) 1754 Table << MatchTable::Comment("SubOperand") 1755 << MatchTable::IntValue(SubOperand.getValue()); 1756 Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak; 1757 } 1758 }; 1759 1760 /// An action taken when all Matcher predicates succeeded for a parent rule. 1761 /// 1762 /// Typical actions include: 1763 /// * Changing the opcode of an instruction. 1764 /// * Adding an operand to an instruction. 1765 class MatchAction { 1766 public: 1767 virtual ~MatchAction() {} 1768 1769 /// Emit the MatchTable opcodes to implement the action. 1770 virtual void emitActionOpcodes(MatchTable &Table, 1771 RuleMatcher &Rule) const = 0; 1772 }; 1773 1774 /// Generates a comment describing the matched rule being acted upon. 1775 class DebugCommentAction : public MatchAction { 1776 private: 1777 std::string S; 1778 1779 public: 1780 DebugCommentAction(StringRef S) : S(S) {} 1781 1782 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1783 Table << MatchTable::Comment(S) << MatchTable::LineBreak; 1784 } 1785 }; 1786 1787 /// Generates code to build an instruction or mutate an existing instruction 1788 /// into the desired instruction when this is possible. 1789 class BuildMIAction : public MatchAction { 1790 private: 1791 unsigned InsnID; 1792 const CodeGenInstruction *I; 1793 const InstructionMatcher *Matched; 1794 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers; 1795 1796 /// True if the instruction can be built solely by mutating the opcode. 1797 bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const { 1798 if (!Insn) 1799 return false; 1800 1801 if (OperandRenderers.size() != Insn->getNumOperands()) 1802 return false; 1803 1804 for (const auto &Renderer : enumerate(OperandRenderers)) { 1805 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) { 1806 const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName()); 1807 if (Insn != &OM.getInstructionMatcher() || 1808 OM.getOperandIndex() != Renderer.index()) 1809 return false; 1810 } else 1811 return false; 1812 } 1813 1814 return true; 1815 } 1816 1817 public: 1818 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I) 1819 : InsnID(InsnID), I(I), Matched(nullptr) {} 1820 1821 const CodeGenInstruction *getCGI() const { return I; } 1822 1823 void chooseInsnToMutate(RuleMatcher &Rule) { 1824 for (const auto *MutateCandidate : Rule.mutatable_insns()) { 1825 if (canMutate(Rule, MutateCandidate)) { 1826 // Take the first one we're offered that we're able to mutate. 1827 Rule.reserveInsnMatcherForMutation(MutateCandidate); 1828 Matched = MutateCandidate; 1829 return; 1830 } 1831 } 1832 } 1833 1834 template <class Kind, class... Args> 1835 Kind &addRenderer(Args&&... args) { 1836 OperandRenderers.emplace_back( 1837 llvm::make_unique<Kind>(InsnID, std::forward<Args>(args)...)); 1838 return *static_cast<Kind *>(OperandRenderers.back().get()); 1839 } 1840 1841 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1842 if (Matched) { 1843 assert(canMutate(Rule, Matched) && 1844 "Arranged to mutate an insn that isn't mutatable"); 1845 1846 unsigned RecycleInsnID = Rule.getInsnVarID(*Matched); 1847 Table << MatchTable::Opcode("GIR_MutateOpcode") 1848 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 1849 << MatchTable::Comment("RecycleInsnID") 1850 << MatchTable::IntValue(RecycleInsnID) 1851 << MatchTable::Comment("Opcode") 1852 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName()) 1853 << MatchTable::LineBreak; 1854 1855 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) { 1856 for (auto Def : I->ImplicitDefs) { 1857 auto Namespace = Def->getValue("Namespace") 1858 ? Def->getValueAsString("Namespace") 1859 : ""; 1860 Table << MatchTable::Opcode("GIR_AddImplicitDef") 1861 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 1862 << MatchTable::NamedValue(Namespace, Def->getName()) 1863 << MatchTable::LineBreak; 1864 } 1865 for (auto Use : I->ImplicitUses) { 1866 auto Namespace = Use->getValue("Namespace") 1867 ? Use->getValueAsString("Namespace") 1868 : ""; 1869 Table << MatchTable::Opcode("GIR_AddImplicitUse") 1870 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 1871 << MatchTable::NamedValue(Namespace, Use->getName()) 1872 << MatchTable::LineBreak; 1873 } 1874 } 1875 return; 1876 } 1877 1878 // TODO: Simple permutation looks like it could be almost as common as 1879 // mutation due to commutative operations. 1880 1881 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID") 1882 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode") 1883 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName()) 1884 << MatchTable::LineBreak; 1885 for (const auto &Renderer : OperandRenderers) 1886 Renderer->emitRenderOpcodes(Table, Rule); 1887 1888 if (I->mayLoad || I->mayStore) { 1889 Table << MatchTable::Opcode("GIR_MergeMemOperands") 1890 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 1891 << MatchTable::Comment("MergeInsnID's"); 1892 // Emit the ID's for all the instructions that are matched by this rule. 1893 // TODO: Limit this to matched instructions that mayLoad/mayStore or have 1894 // some other means of having a memoperand. Also limit this to 1895 // emitted instructions that expect to have a memoperand too. For 1896 // example, (G_SEXT (G_LOAD x)) that results in separate load and 1897 // sign-extend instructions shouldn't put the memoperand on the 1898 // sign-extend since it has no effect there. 1899 std::vector<unsigned> MergeInsnIDs; 1900 for (const auto &IDMatcherPair : Rule.defined_insn_vars()) 1901 MergeInsnIDs.push_back(IDMatcherPair.second); 1902 std::sort(MergeInsnIDs.begin(), MergeInsnIDs.end()); 1903 for (const auto &MergeInsnID : MergeInsnIDs) 1904 Table << MatchTable::IntValue(MergeInsnID); 1905 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList") 1906 << MatchTable::LineBreak; 1907 } 1908 1909 Table << MatchTable::Opcode("GIR_EraseFromParent") 1910 << MatchTable::Comment("InsnID") << MatchTable::IntValue(0) 1911 << MatchTable::LineBreak; 1912 } 1913 }; 1914 1915 /// Generates code to constrain the operands of an output instruction to the 1916 /// register classes specified by the definition of that instruction. 1917 class ConstrainOperandsToDefinitionAction : public MatchAction { 1918 unsigned InsnID; 1919 1920 public: 1921 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {} 1922 1923 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1924 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands") 1925 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 1926 << MatchTable::LineBreak; 1927 } 1928 }; 1929 1930 /// Generates code to constrain the specified operand of an output instruction 1931 /// to the specified register class. 1932 class ConstrainOperandToRegClassAction : public MatchAction { 1933 unsigned InsnID; 1934 unsigned OpIdx; 1935 const CodeGenRegisterClass &RC; 1936 1937 public: 1938 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx, 1939 const CodeGenRegisterClass &RC) 1940 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {} 1941 1942 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override { 1943 Table << MatchTable::Opcode("GIR_ConstrainOperandRC") 1944 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 1945 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx) 1946 << MatchTable::Comment("RC " + RC.getName()) 1947 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak; 1948 } 1949 }; 1950 1951 InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) { 1952 Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName)); 1953 MutatableInsns.insert(Matchers.back().get()); 1954 return *Matchers.back(); 1955 } 1956 1957 void RuleMatcher::addRequiredFeature(Record *Feature) { 1958 RequiredFeatures.push_back(Feature); 1959 } 1960 1961 const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const { 1962 return RequiredFeatures; 1963 } 1964 1965 // Emplaces an action of the specified Kind at the end of the action list. 1966 // 1967 // Returns a reference to the newly created action. 1968 // 1969 // Like std::vector::emplace_back(), may invalidate all iterators if the new 1970 // size exceeds the capacity. Otherwise, only invalidates the past-the-end 1971 // iterator. 1972 template <class Kind, class... Args> 1973 Kind &RuleMatcher::addAction(Args &&... args) { 1974 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...)); 1975 return *static_cast<Kind *>(Actions.back().get()); 1976 } 1977 // Emplaces an action of the specified Kind before the given insertion point. 1978 // 1979 // Returns an iterator pointing at the newly created instruction. 1980 // 1981 // Like std::vector::insert(), may invalidate all iterators if the new size 1982 // exceeds the capacity. Otherwise, only invalidates the iterators from the 1983 // insertion point onwards. 1984 template <class Kind, class... Args> 1985 action_iterator RuleMatcher::insertAction(action_iterator InsertPt, 1986 Args &&... args) { 1987 return Actions.insert(InsertPt, llvm::make_unique<Kind>(std::forward<Args>(args)...)); 1988 } 1989 1990 unsigned 1991 RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) { 1992 unsigned NewInsnVarID = NextInsnVarID++; 1993 InsnVariableIDs[&Matcher] = NewInsnVarID; 1994 return NewInsnVarID; 1995 } 1996 1997 unsigned RuleMatcher::defineInsnVar(MatchTable &Table, 1998 const InstructionMatcher &Matcher, 1999 unsigned InsnID, unsigned OpIdx) { 2000 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher); 2001 Table << MatchTable::Opcode("GIM_RecordInsn") 2002 << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID) 2003 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID) 2004 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx) 2005 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]") 2006 << MatchTable::LineBreak; 2007 return NewInsnVarID; 2008 } 2009 2010 unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const { 2011 const auto &I = InsnVariableIDs.find(&InsnMatcher); 2012 if (I != InsnVariableIDs.end()) 2013 return I->second; 2014 llvm_unreachable("Matched Insn was not captured in a local variable"); 2015 } 2016 2017 void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) { 2018 if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) { 2019 DefinedOperands[SymbolicName] = &OM; 2020 return; 2021 } 2022 2023 // If the operand is already defined, then we must ensure both references in 2024 // the matcher have the exact same node. 2025 OM.addPredicate<SameOperandMatcher>(OM.getSymbolicName()); 2026 } 2027 2028 const InstructionMatcher & 2029 RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const { 2030 for (const auto &I : InsnVariableIDs) 2031 if (I.first->getSymbolicName() == SymbolicName) 2032 return *I.first; 2033 llvm_unreachable( 2034 ("Failed to lookup instruction " + SymbolicName).str().c_str()); 2035 } 2036 2037 const OperandMatcher & 2038 RuleMatcher::getOperandMatcher(StringRef Name) const { 2039 const auto &I = DefinedOperands.find(Name); 2040 2041 if (I == DefinedOperands.end()) 2042 PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher"); 2043 2044 return *I->second; 2045 } 2046 2047 /// Emit MatchTable opcodes to check the shape of the match and capture 2048 /// instructions into local variables. 2049 void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) { 2050 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet"); 2051 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front()); 2052 Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID); 2053 } 2054 2055 void RuleMatcher::emit(MatchTable &Table) { 2056 if (Matchers.empty()) 2057 llvm_unreachable("Unexpected empty matcher!"); 2058 2059 // The representation supports rules that require multiple roots such as: 2060 // %ptr(p0) = ... 2061 // %elt0(s32) = G_LOAD %ptr 2062 // %1(p0) = G_ADD %ptr, 4 2063 // %elt1(s32) = G_LOAD p0 %1 2064 // which could be usefully folded into: 2065 // %ptr(p0) = ... 2066 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr 2067 // on some targets but we don't need to make use of that yet. 2068 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet"); 2069 2070 unsigned LabelID = Table.allocateLabelID(); 2071 Table << MatchTable::Opcode("GIM_Try", +1) 2072 << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID) 2073 << MatchTable::LineBreak; 2074 2075 if (!RequiredFeatures.empty()) { 2076 Table << MatchTable::Opcode("GIM_CheckFeatures") 2077 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures)) 2078 << MatchTable::LineBreak; 2079 } 2080 2081 emitCaptureOpcodes(Table); 2082 2083 Matchers.front()->emitPredicateOpcodes(Table, *this, 2084 getInsnVarID(*Matchers.front())); 2085 2086 // We must also check if it's safe to fold the matched instructions. 2087 if (InsnVariableIDs.size() >= 2) { 2088 // Invert the map to create stable ordering (by var names) 2089 SmallVector<unsigned, 2> InsnIDs; 2090 for (const auto &Pair : InsnVariableIDs) { 2091 // Skip the root node since it isn't moving anywhere. Everything else is 2092 // sinking to meet it. 2093 if (Pair.first == Matchers.front().get()) 2094 continue; 2095 2096 InsnIDs.push_back(Pair.second); 2097 } 2098 std::sort(InsnIDs.begin(), InsnIDs.end()); 2099 2100 for (const auto &InsnID : InsnIDs) { 2101 // Reject the difficult cases until we have a more accurate check. 2102 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold") 2103 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID) 2104 << MatchTable::LineBreak; 2105 2106 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or 2107 // account for unsafe cases. 2108 // 2109 // Example: 2110 // MI1--> %0 = ... 2111 // %1 = ... %0 2112 // MI0--> %2 = ... %0 2113 // It's not safe to erase MI1. We currently handle this by not 2114 // erasing %0 (even when it's dead). 2115 // 2116 // Example: 2117 // MI1--> %0 = load volatile @a 2118 // %1 = load volatile @a 2119 // MI0--> %2 = ... %0 2120 // It's not safe to sink %0's def past %1. We currently handle 2121 // this by rejecting all loads. 2122 // 2123 // Example: 2124 // MI1--> %0 = load @a 2125 // %1 = store @a 2126 // MI0--> %2 = ... %0 2127 // It's not safe to sink %0's def past %1. We currently handle 2128 // this by rejecting all loads. 2129 // 2130 // Example: 2131 // G_CONDBR %cond, @BB1 2132 // BB0: 2133 // MI1--> %0 = load @a 2134 // G_BR @BB1 2135 // BB1: 2136 // MI0--> %2 = ... %0 2137 // It's not always safe to sink %0 across control flow. In this 2138 // case it may introduce a memory fault. We currentl handle this 2139 // by rejecting all loads. 2140 } 2141 } 2142 2143 for (const auto &MA : Actions) 2144 MA->emitActionOpcodes(Table, *this); 2145 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak 2146 << MatchTable::Label(LabelID); 2147 } 2148 2149 bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const { 2150 // Rules involving more match roots have higher priority. 2151 if (Matchers.size() > B.Matchers.size()) 2152 return true; 2153 if (Matchers.size() < B.Matchers.size()) 2154 return false; 2155 2156 for (const auto &Matcher : zip(Matchers, B.Matchers)) { 2157 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher))) 2158 return true; 2159 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher))) 2160 return false; 2161 } 2162 2163 return false; 2164 } 2165 2166 unsigned RuleMatcher::countRendererFns() const { 2167 return std::accumulate( 2168 Matchers.begin(), Matchers.end(), 0, 2169 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) { 2170 return A + Matcher->countRendererFns(); 2171 }); 2172 } 2173 2174 bool OperandPredicateMatcher::isHigherPriorityThan( 2175 const OperandPredicateMatcher &B) const { 2176 // Generally speaking, an instruction is more important than an Int or a 2177 // LiteralInt because it can cover more nodes but theres an exception to 2178 // this. G_CONSTANT's are less important than either of those two because they 2179 // are more permissive. 2180 2181 const InstructionOperandMatcher *AOM = 2182 dyn_cast<InstructionOperandMatcher>(this); 2183 const InstructionOperandMatcher *BOM = 2184 dyn_cast<InstructionOperandMatcher>(&B); 2185 bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction(); 2186 bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction(); 2187 2188 if (AOM && BOM) { 2189 // The relative priorities between a G_CONSTANT and any other instruction 2190 // don't actually matter but this code is needed to ensure a strict weak 2191 // ordering. This is particularly important on Windows where the rules will 2192 // be incorrectly sorted without it. 2193 if (AIsConstantInsn != BIsConstantInsn) 2194 return AIsConstantInsn < BIsConstantInsn; 2195 return false; 2196 } 2197 2198 if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt)) 2199 return false; 2200 if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt)) 2201 return true; 2202 2203 return Kind < B.Kind; 2204 } 2205 2206 void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table, 2207 RuleMatcher &Rule, 2208 unsigned InsnVarID, 2209 unsigned OpIdx) const { 2210 const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName); 2211 unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher()); 2212 2213 Table << MatchTable::Opcode("GIM_CheckIsSameOperand") 2214 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID) 2215 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx) 2216 << MatchTable::Comment("OtherMI") 2217 << MatchTable::IntValue(OtherInsnVarID) 2218 << MatchTable::Comment("OtherOpIdx") 2219 << MatchTable::IntValue(OtherOM.getOperandIndex()) 2220 << MatchTable::LineBreak; 2221 } 2222 2223 //===- GlobalISelEmitter class --------------------------------------------===// 2224 2225 class GlobalISelEmitter { 2226 public: 2227 explicit GlobalISelEmitter(RecordKeeper &RK); 2228 void run(raw_ostream &OS); 2229 2230 private: 2231 const RecordKeeper &RK; 2232 const CodeGenDAGPatterns CGP; 2233 const CodeGenTarget &Target; 2234 CodeGenRegBank CGRegs; 2235 2236 /// Keep track of the equivalence between SDNodes and Instruction by mapping 2237 /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to 2238 /// check for attributes on the relation such as CheckMMOIsNonAtomic. 2239 /// This is defined using 'GINodeEquiv' in the target description. 2240 DenseMap<Record *, Record *> NodeEquivs; 2241 2242 /// Keep track of the equivalence between ComplexPattern's and 2243 /// GIComplexOperandMatcher. Map entries are specified by subclassing 2244 /// GIComplexPatternEquiv. 2245 DenseMap<const Record *, const Record *> ComplexPatternEquivs; 2246 2247 // Map of predicates to their subtarget features. 2248 SubtargetFeatureInfoMap SubtargetFeatures; 2249 2250 void gatherNodeEquivs(); 2251 Record *findNodeEquiv(Record *N) const; 2252 2253 Error importRulePredicates(RuleMatcher &M, ArrayRef<Predicate> Predicates); 2254 Expected<InstructionMatcher &> createAndImportSelDAGMatcher( 2255 RuleMatcher &Rule, InstructionMatcher &InsnMatcher, 2256 const TreePatternNode *Src, unsigned &TempOpIdx) const; 2257 Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R, 2258 unsigned &TempOpIdx) const; 2259 Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher, 2260 const TreePatternNode *SrcChild, 2261 bool OperandIsAPointer, unsigned OpIdx, 2262 unsigned &TempOpIdx) const; 2263 2264 Expected<BuildMIAction &> 2265 createAndImportInstructionRenderer(RuleMatcher &M, 2266 const TreePatternNode *Dst); 2267 Expected<action_iterator> 2268 createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M, 2269 const TreePatternNode *Dst); 2270 void importExplicitDefRenderers(BuildMIAction &DstMIBuilder); 2271 Expected<action_iterator> 2272 importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M, 2273 BuildMIAction &DstMIBuilder, 2274 const llvm::TreePatternNode *Dst); 2275 Expected<action_iterator> 2276 importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule, 2277 BuildMIAction &DstMIBuilder, 2278 TreePatternNode *DstChild) const; 2279 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder, 2280 DagInit *DefaultOps) const; 2281 Error 2282 importImplicitDefRenderers(BuildMIAction &DstMIBuilder, 2283 const std::vector<Record *> &ImplicitDefs) const; 2284 2285 void emitImmPredicates(raw_ostream &OS, StringRef TypeIdentifier, 2286 StringRef Type, 2287 std::function<bool(const Record *R)> Filter); 2288 2289 /// Analyze pattern \p P, returning a matcher for it if possible. 2290 /// Otherwise, return an Error explaining why we don't support it. 2291 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P); 2292 2293 void declareSubtargetFeature(Record *Predicate); 2294 }; 2295 2296 void GlobalISelEmitter::gatherNodeEquivs() { 2297 assert(NodeEquivs.empty()); 2298 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv")) 2299 NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv; 2300 2301 assert(ComplexPatternEquivs.empty()); 2302 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) { 2303 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent"); 2304 if (!SelDAGEquiv) 2305 continue; 2306 ComplexPatternEquivs[SelDAGEquiv] = Equiv; 2307 } 2308 } 2309 2310 Record *GlobalISelEmitter::findNodeEquiv(Record *N) const { 2311 return NodeEquivs.lookup(N); 2312 } 2313 2314 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK) 2315 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()), 2316 CGRegs(RK, Target.getHwModes()) {} 2317 2318 //===- Emitter ------------------------------------------------------------===// 2319 2320 Error 2321 GlobalISelEmitter::importRulePredicates(RuleMatcher &M, 2322 ArrayRef<Predicate> Predicates) { 2323 for (const Predicate &P : Predicates) { 2324 if (!P.Def) 2325 continue; 2326 declareSubtargetFeature(P.Def); 2327 M.addRequiredFeature(P.Def); 2328 } 2329 2330 return Error::success(); 2331 } 2332 2333 Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher( 2334 RuleMatcher &Rule, InstructionMatcher &InsnMatcher, 2335 const TreePatternNode *Src, unsigned &TempOpIdx) const { 2336 Record *SrcGIEquivOrNull = nullptr; 2337 const CodeGenInstruction *SrcGIOrNull = nullptr; 2338 2339 // Start with the defined operands (i.e., the results of the root operator). 2340 if (Src->getExtTypes().size() > 1) 2341 return failedImport("Src pattern has multiple results"); 2342 2343 if (Src->isLeaf()) { 2344 Init *SrcInit = Src->getLeafValue(); 2345 if (isa<IntInit>(SrcInit)) { 2346 InsnMatcher.addPredicate<InstructionOpcodeMatcher>( 2347 &Target.getInstruction(RK.getDef("G_CONSTANT"))); 2348 } else 2349 return failedImport( 2350 "Unable to deduce gMIR opcode to handle Src (which is a leaf)"); 2351 } else { 2352 SrcGIEquivOrNull = findNodeEquiv(Src->getOperator()); 2353 if (!SrcGIEquivOrNull) 2354 return failedImport("Pattern operator lacks an equivalent Instruction" + 2355 explainOperator(Src->getOperator())); 2356 SrcGIOrNull = &Target.getInstruction(SrcGIEquivOrNull->getValueAsDef("I")); 2357 2358 // The operators look good: match the opcode 2359 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull); 2360 } 2361 2362 unsigned OpIdx = 0; 2363 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) { 2364 // Results don't have a name unless they are the root node. The caller will 2365 // set the name if appropriate. 2366 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx); 2367 if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */)) 2368 return failedImport(toString(std::move(Error)) + 2369 " for result of Src pattern operator"); 2370 } 2371 2372 for (const auto &Predicate : Src->getPredicateFns()) { 2373 if (Predicate.isAlwaysTrue()) 2374 continue; 2375 2376 if (Predicate.isImmediatePattern()) { 2377 InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate); 2378 continue; 2379 } 2380 2381 // No check required. A G_LOAD is an unindexed load. 2382 if (Predicate.isLoad() && Predicate.isUnindexed()) 2383 continue; 2384 2385 // No check required. G_LOAD by itself is a non-extending load. 2386 if (Predicate.isNonExtLoad()) 2387 continue; 2388 2389 if (Predicate.isLoad() && Predicate.getMemoryVT() != nullptr) { 2390 Optional<LLTCodeGen> MemTyOrNone = 2391 MVTToLLT(getValueType(Predicate.getMemoryVT())); 2392 2393 if (!MemTyOrNone) 2394 return failedImport("MemVT could not be converted to LLT"); 2395 2396 InsnMatcher.getOperand(0).addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue()); 2397 continue; 2398 } 2399 2400 // No check required. A G_STORE is an unindexed store. 2401 if (Predicate.isStore() && Predicate.isUnindexed()) 2402 continue; 2403 2404 // No check required. G_STORE by itself is a non-extending store. 2405 if (Predicate.isNonTruncStore()) 2406 continue; 2407 2408 if (Predicate.isStore() && Predicate.getMemoryVT() != nullptr) { 2409 Optional<LLTCodeGen> MemTyOrNone = 2410 MVTToLLT(getValueType(Predicate.getMemoryVT())); 2411 2412 if (!MemTyOrNone) 2413 return failedImport("MemVT could not be converted to LLT"); 2414 2415 InsnMatcher.getOperand(0).addPredicate<LLTOperandMatcher>(MemTyOrNone.getValue()); 2416 continue; 2417 } 2418 2419 return failedImport("Src pattern child has predicate (" + 2420 explainPredicates(Src) + ")"); 2421 } 2422 if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic")) 2423 InsnMatcher.addPredicate<NonAtomicMMOPredicateMatcher>(); 2424 2425 if (Src->isLeaf()) { 2426 Init *SrcInit = Src->getLeafValue(); 2427 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) { 2428 OperandMatcher &OM = 2429 InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx); 2430 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue()); 2431 } else 2432 return failedImport( 2433 "Unable to deduce gMIR opcode to handle Src (which is a leaf)"); 2434 } else { 2435 assert(SrcGIOrNull && 2436 "Expected to have already found an equivalent Instruction"); 2437 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" || 2438 SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") { 2439 // imm/fpimm still have operands but we don't need to do anything with it 2440 // here since we don't support ImmLeaf predicates yet. However, we still 2441 // need to note the hidden operand to get GIM_CheckNumOperands correct. 2442 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx); 2443 return InsnMatcher; 2444 } 2445 2446 // Match the used operands (i.e. the children of the operator). 2447 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) { 2448 TreePatternNode *SrcChild = Src->getChild(i); 2449 2450 // SelectionDAG allows pointers to be represented with iN since it doesn't 2451 // distinguish between pointers and integers but they are different types in GlobalISel. 2452 // Coerce integers to pointers to address space 0 if the context indicates a pointer. 2453 // TODO: Find a better way to do this, SDTCisPtrTy? 2454 bool OperandIsAPointer = 2455 (SrcGIOrNull->TheDef->getName() == "G_LOAD" && i == 0) || 2456 (SrcGIOrNull->TheDef->getName() == "G_STORE" && i == 1); 2457 2458 // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately 2459 // following the defs is an intrinsic ID. 2460 if ((SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" || 2461 SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS") && 2462 i == 0) { 2463 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) { 2464 OperandMatcher &OM = 2465 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx); 2466 OM.addPredicate<IntrinsicIDOperandMatcher>(II); 2467 continue; 2468 } 2469 2470 return failedImport("Expected IntInit containing instrinsic ID)"); 2471 } 2472 2473 if (auto Error = 2474 importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer, 2475 OpIdx++, TempOpIdx)) 2476 return std::move(Error); 2477 } 2478 } 2479 2480 return InsnMatcher; 2481 } 2482 2483 Error GlobalISelEmitter::importComplexPatternOperandMatcher( 2484 OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const { 2485 const auto &ComplexPattern = ComplexPatternEquivs.find(R); 2486 if (ComplexPattern == ComplexPatternEquivs.end()) 2487 return failedImport("SelectionDAG ComplexPattern (" + R->getName() + 2488 ") not mapped to GlobalISel"); 2489 2490 OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second); 2491 TempOpIdx++; 2492 return Error::success(); 2493 } 2494 2495 Error GlobalISelEmitter::importChildMatcher(RuleMatcher &Rule, 2496 InstructionMatcher &InsnMatcher, 2497 const TreePatternNode *SrcChild, 2498 bool OperandIsAPointer, 2499 unsigned OpIdx, 2500 unsigned &TempOpIdx) const { 2501 OperandMatcher &OM = 2502 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx); 2503 if (OM.isSameAsAnotherOperand()) 2504 return Error::success(); 2505 2506 ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes(); 2507 if (ChildTypes.size() != 1) 2508 return failedImport("Src pattern child has multiple results"); 2509 2510 // Check MBB's before the type check since they are not a known type. 2511 if (!SrcChild->isLeaf()) { 2512 if (SrcChild->getOperator()->isSubClassOf("SDNode")) { 2513 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator()); 2514 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { 2515 OM.addPredicate<MBBOperandMatcher>(); 2516 return Error::success(); 2517 } 2518 } 2519 } 2520 2521 if (auto Error = 2522 OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer)) 2523 return failedImport(toString(std::move(Error)) + " for Src operand (" + 2524 to_string(*SrcChild) + ")"); 2525 2526 // Check for nested instructions. 2527 if (!SrcChild->isLeaf()) { 2528 if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) { 2529 // When a ComplexPattern is used as an operator, it should do the same 2530 // thing as when used as a leaf. However, the children of the operator 2531 // name the sub-operands that make up the complex operand and we must 2532 // prepare to reference them in the renderer too. 2533 unsigned RendererID = TempOpIdx; 2534 if (auto Error = importComplexPatternOperandMatcher( 2535 OM, SrcChild->getOperator(), TempOpIdx)) 2536 return Error; 2537 2538 for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) { 2539 auto *SubOperand = SrcChild->getChild(i); 2540 if (!SubOperand->getName().empty()) 2541 Rule.defineComplexSubOperand(SubOperand->getName(), 2542 SrcChild->getOperator(), RendererID, i); 2543 } 2544 2545 return Error::success(); 2546 } 2547 2548 auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>( 2549 InsnMatcher.getRuleMatcher(), SrcChild->getName()); 2550 if (!MaybeInsnOperand.hasValue()) { 2551 // This isn't strictly true. If the user were to provide exactly the same 2552 // matchers as the original operand then we could allow it. However, it's 2553 // simpler to not permit the redundant specification. 2554 return failedImport("Nested instruction cannot be the same as another operand"); 2555 } 2556 2557 // Map the node to a gMIR instruction. 2558 InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand; 2559 auto InsnMatcherOrError = createAndImportSelDAGMatcher( 2560 Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx); 2561 if (auto Error = InsnMatcherOrError.takeError()) 2562 return Error; 2563 2564 return Error::success(); 2565 } 2566 2567 // Check for constant immediates. 2568 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) { 2569 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue()); 2570 return Error::success(); 2571 } 2572 2573 // Check for def's like register classes or ComplexPattern's. 2574 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) { 2575 auto *ChildRec = ChildDefInit->getDef(); 2576 2577 // Check for register classes. 2578 if (ChildRec->isSubClassOf("RegisterClass") || 2579 ChildRec->isSubClassOf("RegisterOperand")) { 2580 OM.addPredicate<RegisterBankOperandMatcher>( 2581 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit))); 2582 return Error::success(); 2583 } 2584 2585 // Check for ValueType. 2586 if (ChildRec->isSubClassOf("ValueType")) { 2587 // We already added a type check as standard practice so this doesn't need 2588 // to do anything. 2589 return Error::success(); 2590 } 2591 2592 // Check for ComplexPattern's. 2593 if (ChildRec->isSubClassOf("ComplexPattern")) 2594 return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx); 2595 2596 if (ChildRec->isSubClassOf("ImmLeaf")) { 2597 return failedImport( 2598 "Src pattern child def is an unsupported tablegen class (ImmLeaf)"); 2599 } 2600 2601 return failedImport( 2602 "Src pattern child def is an unsupported tablegen class"); 2603 } 2604 2605 return failedImport("Src pattern child is an unsupported kind"); 2606 } 2607 2608 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer( 2609 action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder, 2610 TreePatternNode *DstChild) const { 2611 if (DstChild->getTransformFn() != nullptr) { 2612 return failedImport("Dst pattern child has transform fn " + 2613 DstChild->getTransformFn()->getName()); 2614 } 2615 2616 const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName()); 2617 if (SubOperand.hasValue()) { 2618 DstMIBuilder.addRenderer<RenderComplexPatternOperand>( 2619 *std::get<0>(*SubOperand), DstChild->getName(), 2620 std::get<1>(*SubOperand), std::get<2>(*SubOperand)); 2621 return InsertPt; 2622 } 2623 2624 if (!DstChild->isLeaf()) { 2625 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't 2626 // inline, but in MI it's just another operand. 2627 if (DstChild->getOperator()->isSubClassOf("SDNode")) { 2628 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator()); 2629 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") { 2630 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName()); 2631 return InsertPt; 2632 } 2633 } 2634 2635 // Similarly, imm is an operator in TreePatternNode's view but must be 2636 // rendered as operands. 2637 // FIXME: The target should be able to choose sign-extended when appropriate 2638 // (e.g. on Mips). 2639 if (DstChild->getOperator()->getName() == "imm") { 2640 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName()); 2641 return InsertPt; 2642 } else if (DstChild->getOperator()->getName() == "fpimm") { 2643 DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>( 2644 DstChild->getName()); 2645 return InsertPt; 2646 } 2647 2648 return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild)); 2649 } 2650 2651 // Otherwise, we're looking for a bog-standard RegisterClass operand. 2652 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) { 2653 auto *ChildRec = ChildDefInit->getDef(); 2654 2655 ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes(); 2656 if (ChildTypes.size() != 1) 2657 return failedImport("Dst pattern child has multiple results"); 2658 2659 Optional<LLTCodeGen> OpTyOrNone = None; 2660 if (ChildTypes.front().isMachineValueType()) 2661 OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy); 2662 if (!OpTyOrNone) 2663 return failedImport("Dst operand has an unsupported type"); 2664 2665 if (ChildRec->isSubClassOf("Register")) { 2666 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec); 2667 return InsertPt; 2668 } 2669 2670 if (ChildRec->isSubClassOf("RegisterClass") || 2671 ChildRec->isSubClassOf("RegisterOperand") || 2672 ChildRec->isSubClassOf("ValueType")) { 2673 if (ChildRec->isSubClassOf("RegisterOperand") && 2674 !ChildRec->isValueUnset("GIZeroRegister")) { 2675 DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>( 2676 DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister")); 2677 return InsertPt; 2678 } 2679 2680 DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName()); 2681 return InsertPt; 2682 } 2683 2684 if (ChildRec->isSubClassOf("ComplexPattern")) { 2685 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec); 2686 if (ComplexPattern == ComplexPatternEquivs.end()) 2687 return failedImport( 2688 "SelectionDAG ComplexPattern not mapped to GlobalISel"); 2689 2690 const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName()); 2691 DstMIBuilder.addRenderer<RenderComplexPatternOperand>( 2692 *ComplexPattern->second, DstChild->getName(), 2693 OM.getAllocatedTemporariesBaseID()); 2694 return InsertPt; 2695 } 2696 2697 if (ChildRec->isSubClassOf("SDNodeXForm")) 2698 return failedImport("Dst pattern child def is an unsupported tablegen " 2699 "class (SDNodeXForm)"); 2700 2701 return failedImport( 2702 "Dst pattern child def is an unsupported tablegen class"); 2703 } 2704 2705 return failedImport("Dst pattern child is an unsupported kind"); 2706 } 2707 2708 Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer( 2709 RuleMatcher &M, const TreePatternNode *Dst) { 2710 auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst); 2711 if (auto Error = InsertPtOrError.takeError()) 2712 return std::move(Error); 2713 2714 action_iterator InsertPt = InsertPtOrError.get(); 2715 BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get()); 2716 2717 importExplicitDefRenderers(DstMIBuilder); 2718 2719 if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst) 2720 .takeError()) 2721 return std::move(Error); 2722 2723 return DstMIBuilder; 2724 } 2725 2726 Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer( 2727 action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) { 2728 Record *DstOp = Dst->getOperator(); 2729 if (!DstOp->isSubClassOf("Instruction")) { 2730 if (DstOp->isSubClassOf("ValueType")) 2731 return failedImport( 2732 "Pattern operator isn't an instruction (it's a ValueType)"); 2733 return failedImport("Pattern operator isn't an instruction"); 2734 } 2735 CodeGenInstruction *DstI = &Target.getInstruction(DstOp); 2736 2737 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction 2738 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy. 2739 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") 2740 DstI = &Target.getInstruction(RK.getDef("COPY")); 2741 else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") 2742 DstI = &Target.getInstruction(RK.getDef("COPY")); 2743 2744 return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(), 2745 DstI); 2746 } 2747 2748 void GlobalISelEmitter::importExplicitDefRenderers( 2749 BuildMIAction &DstMIBuilder) { 2750 const CodeGenInstruction *DstI = DstMIBuilder.getCGI(); 2751 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) { 2752 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I]; 2753 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name); 2754 } 2755 } 2756 2757 Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers( 2758 action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder, 2759 const llvm::TreePatternNode *Dst) { 2760 const CodeGenInstruction *DstI = DstMIBuilder.getCGI(); 2761 CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator()); 2762 2763 // EXTRACT_SUBREG needs to use a subregister COPY. 2764 if (OrigDstI->TheDef->getName() == "EXTRACT_SUBREG") { 2765 if (!Dst->getChild(0)->isLeaf()) 2766 return failedImport("EXTRACT_SUBREG child #1 is not a leaf"); 2767 2768 if (DefInit *SubRegInit = 2769 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) { 2770 CodeGenRegisterClass *RC = CGRegs.getRegClass( 2771 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue())); 2772 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef()); 2773 2774 const auto &SrcRCDstRCPair = 2775 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx); 2776 if (SrcRCDstRCPair.hasValue()) { 2777 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass"); 2778 if (SrcRCDstRCPair->first != RC) 2779 return failedImport("EXTRACT_SUBREG requires an additional COPY"); 2780 } 2781 2782 DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(), 2783 SubIdx); 2784 return InsertPt; 2785 } 2786 2787 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index"); 2788 } 2789 2790 // Render the explicit uses. 2791 unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs; 2792 unsigned ExpectedDstINumUses = Dst->getNumChildren(); 2793 if (OrigDstI->TheDef->getName() == "COPY_TO_REGCLASS") { 2794 DstINumUses--; // Ignore the class constraint. 2795 ExpectedDstINumUses--; 2796 } 2797 2798 unsigned Child = 0; 2799 unsigned NumDefaultOps = 0; 2800 for (unsigned I = 0; I != DstINumUses; ++I) { 2801 const CGIOperandList::OperandInfo &DstIOperand = 2802 DstI->Operands[DstI->Operands.NumDefs + I]; 2803 2804 // If the operand has default values, introduce them now. 2805 // FIXME: Until we have a decent test case that dictates we should do 2806 // otherwise, we're going to assume that operands with default values cannot 2807 // be specified in the patterns. Therefore, adding them will not cause us to 2808 // end up with too many rendered operands. 2809 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) { 2810 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps"); 2811 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps)) 2812 return std::move(Error); 2813 ++NumDefaultOps; 2814 continue; 2815 } 2816 2817 auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder, 2818 Dst->getChild(Child)); 2819 if (auto Error = InsertPtOrError.takeError()) 2820 return std::move(Error); 2821 InsertPt = InsertPtOrError.get(); 2822 ++Child; 2823 } 2824 2825 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses) 2826 return failedImport("Expected " + llvm::to_string(DstINumUses) + 2827 " used operands but found " + 2828 llvm::to_string(ExpectedDstINumUses) + 2829 " explicit ones and " + llvm::to_string(NumDefaultOps) + 2830 " default ones"); 2831 2832 return InsertPt; 2833 } 2834 2835 Error GlobalISelEmitter::importDefaultOperandRenderers( 2836 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const { 2837 for (const auto *DefaultOp : DefaultOps->getArgs()) { 2838 // Look through ValueType operators. 2839 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) { 2840 if (const DefInit *DefaultDagOperator = 2841 dyn_cast<DefInit>(DefaultDagOp->getOperator())) { 2842 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) 2843 DefaultOp = DefaultDagOp->getArg(0); 2844 } 2845 } 2846 2847 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) { 2848 DstMIBuilder.addRenderer<AddRegisterRenderer>(DefaultDefOp->getDef()); 2849 continue; 2850 } 2851 2852 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) { 2853 DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue()); 2854 continue; 2855 } 2856 2857 return failedImport("Could not add default op"); 2858 } 2859 2860 return Error::success(); 2861 } 2862 2863 Error GlobalISelEmitter::importImplicitDefRenderers( 2864 BuildMIAction &DstMIBuilder, 2865 const std::vector<Record *> &ImplicitDefs) const { 2866 if (!ImplicitDefs.empty()) 2867 return failedImport("Pattern defines a physical register"); 2868 return Error::success(); 2869 } 2870 2871 Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) { 2872 // Keep track of the matchers and actions to emit. 2873 RuleMatcher M(P.getSrcRecord()->getLoc()); 2874 M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) + 2875 " => " + 2876 llvm::to_string(*P.getDstPattern())); 2877 2878 if (auto Error = importRulePredicates(M, P.getPredicates())) 2879 return std::move(Error); 2880 2881 // Next, analyze the pattern operators. 2882 TreePatternNode *Src = P.getSrcPattern(); 2883 TreePatternNode *Dst = P.getDstPattern(); 2884 2885 // If the root of either pattern isn't a simple operator, ignore it. 2886 if (auto Err = isTrivialOperatorNode(Dst)) 2887 return failedImport("Dst pattern root isn't a trivial operator (" + 2888 toString(std::move(Err)) + ")"); 2889 if (auto Err = isTrivialOperatorNode(Src)) 2890 return failedImport("Src pattern root isn't a trivial operator (" + 2891 toString(std::move(Err)) + ")"); 2892 2893 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName()); 2894 unsigned TempOpIdx = 0; 2895 auto InsnMatcherOrError = 2896 createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx); 2897 if (auto Error = InsnMatcherOrError.takeError()) 2898 return std::move(Error); 2899 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get(); 2900 2901 if (Dst->isLeaf()) { 2902 Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue()); 2903 2904 const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef); 2905 if (RCDef) { 2906 // We need to replace the def and all its uses with the specified 2907 // operand. However, we must also insert COPY's wherever needed. 2908 // For now, emit a copy and let the register allocator clean up. 2909 auto &DstI = Target.getInstruction(RK.getDef("COPY")); 2910 const auto &DstIOperand = DstI.Operands[0]; 2911 2912 OperandMatcher &OM0 = InsnMatcher.getOperand(0); 2913 OM0.setSymbolicName(DstIOperand.Name); 2914 M.defineOperand(OM0.getSymbolicName(), OM0); 2915 OM0.addPredicate<RegisterBankOperandMatcher>(RC); 2916 2917 auto &DstMIBuilder = 2918 M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI); 2919 DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name); 2920 DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName()); 2921 M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC); 2922 2923 // We're done with this pattern! It's eligible for GISel emission; return 2924 // it. 2925 ++NumPatternImported; 2926 return std::move(M); 2927 } 2928 2929 return failedImport("Dst pattern root isn't a known leaf"); 2930 } 2931 2932 // Start with the defined operands (i.e., the results of the root operator). 2933 Record *DstOp = Dst->getOperator(); 2934 if (!DstOp->isSubClassOf("Instruction")) 2935 return failedImport("Pattern operator isn't an instruction"); 2936 2937 auto &DstI = Target.getInstruction(DstOp); 2938 if (DstI.Operands.NumDefs != Src->getExtTypes().size()) 2939 return failedImport("Src pattern results and dst MI defs are different (" + 2940 to_string(Src->getExtTypes().size()) + " def(s) vs " + 2941 to_string(DstI.Operands.NumDefs) + " def(s))"); 2942 2943 // The root of the match also has constraints on the register bank so that it 2944 // matches the result instruction. 2945 unsigned OpIdx = 0; 2946 for (const TypeSetByHwMode &VTy : Src->getExtTypes()) { 2947 (void)VTy; 2948 2949 const auto &DstIOperand = DstI.Operands[OpIdx]; 2950 Record *DstIOpRec = DstIOperand.Rec; 2951 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") { 2952 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue()); 2953 2954 if (DstIOpRec == nullptr) 2955 return failedImport( 2956 "COPY_TO_REGCLASS operand #1 isn't a register class"); 2957 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") { 2958 if (!Dst->getChild(0)->isLeaf()) 2959 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf"); 2960 2961 // We can assume that a subregister is in the same bank as it's super 2962 // register. 2963 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()); 2964 2965 if (DstIOpRec == nullptr) 2966 return failedImport( 2967 "EXTRACT_SUBREG operand #0 isn't a register class"); 2968 } else if (DstIOpRec->isSubClassOf("RegisterOperand")) 2969 DstIOpRec = DstIOpRec->getValueAsDef("RegClass"); 2970 else if (!DstIOpRec->isSubClassOf("RegisterClass")) 2971 return failedImport("Dst MI def isn't a register class" + 2972 to_string(*Dst)); 2973 2974 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx); 2975 OM.setSymbolicName(DstIOperand.Name); 2976 M.defineOperand(OM.getSymbolicName(), OM); 2977 OM.addPredicate<RegisterBankOperandMatcher>( 2978 Target.getRegisterClass(DstIOpRec)); 2979 ++OpIdx; 2980 } 2981 2982 auto DstMIBuilderOrError = createAndImportInstructionRenderer(M, Dst); 2983 if (auto Error = DstMIBuilderOrError.takeError()) 2984 return std::move(Error); 2985 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get(); 2986 2987 // Render the implicit defs. 2988 // These are only added to the root of the result. 2989 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs())) 2990 return std::move(Error); 2991 2992 DstMIBuilder.chooseInsnToMutate(M); 2993 2994 // Constrain the registers to classes. This is normally derived from the 2995 // emitted instruction but a few instructions require special handling. 2996 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") { 2997 // COPY_TO_REGCLASS does not provide operand constraints itself but the 2998 // result is constrained to the class given by the second child. 2999 Record *DstIOpRec = 3000 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue()); 3001 3002 if (DstIOpRec == nullptr) 3003 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class"); 3004 3005 M.addAction<ConstrainOperandToRegClassAction>( 3006 0, 0, Target.getRegisterClass(DstIOpRec)); 3007 3008 // We're done with this pattern! It's eligible for GISel emission; return 3009 // it. 3010 ++NumPatternImported; 3011 return std::move(M); 3012 } 3013 3014 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") { 3015 // EXTRACT_SUBREG selects into a subregister COPY but unlike most 3016 // instructions, the result register class is controlled by the 3017 // subregisters of the operand. As a result, we must constrain the result 3018 // class rather than check that it's already the right one. 3019 if (!Dst->getChild(0)->isLeaf()) 3020 return failedImport("EXTRACT_SUBREG child #1 is not a leaf"); 3021 3022 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue()); 3023 if (!SubRegInit) 3024 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index"); 3025 3026 // Constrain the result to the same register bank as the operand. 3027 Record *DstIOpRec = 3028 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()); 3029 3030 if (DstIOpRec == nullptr) 3031 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class"); 3032 3033 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef()); 3034 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec); 3035 3036 // It would be nice to leave this constraint implicit but we're required 3037 // to pick a register class so constrain the result to a register class 3038 // that can hold the correct MVT. 3039 // 3040 // FIXME: This may introduce an extra copy if the chosen class doesn't 3041 // actually contain the subregisters. 3042 assert(Src->getExtTypes().size() == 1 && 3043 "Expected Src of EXTRACT_SUBREG to have one result type"); 3044 3045 const auto &SrcRCDstRCPair = 3046 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx); 3047 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass"); 3048 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second); 3049 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first); 3050 3051 // We're done with this pattern! It's eligible for GISel emission; return 3052 // it. 3053 ++NumPatternImported; 3054 return std::move(M); 3055 } 3056 3057 M.addAction<ConstrainOperandsToDefinitionAction>(0); 3058 3059 // We're done with this pattern! It's eligible for GISel emission; return it. 3060 ++NumPatternImported; 3061 return std::move(M); 3062 } 3063 3064 // Emit imm predicate table and an enum to reference them with. 3065 // The 'Predicate_' part of the name is redundant but eliminating it is more 3066 // trouble than it's worth. 3067 void GlobalISelEmitter::emitImmPredicates( 3068 raw_ostream &OS, StringRef TypeIdentifier, StringRef Type, 3069 std::function<bool(const Record *R)> Filter) { 3070 std::vector<const Record *> MatchedRecords; 3071 const auto &Defs = RK.getAllDerivedDefinitions("PatFrag"); 3072 std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords), 3073 [&](Record *Record) { 3074 return !Record->getValueAsString("ImmediateCode").empty() && 3075 Filter(Record); 3076 }); 3077 3078 if (!MatchedRecords.empty()) { 3079 OS << "// PatFrag predicates.\n" 3080 << "enum {\n"; 3081 std::string EnumeratorSeparator = 3082 (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str(); 3083 for (const auto *Record : MatchedRecords) { 3084 OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName() 3085 << EnumeratorSeparator; 3086 EnumeratorSeparator = ",\n"; 3087 } 3088 OS << "};\n"; 3089 } 3090 3091 for (const auto *Record : MatchedRecords) 3092 OS << "static bool Predicate_" << Record->getName() << "(" << Type 3093 << " Imm) {" << Record->getValueAsString("ImmediateCode") << "}\n"; 3094 3095 OS << "static InstructionSelector::" << TypeIdentifier 3096 << "ImmediatePredicateFn " << TypeIdentifier << "ImmPredicateFns[] = {\n" 3097 << " nullptr,\n"; 3098 for (const auto *Record : MatchedRecords) 3099 OS << " Predicate_" << Record->getName() << ",\n"; 3100 OS << "};\n"; 3101 } 3102 3103 void GlobalISelEmitter::run(raw_ostream &OS) { 3104 // Track the GINodeEquiv definitions. 3105 gatherNodeEquivs(); 3106 3107 emitSourceFileHeader(("Global Instruction Selector for the " + 3108 Target.getName() + " target").str(), OS); 3109 std::vector<RuleMatcher> Rules; 3110 // Look through the SelectionDAG patterns we found, possibly emitting some. 3111 for (const PatternToMatch &Pat : CGP.ptms()) { 3112 ++NumPatternTotal; 3113 auto MatcherOrErr = runOnPattern(Pat); 3114 3115 // The pattern analysis can fail, indicating an unsupported pattern. 3116 // Report that if we've been asked to do so. 3117 if (auto Err = MatcherOrErr.takeError()) { 3118 if (WarnOnSkippedPatterns) { 3119 PrintWarning(Pat.getSrcRecord()->getLoc(), 3120 "Skipped pattern: " + toString(std::move(Err))); 3121 } else { 3122 consumeError(std::move(Err)); 3123 } 3124 ++NumPatternImportsSkipped; 3125 continue; 3126 } 3127 3128 Rules.push_back(std::move(MatcherOrErr.get())); 3129 } 3130 3131 std::stable_sort(Rules.begin(), Rules.end(), 3132 [&](const RuleMatcher &A, const RuleMatcher &B) { 3133 if (A.isHigherPriorityThan(B)) { 3134 assert(!B.isHigherPriorityThan(A) && "Cannot be more important " 3135 "and less important at " 3136 "the same time"); 3137 return true; 3138 } 3139 return false; 3140 }); 3141 3142 std::vector<Record *> ComplexPredicates = 3143 RK.getAllDerivedDefinitions("GIComplexOperandMatcher"); 3144 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(), 3145 [](const Record *A, const Record *B) { 3146 if (A->getName() < B->getName()) 3147 return true; 3148 return false; 3149 }); 3150 unsigned MaxTemporaries = 0; 3151 for (const auto &Rule : Rules) 3152 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns()); 3153 3154 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n" 3155 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size() 3156 << ";\n" 3157 << "using PredicateBitset = " 3158 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n" 3159 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n"; 3160 3161 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n" 3162 << " mutable MatcherState State;\n" 3163 << " typedef " 3164 "ComplexRendererFns(" 3165 << Target.getName() 3166 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n" 3167 << " const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> " 3168 "MatcherInfo;\n" 3169 << " static " << Target.getName() 3170 << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n" 3171 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n"; 3172 3173 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n" 3174 << ", State(" << MaxTemporaries << "),\n" 3175 << "MatcherInfo({TypeObjects, FeatureBitsets, I64ImmPredicateFns, " 3176 "APIntImmPredicateFns, APFloatImmPredicateFns, ComplexPredicateFns})\n" 3177 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n"; 3178 3179 OS << "#ifdef GET_GLOBALISEL_IMPL\n"; 3180 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures, 3181 OS); 3182 3183 // Separate subtarget features by how often they must be recomputed. 3184 SubtargetFeatureInfoMap ModuleFeatures; 3185 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(), 3186 std::inserter(ModuleFeatures, ModuleFeatures.end()), 3187 [](const SubtargetFeatureInfoMap::value_type &X) { 3188 return !X.second.mustRecomputePerFunction(); 3189 }); 3190 SubtargetFeatureInfoMap FunctionFeatures; 3191 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(), 3192 std::inserter(FunctionFeatures, FunctionFeatures.end()), 3193 [](const SubtargetFeatureInfoMap::value_type &X) { 3194 return X.second.mustRecomputePerFunction(); 3195 }); 3196 3197 SubtargetFeatureInfo::emitComputeAvailableFeatures( 3198 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures", 3199 ModuleFeatures, OS); 3200 SubtargetFeatureInfo::emitComputeAvailableFeatures( 3201 Target.getName(), "InstructionSelector", 3202 "computeAvailableFunctionFeatures", FunctionFeatures, OS, 3203 "const MachineFunction *MF"); 3204 3205 // Emit a table containing the LLT objects needed by the matcher and an enum 3206 // for the matcher to reference them with. 3207 std::vector<LLTCodeGen> TypeObjects; 3208 for (const auto &Ty : LLTOperandMatcher::KnownTypes) 3209 TypeObjects.push_back(Ty); 3210 std::sort(TypeObjects.begin(), TypeObjects.end()); 3211 OS << "// LLT Objects.\n" 3212 << "enum {\n"; 3213 for (const auto &TypeObject : TypeObjects) { 3214 OS << " "; 3215 TypeObject.emitCxxEnumValue(OS); 3216 OS << ",\n"; 3217 } 3218 OS << "};\n" 3219 << "const static LLT TypeObjects[] = {\n"; 3220 for (const auto &TypeObject : TypeObjects) { 3221 OS << " "; 3222 TypeObject.emitCxxConstructorCall(OS); 3223 OS << ",\n"; 3224 } 3225 OS << "};\n\n"; 3226 3227 // Emit a table containing the PredicateBitsets objects needed by the matcher 3228 // and an enum for the matcher to reference them with. 3229 std::vector<std::vector<Record *>> FeatureBitsets; 3230 for (auto &Rule : Rules) 3231 FeatureBitsets.push_back(Rule.getRequiredFeatures()); 3232 std::sort( 3233 FeatureBitsets.begin(), FeatureBitsets.end(), 3234 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) { 3235 if (A.size() < B.size()) 3236 return true; 3237 if (A.size() > B.size()) 3238 return false; 3239 for (const auto &Pair : zip(A, B)) { 3240 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName()) 3241 return true; 3242 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName()) 3243 return false; 3244 } 3245 return false; 3246 }); 3247 FeatureBitsets.erase( 3248 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()), 3249 FeatureBitsets.end()); 3250 OS << "// Feature bitsets.\n" 3251 << "enum {\n" 3252 << " GIFBS_Invalid,\n"; 3253 for (const auto &FeatureBitset : FeatureBitsets) { 3254 if (FeatureBitset.empty()) 3255 continue; 3256 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n"; 3257 } 3258 OS << "};\n" 3259 << "const static PredicateBitset FeatureBitsets[] {\n" 3260 << " {}, // GIFBS_Invalid\n"; 3261 for (const auto &FeatureBitset : FeatureBitsets) { 3262 if (FeatureBitset.empty()) 3263 continue; 3264 OS << " {"; 3265 for (const auto &Feature : FeatureBitset) { 3266 const auto &I = SubtargetFeatures.find(Feature); 3267 assert(I != SubtargetFeatures.end() && "Didn't import predicate?"); 3268 OS << I->second.getEnumBitName() << ", "; 3269 } 3270 OS << "},\n"; 3271 } 3272 OS << "};\n\n"; 3273 3274 // Emit complex predicate table and an enum to reference them with. 3275 OS << "// ComplexPattern predicates.\n" 3276 << "enum {\n" 3277 << " GICP_Invalid,\n"; 3278 for (const auto &Record : ComplexPredicates) 3279 OS << " GICP_" << Record->getName() << ",\n"; 3280 OS << "};\n" 3281 << "// See constructor for table contents\n\n"; 3282 3283 emitImmPredicates(OS, "I64", "int64_t", [](const Record *R) { 3284 bool Unset; 3285 return !R->getValueAsBitOrUnset("IsAPFloat", Unset) && 3286 !R->getValueAsBit("IsAPInt"); 3287 }); 3288 emitImmPredicates(OS, "APFloat", "const APFloat &", [](const Record *R) { 3289 bool Unset; 3290 return R->getValueAsBitOrUnset("IsAPFloat", Unset); 3291 }); 3292 emitImmPredicates(OS, "APInt", "const APInt &", [](const Record *R) { 3293 return R->getValueAsBit("IsAPInt"); 3294 }); 3295 OS << "\n"; 3296 3297 OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n" 3298 << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n" 3299 << " nullptr, // GICP_Invalid\n"; 3300 for (const auto &Record : ComplexPredicates) 3301 OS << " &" << Target.getName() 3302 << "InstructionSelector::" << Record->getValueAsString("MatcherFn") 3303 << ", // " << Record->getName() << "\n"; 3304 OS << "};\n\n"; 3305 3306 OS << "bool " << Target.getName() 3307 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n" 3308 << " MachineFunction &MF = *I.getParent()->getParent();\n" 3309 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n" 3310 << " // FIXME: This should be computed on a per-function basis rather " 3311 "than per-insn.\n" 3312 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, " 3313 "&MF);\n" 3314 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n" 3315 << " NewMIVector OutMIs;\n" 3316 << " State.MIs.clear();\n" 3317 << " State.MIs.push_back(&I);\n\n"; 3318 3319 MatchTable Table(0); 3320 for (auto &Rule : Rules) { 3321 Rule.emit(Table); 3322 ++NumPatternEmitted; 3323 } 3324 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak; 3325 Table.emitDeclaration(OS); 3326 OS << " if (executeMatchTable(*this, OutMIs, State, MatcherInfo, "; 3327 Table.emitUse(OS); 3328 OS << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n" 3329 << " return true;\n" 3330 << " }\n\n"; 3331 3332 OS << " return false;\n" 3333 << "}\n" 3334 << "#endif // ifdef GET_GLOBALISEL_IMPL\n"; 3335 3336 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n" 3337 << "PredicateBitset AvailableModuleFeatures;\n" 3338 << "mutable PredicateBitset AvailableFunctionFeatures;\n" 3339 << "PredicateBitset getAvailableFeatures() const {\n" 3340 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n" 3341 << "}\n" 3342 << "PredicateBitset\n" 3343 << "computeAvailableModuleFeatures(const " << Target.getName() 3344 << "Subtarget *Subtarget) const;\n" 3345 << "PredicateBitset\n" 3346 << "computeAvailableFunctionFeatures(const " << Target.getName() 3347 << "Subtarget *Subtarget,\n" 3348 << " const MachineFunction *MF) const;\n" 3349 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n"; 3350 3351 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n" 3352 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n" 3353 << "AvailableFunctionFeatures()\n" 3354 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n"; 3355 } 3356 3357 void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) { 3358 if (SubtargetFeatures.count(Predicate) == 0) 3359 SubtargetFeatures.emplace( 3360 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size())); 3361 } 3362 3363 } // end anonymous namespace 3364 3365 //===----------------------------------------------------------------------===// 3366 3367 namespace llvm { 3368 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) { 3369 GlobalISelEmitter(RK).run(OS); 3370 } 3371 } // End llvm namespace 3372