1 //===- CodeGenDAGPatterns.h - Read DAG patterns from .td file ---*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file declares the CodeGenDAGPatterns class, which is used to read and 10 // represent the patterns present in a .td file for instructions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_UTILS_TABLEGEN_COMMON_CODEGENDAGPATTERNS_H 15 #define LLVM_UTILS_TABLEGEN_COMMON_CODEGENDAGPATTERNS_H 16 17 #include "Basic/CodeGenIntrinsics.h" 18 #include "Basic/SDNodeProperties.h" 19 #include "CodeGenTarget.h" 20 #include "llvm/ADT/IntrusiveRefCntPtr.h" 21 #include "llvm/ADT/MapVector.h" 22 #include "llvm/ADT/PointerUnion.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/StringMap.h" 25 #include "llvm/ADT/StringSet.h" 26 #include "llvm/ADT/Twine.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/MathExtras.h" 29 #include "llvm/TableGen/Record.h" 30 #include <algorithm> 31 #include <array> 32 #include <functional> 33 #include <map> 34 #include <numeric> 35 #include <vector> 36 37 namespace llvm { 38 39 class Init; 40 class ListInit; 41 class DagInit; 42 class SDNodeInfo; 43 class TreePattern; 44 class TreePatternNode; 45 class CodeGenDAGPatterns; 46 47 /// Shared pointer for TreePatternNode. 48 using TreePatternNodePtr = IntrusiveRefCntPtr<TreePatternNode>; 49 50 /// This represents a set of MVTs. Since the underlying type for the MVT 51 /// is uint16_t, there are at most 65536 values. To reduce the number of memory 52 /// allocations and deallocations, represent the set as a sequence of bits. 53 /// To reduce the allocations even further, make MachineValueTypeSet own 54 /// the storage and use std::array as the bit container. 55 struct MachineValueTypeSet { 56 static unsigned constexpr Capacity = 512; 57 using WordType = uint64_t; 58 static unsigned constexpr WordWidth = CHAR_BIT * sizeof(WordType); 59 static unsigned constexpr NumWords = Capacity / WordWidth; 60 static_assert(NumWords * WordWidth == Capacity, 61 "Capacity should be a multiple of WordWidth"); 62 63 LLVM_ATTRIBUTE_ALWAYS_INLINE 64 MachineValueTypeSet() { clear(); } 65 66 LLVM_ATTRIBUTE_ALWAYS_INLINE 67 unsigned size() const { 68 unsigned Count = 0; 69 for (WordType W : Words) 70 Count += llvm::popcount(W); 71 return Count; 72 } 73 LLVM_ATTRIBUTE_ALWAYS_INLINE 74 void clear() { std::memset(Words.data(), 0, NumWords * sizeof(WordType)); } 75 LLVM_ATTRIBUTE_ALWAYS_INLINE 76 bool empty() const { 77 for (WordType W : Words) 78 if (W != 0) 79 return false; 80 return true; 81 } 82 LLVM_ATTRIBUTE_ALWAYS_INLINE 83 unsigned count(MVT T) const { 84 assert(T.SimpleTy < Capacity && "Capacity needs to be enlarged"); 85 return (Words[T.SimpleTy / WordWidth] >> (T.SimpleTy % WordWidth)) & 1; 86 } 87 std::pair<MachineValueTypeSet &, bool> insert(MVT T) { 88 assert(T.SimpleTy < Capacity && "Capacity needs to be enlarged"); 89 bool V = count(T.SimpleTy); 90 Words[T.SimpleTy / WordWidth] |= WordType(1) << (T.SimpleTy % WordWidth); 91 return {*this, V}; 92 } 93 MachineValueTypeSet &insert(const MachineValueTypeSet &S) { 94 for (unsigned i = 0; i != NumWords; ++i) 95 Words[i] |= S.Words[i]; 96 return *this; 97 } 98 LLVM_ATTRIBUTE_ALWAYS_INLINE 99 void erase(MVT T) { 100 assert(T.SimpleTy < Capacity && "Capacity needs to be enlarged"); 101 Words[T.SimpleTy / WordWidth] &= ~(WordType(1) << (T.SimpleTy % WordWidth)); 102 } 103 104 void writeToStream(raw_ostream &OS) const; 105 106 struct const_iterator { 107 // Some implementations of the C++ library require these traits to be 108 // defined. 109 using iterator_category = std::forward_iterator_tag; 110 using value_type = MVT; 111 using difference_type = ptrdiff_t; 112 using pointer = const MVT *; 113 using reference = const MVT &; 114 115 LLVM_ATTRIBUTE_ALWAYS_INLINE 116 MVT operator*() const { 117 assert(Pos != Capacity); 118 return MVT::SimpleValueType(Pos); 119 } 120 LLVM_ATTRIBUTE_ALWAYS_INLINE 121 const_iterator(const MachineValueTypeSet *S, bool End) : Set(S) { 122 Pos = End ? Capacity : find_from_pos(0); 123 } 124 LLVM_ATTRIBUTE_ALWAYS_INLINE 125 const_iterator &operator++() { 126 assert(Pos != Capacity); 127 Pos = find_from_pos(Pos + 1); 128 return *this; 129 } 130 131 LLVM_ATTRIBUTE_ALWAYS_INLINE 132 bool operator==(const const_iterator &It) const { 133 return Set == It.Set && Pos == It.Pos; 134 } 135 LLVM_ATTRIBUTE_ALWAYS_INLINE 136 bool operator!=(const const_iterator &It) const { return !operator==(It); } 137 138 private: 139 unsigned find_from_pos(unsigned P) const { 140 unsigned SkipWords = P / WordWidth; 141 unsigned SkipBits = P % WordWidth; 142 unsigned Count = SkipWords * WordWidth; 143 144 // If P is in the middle of a word, process it manually here, because 145 // the trailing bits need to be masked off to use findFirstSet. 146 if (SkipBits != 0) { 147 WordType W = Set->Words[SkipWords]; 148 W &= maskLeadingOnes<WordType>(WordWidth - SkipBits); 149 if (W != 0) 150 return Count + llvm::countr_zero(W); 151 Count += WordWidth; 152 SkipWords++; 153 } 154 155 for (unsigned i = SkipWords; i != NumWords; ++i) { 156 WordType W = Set->Words[i]; 157 if (W != 0) 158 return Count + llvm::countr_zero(W); 159 Count += WordWidth; 160 } 161 return Capacity; 162 } 163 164 const MachineValueTypeSet *Set; 165 unsigned Pos; 166 }; 167 168 LLVM_ATTRIBUTE_ALWAYS_INLINE 169 const_iterator begin() const { return const_iterator(this, false); } 170 LLVM_ATTRIBUTE_ALWAYS_INLINE 171 const_iterator end() const { return const_iterator(this, true); } 172 173 LLVM_ATTRIBUTE_ALWAYS_INLINE 174 bool operator==(const MachineValueTypeSet &S) const { 175 return Words == S.Words; 176 } 177 LLVM_ATTRIBUTE_ALWAYS_INLINE 178 bool operator!=(const MachineValueTypeSet &S) const { return !operator==(S); } 179 180 private: 181 friend struct const_iterator; 182 std::array<WordType, NumWords> Words; 183 }; 184 185 raw_ostream &operator<<(raw_ostream &OS, const MachineValueTypeSet &T); 186 187 struct TypeSetByHwMode : public InfoByHwMode<MachineValueTypeSet> { 188 using SetType = MachineValueTypeSet; 189 unsigned AddrSpace = std::numeric_limits<unsigned>::max(); 190 191 TypeSetByHwMode() = default; 192 TypeSetByHwMode(const TypeSetByHwMode &VTS) = default; 193 TypeSetByHwMode &operator=(const TypeSetByHwMode &) = default; 194 TypeSetByHwMode(MVT::SimpleValueType VT) 195 : TypeSetByHwMode(ValueTypeByHwMode(VT)) {} 196 TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList); 197 198 SetType &getOrCreate(unsigned Mode) { return Map[Mode]; } 199 200 bool isValueTypeByHwMode(bool AllowEmpty) const; 201 ValueTypeByHwMode getValueTypeByHwMode() const; 202 203 LLVM_ATTRIBUTE_ALWAYS_INLINE 204 bool isMachineValueType() const { 205 return isSimple() && getSimple().size() == 1; 206 } 207 208 LLVM_ATTRIBUTE_ALWAYS_INLINE 209 MVT getMachineValueType() const { 210 assert(isMachineValueType()); 211 return *getSimple().begin(); 212 } 213 214 bool isPossible() const; 215 216 bool isPointer() const { return getValueTypeByHwMode().isPointer(); } 217 218 unsigned getPtrAddrSpace() const { 219 assert(isPointer()); 220 return getValueTypeByHwMode().PtrAddrSpace; 221 } 222 223 bool insert(const ValueTypeByHwMode &VVT); 224 bool constrain(const TypeSetByHwMode &VTS); 225 template <typename Predicate> bool constrain(Predicate P); 226 template <typename Predicate> 227 bool assign_if(const TypeSetByHwMode &VTS, Predicate P); 228 229 void writeToStream(raw_ostream &OS) const; 230 231 bool operator==(const TypeSetByHwMode &VTS) const; 232 bool operator!=(const TypeSetByHwMode &VTS) const { return !(*this == VTS); } 233 234 void dump() const; 235 bool validate() const; 236 237 private: 238 unsigned PtrAddrSpace = std::numeric_limits<unsigned>::max(); 239 /// Intersect two sets. Return true if anything has changed. 240 bool intersect(SetType &Out, const SetType &In); 241 }; 242 243 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T); 244 245 struct TypeInfer { 246 TypeInfer(TreePattern &T) : TP(T) {} 247 248 bool isConcrete(const TypeSetByHwMode &VTS, bool AllowEmpty) const { 249 return VTS.isValueTypeByHwMode(AllowEmpty); 250 } 251 ValueTypeByHwMode getConcrete(const TypeSetByHwMode &VTS, 252 bool AllowEmpty) const { 253 assert(VTS.isValueTypeByHwMode(AllowEmpty)); 254 return VTS.getValueTypeByHwMode(); 255 } 256 257 /// The protocol in the following functions (Merge*, force*, Enforce*, 258 /// expand*) is to return "true" if a change has been made, "false" 259 /// otherwise. 260 261 bool MergeInTypeInfo(TypeSetByHwMode &Out, const TypeSetByHwMode &In) const; 262 bool MergeInTypeInfo(TypeSetByHwMode &Out, MVT::SimpleValueType InVT) const { 263 return MergeInTypeInfo(Out, TypeSetByHwMode(InVT)); 264 } 265 bool MergeInTypeInfo(TypeSetByHwMode &Out, 266 const ValueTypeByHwMode &InVT) const { 267 return MergeInTypeInfo(Out, TypeSetByHwMode(InVT)); 268 } 269 270 /// Reduce the set \p Out to have at most one element for each mode. 271 bool forceArbitrary(TypeSetByHwMode &Out); 272 273 /// The following four functions ensure that upon return the set \p Out 274 /// will only contain types of the specified kind: integer, floating-point, 275 /// scalar, or vector. 276 /// If \p Out is empty, all legal types of the specified kind will be added 277 /// to it. Otherwise, all types that are not of the specified kind will be 278 /// removed from \p Out. 279 bool EnforceInteger(TypeSetByHwMode &Out); 280 bool EnforceFloatingPoint(TypeSetByHwMode &Out); 281 bool EnforceScalar(TypeSetByHwMode &Out); 282 bool EnforceVector(TypeSetByHwMode &Out); 283 284 /// If \p Out is empty, fill it with all legal types. Otherwise, leave it 285 /// unchanged. 286 bool EnforceAny(TypeSetByHwMode &Out); 287 /// Make sure that for each type in \p Small, there exists a larger type 288 /// in \p Big. \p SmallIsVT indicates that this is being called for 289 /// SDTCisVTSmallerThanOp. In that case the TypeSetByHwMode is re-created for 290 /// each call and needs special consideration in how we detect changes. 291 bool EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big, 292 bool SmallIsVT = false); 293 /// 1. Ensure that for each type T in \p Vec, T is a vector type, and that 294 /// for each type U in \p Elem, U is a scalar type. 295 /// 2. Ensure that for each (scalar) type U in \p Elem, there exists a 296 /// (vector) type T in \p Vec, such that U is the element type of T. 297 bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, TypeSetByHwMode &Elem); 298 bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, 299 const ValueTypeByHwMode &VVT); 300 /// Ensure that for each type T in \p Sub, T is a vector type, and there 301 /// exists a type U in \p Vec such that U is a vector type with the same 302 /// element type as T and at least as many elements as T. 303 bool EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec, TypeSetByHwMode &Sub); 304 /// 1. Ensure that \p V has a scalar type iff \p W has a scalar type. 305 /// 2. Ensure that for each vector type T in \p V, there exists a vector 306 /// type U in \p W, such that T and U have the same number of elements. 307 /// 3. Ensure that for each vector type U in \p W, there exists a vector 308 /// type T in \p V, such that T and U have the same number of elements 309 /// (reverse of 2). 310 bool EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W); 311 /// 1. Ensure that for each type T in \p A, there exists a type U in \p B, 312 /// such that T and U have equal size in bits. 313 /// 2. Ensure that for each type U in \p B, there exists a type T in \p A 314 /// such that T and U have equal size in bits (reverse of 1). 315 bool EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B); 316 317 /// For each overloaded type (i.e. of form *Any), replace it with the 318 /// corresponding subset of legal, specific types. 319 void expandOverloads(TypeSetByHwMode &VTS) const; 320 void expandOverloads(TypeSetByHwMode::SetType &Out, 321 const TypeSetByHwMode::SetType &Legal) const; 322 323 struct ValidateOnExit { 324 ValidateOnExit(const TypeSetByHwMode &T, const TypeInfer &TI) 325 : Infer(TI), VTS(T) {} 326 ~ValidateOnExit(); 327 const TypeInfer &Infer; 328 const TypeSetByHwMode &VTS; 329 }; 330 331 struct SuppressValidation { 332 SuppressValidation(TypeInfer &TI) : Infer(TI), SavedValidate(TI.Validate) { 333 Infer.Validate = false; 334 } 335 ~SuppressValidation() { Infer.Validate = SavedValidate; } 336 TypeInfer &Infer; 337 bool SavedValidate; 338 }; 339 340 TreePattern &TP; 341 bool Validate = true; // Indicate whether to validate types. 342 343 private: 344 const TypeSetByHwMode &getLegalTypes() const; 345 346 /// Cached legal types (in default mode). 347 mutable bool LegalTypesCached = false; 348 mutable TypeSetByHwMode LegalCache; 349 }; 350 351 /// Set type used to track multiply used variables in patterns 352 typedef StringSet<> MultipleUseVarSet; 353 354 /// SDTypeConstraint - This is a discriminated union of constraints, 355 /// corresponding to the SDTypeConstraint tablegen class in Target.td. 356 struct SDTypeConstraint { 357 SDTypeConstraint() = default; 358 SDTypeConstraint(const Record *R, const CodeGenHwModes &CGH); 359 360 unsigned OperandNo; // The operand # this constraint applies to. 361 enum KindTy { 362 SDTCisVT, 363 SDTCisPtrTy, 364 SDTCisInt, 365 SDTCisFP, 366 SDTCisVec, 367 SDTCisSameAs, 368 SDTCisVTSmallerThanOp, 369 SDTCisOpSmallerThanOp, 370 SDTCisEltOfVec, 371 SDTCisSubVecOfVec, 372 SDTCVecEltisVT, 373 SDTCisSameNumEltsAs, 374 SDTCisSameSizeAs 375 } ConstraintType; 376 377 unsigned OtherOperandNo; 378 379 // The VT for SDTCisVT and SDTCVecEltisVT. 380 // Must not be in the union because it has a non-trivial destructor. 381 ValueTypeByHwMode VVT; 382 383 /// ApplyTypeConstraint - Given a node in a pattern, apply this type 384 /// constraint to the nodes operands. This returns true if it makes a 385 /// change, false otherwise. If a type contradiction is found, an error 386 /// is flagged. 387 bool ApplyTypeConstraint(TreePatternNode &N, const SDNodeInfo &NodeInfo, 388 TreePattern &TP) const; 389 390 friend bool operator==(const SDTypeConstraint &LHS, 391 const SDTypeConstraint &RHS); 392 friend bool operator<(const SDTypeConstraint &LHS, 393 const SDTypeConstraint &RHS); 394 }; 395 396 /// ScopedName - A name of a node associated with a "scope" that indicates 397 /// the context (e.g. instance of Pattern or PatFrag) in which the name was 398 /// used. This enables substitution of pattern fragments while keeping track 399 /// of what name(s) were originally given to various nodes in the tree. 400 class ScopedName { 401 unsigned Scope; 402 std::string Identifier; 403 404 public: 405 ScopedName(unsigned Scope, StringRef Identifier) 406 : Scope(Scope), Identifier(std::string(Identifier)) { 407 assert(Scope != 0 && 408 "Scope == 0 is used to indicate predicates without arguments"); 409 } 410 411 unsigned getScope() const { return Scope; } 412 const std::string &getIdentifier() const { return Identifier; } 413 414 bool operator==(const ScopedName &o) const; 415 bool operator!=(const ScopedName &o) const; 416 }; 417 418 /// SDNodeInfo - One of these records is created for each SDNode instance in 419 /// the target .td file. This represents the various dag nodes we will be 420 /// processing. 421 class SDNodeInfo { 422 const Record *Def; 423 StringRef EnumName; 424 StringRef SDClassName; 425 unsigned NumResults; 426 int NumOperands; 427 unsigned Properties; 428 bool IsStrictFP; 429 uint32_t TSFlags; 430 std::vector<SDTypeConstraint> TypeConstraints; 431 432 public: 433 // Parse the specified record. 434 SDNodeInfo(const Record *R, const CodeGenHwModes &CGH); 435 436 unsigned getNumResults() const { return NumResults; } 437 438 /// getNumOperands - This is the number of operands required or -1 if 439 /// variadic. 440 int getNumOperands() const { return NumOperands; } 441 const Record *getRecord() const { return Def; } 442 StringRef getEnumName() const { return EnumName; } 443 StringRef getSDClassName() const { return SDClassName; } 444 445 const std::vector<SDTypeConstraint> &getTypeConstraints() const { 446 return TypeConstraints; 447 } 448 449 /// getKnownType - If the type constraints on this node imply a fixed type 450 /// (e.g. all stores return void, etc), then return it as an 451 /// MVT::SimpleValueType. Otherwise, return MVT::Other. 452 MVT::SimpleValueType getKnownType(unsigned ResNo) const; 453 454 unsigned getProperties() const { return Properties; } 455 456 /// hasProperty - Return true if this node has the specified property. 457 /// 458 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); } 459 460 bool isStrictFP() const { return IsStrictFP; } 461 462 uint32_t getTSFlags() const { return TSFlags; } 463 464 /// ApplyTypeConstraints - Given a node in a pattern, apply the type 465 /// constraints for this node to the operands of the node. This returns 466 /// true if it makes a change, false otherwise. If a type contradiction is 467 /// found, an error is flagged. 468 bool ApplyTypeConstraints(TreePatternNode &N, TreePattern &TP) const; 469 }; 470 471 /// TreePredicateFn - This is an abstraction that represents the predicates on 472 /// a PatFrag node. This is a simple one-word wrapper around a pointer to 473 /// provide nice accessors. 474 class TreePredicateFn { 475 /// PatFragRec - This is the TreePattern for the PatFrag that we 476 /// originally came from. 477 TreePattern *PatFragRec; 478 479 public: 480 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag. 481 TreePredicateFn(TreePattern *N); 482 483 TreePattern *getOrigPatFragRecord() const { return PatFragRec; } 484 485 /// isAlwaysTrue - Return true if this is a noop predicate. 486 bool isAlwaysTrue() const; 487 488 bool isImmediatePattern() const { return hasImmCode(); } 489 490 /// getImmediatePredicateCode - Return the code that evaluates this pattern if 491 /// this is an immediate predicate. It is an error to call this on a 492 /// non-immediate pattern. 493 std::string getImmediatePredicateCode() const { 494 std::string Result = getImmCode(); 495 assert(!Result.empty() && "Isn't an immediate pattern!"); 496 return Result; 497 } 498 499 bool operator==(const TreePredicateFn &RHS) const { 500 return PatFragRec == RHS.PatFragRec; 501 } 502 503 bool operator!=(const TreePredicateFn &RHS) const { return !(*this == RHS); } 504 505 /// Return the name to use in the generated code to reference this, this is 506 /// "Predicate_foo" if from a pattern fragment "foo". 507 std::string getFnName() const; 508 509 /// getCodeToRunOnSDNode - Return the code for the function body that 510 /// evaluates this predicate. The argument is expected to be in "Node", 511 /// not N. This handles casting and conversion to a concrete node type as 512 /// appropriate. 513 std::string getCodeToRunOnSDNode() const; 514 515 /// Get the data type of the argument to getImmediatePredicateCode(). 516 StringRef getImmType() const; 517 518 /// Get a string that describes the type returned by getImmType() but is 519 /// usable as part of an identifier. 520 StringRef getImmTypeIdentifier() const; 521 522 // Predicate code uses the PatFrag's captured operands. 523 bool usesOperands() const; 524 525 // Check if the HasNoUse predicate is set. 526 bool hasNoUse() const; 527 // Check if the HasOneUse predicate is set. 528 bool hasOneUse() const; 529 530 // Is the desired predefined predicate for a load? 531 bool isLoad() const; 532 // Is the desired predefined predicate for a store? 533 bool isStore() const; 534 // Is the desired predefined predicate for an atomic? 535 bool isAtomic() const; 536 537 /// Is this predicate the predefined unindexed load predicate? 538 /// Is this predicate the predefined unindexed store predicate? 539 bool isUnindexed() const; 540 /// Is this predicate the predefined non-extending load predicate? 541 bool isNonExtLoad() const; 542 /// Is this predicate the predefined any-extend load predicate? 543 bool isAnyExtLoad() const; 544 /// Is this predicate the predefined sign-extend load predicate? 545 bool isSignExtLoad() const; 546 /// Is this predicate the predefined zero-extend load predicate? 547 bool isZeroExtLoad() const; 548 /// Is this predicate the predefined non-truncating store predicate? 549 bool isNonTruncStore() const; 550 /// Is this predicate the predefined truncating store predicate? 551 bool isTruncStore() const; 552 553 /// Is this predicate the predefined monotonic atomic predicate? 554 bool isAtomicOrderingMonotonic() const; 555 /// Is this predicate the predefined acquire atomic predicate? 556 bool isAtomicOrderingAcquire() const; 557 /// Is this predicate the predefined release atomic predicate? 558 bool isAtomicOrderingRelease() const; 559 /// Is this predicate the predefined acquire-release atomic predicate? 560 bool isAtomicOrderingAcquireRelease() const; 561 /// Is this predicate the predefined sequentially consistent atomic predicate? 562 bool isAtomicOrderingSequentiallyConsistent() const; 563 564 /// Is this predicate the predefined acquire-or-stronger atomic predicate? 565 bool isAtomicOrderingAcquireOrStronger() const; 566 /// Is this predicate the predefined weaker-than-acquire atomic predicate? 567 bool isAtomicOrderingWeakerThanAcquire() const; 568 569 /// Is this predicate the predefined release-or-stronger atomic predicate? 570 bool isAtomicOrderingReleaseOrStronger() const; 571 /// Is this predicate the predefined weaker-than-release atomic predicate? 572 bool isAtomicOrderingWeakerThanRelease() const; 573 574 /// If non-null, indicates that this predicate is a predefined memory VT 575 /// predicate for a load/store and returns the ValueType record for the memory 576 /// VT. 577 const Record *getMemoryVT() const; 578 /// If non-null, indicates that this predicate is a predefined memory VT 579 /// predicate (checking only the scalar type) for load/store and returns the 580 /// ValueType record for the memory VT. 581 const Record *getScalarMemoryVT() const; 582 583 const ListInit *getAddressSpaces() const; 584 int64_t getMinAlignment() const; 585 586 // If true, indicates that GlobalISel-based C++ code was supplied. 587 bool hasGISelPredicateCode() const; 588 std::string getGISelPredicateCode() const; 589 590 private: 591 bool hasPredCode() const; 592 bool hasImmCode() const; 593 std::string getPredCode() const; 594 std::string getImmCode() const; 595 bool immCodeUsesAPInt() const; 596 bool immCodeUsesAPFloat() const; 597 598 bool isPredefinedPredicateEqualTo(StringRef Field, bool Value) const; 599 }; 600 601 struct TreePredicateCall { 602 TreePredicateFn Fn; 603 604 // Scope -- unique identifier for retrieving named arguments. 0 is used when 605 // the predicate does not use named arguments. 606 unsigned Scope; 607 608 TreePredicateCall(const TreePredicateFn &Fn, unsigned Scope) 609 : Fn(Fn), Scope(Scope) {} 610 611 bool operator==(const TreePredicateCall &o) const { 612 return Fn == o.Fn && Scope == o.Scope; 613 } 614 bool operator!=(const TreePredicateCall &o) const { return !(*this == o); } 615 }; 616 617 class TreePatternNode : public RefCountedBase<TreePatternNode> { 618 /// The type of each node result. Before and during type inference, each 619 /// result may be a set of possible types. After (successful) type inference, 620 /// each is a single concrete type. 621 std::vector<TypeSetByHwMode> Types; 622 623 /// The index of each result in results of the pattern. 624 std::vector<unsigned> ResultPerm; 625 626 /// OperatorOrVal - The Record for the operator if this is an interior node 627 /// (not a leaf) or the init value (e.g. the "GPRC" record, or "7") for a 628 /// leaf. 629 PointerUnion<const Record *, const Init *> OperatorOrVal; 630 631 /// Name - The name given to this node with the :$foo notation. 632 /// 633 std::string Name; 634 635 std::vector<ScopedName> NamesAsPredicateArg; 636 637 /// PredicateCalls - The predicate functions to execute on this node to check 638 /// for a match. If this list is empty, no predicate is involved. 639 std::vector<TreePredicateCall> PredicateCalls; 640 641 /// TransformFn - The transformation function to execute on this node before 642 /// it can be substituted into the resulting instruction on a pattern match. 643 const Record *TransformFn; 644 645 std::vector<TreePatternNodePtr> Children; 646 647 /// If this was instantiated from a PatFrag node, and the PatFrag was derived 648 /// from "GISelFlags": the original Record derived from GISelFlags. 649 const Record *GISelFlags = nullptr; 650 651 public: 652 TreePatternNode(const Record *Op, std::vector<TreePatternNodePtr> Ch, 653 unsigned NumResults) 654 : OperatorOrVal(Op), TransformFn(nullptr), Children(std::move(Ch)) { 655 Types.resize(NumResults); 656 ResultPerm.resize(NumResults); 657 std::iota(ResultPerm.begin(), ResultPerm.end(), 0); 658 } 659 TreePatternNode(const Init *val, unsigned NumResults) // leaf ctor 660 : OperatorOrVal(val), TransformFn(nullptr) { 661 Types.resize(NumResults); 662 ResultPerm.resize(NumResults); 663 std::iota(ResultPerm.begin(), ResultPerm.end(), 0); 664 } 665 666 bool hasName() const { return !Name.empty(); } 667 const std::string &getName() const { return Name; } 668 void setName(StringRef N) { Name.assign(N.begin(), N.end()); } 669 670 const std::vector<ScopedName> &getNamesAsPredicateArg() const { 671 return NamesAsPredicateArg; 672 } 673 void setNamesAsPredicateArg(const std::vector<ScopedName> &Names) { 674 NamesAsPredicateArg = Names; 675 } 676 void addNameAsPredicateArg(const ScopedName &N) { 677 NamesAsPredicateArg.push_back(N); 678 } 679 680 bool isLeaf() const { return isa<const Init *>(OperatorOrVal); } 681 682 // Type accessors. 683 unsigned getNumTypes() const { return Types.size(); } 684 ValueTypeByHwMode getType(unsigned ResNo) const { 685 return Types[ResNo].getValueTypeByHwMode(); 686 } 687 const std::vector<TypeSetByHwMode> &getExtTypes() const { return Types; } 688 const TypeSetByHwMode &getExtType(unsigned ResNo) const { 689 return Types[ResNo]; 690 } 691 TypeSetByHwMode &getExtType(unsigned ResNo) { return Types[ResNo]; } 692 void setType(unsigned ResNo, const TypeSetByHwMode &T) { Types[ResNo] = T; } 693 MVT::SimpleValueType getSimpleType(unsigned ResNo) const { 694 return Types[ResNo].getMachineValueType().SimpleTy; 695 } 696 697 bool hasConcreteType(unsigned ResNo) const { 698 return Types[ResNo].isValueTypeByHwMode(false); 699 } 700 bool isTypeCompletelyUnknown(unsigned ResNo, TreePattern &TP) const { 701 return Types[ResNo].empty(); 702 } 703 704 unsigned getNumResults() const { return ResultPerm.size(); } 705 unsigned getResultIndex(unsigned ResNo) const { return ResultPerm[ResNo]; } 706 void setResultIndex(unsigned ResNo, unsigned RI) { ResultPerm[ResNo] = RI; } 707 708 const Init *getLeafValue() const { 709 assert(isLeaf()); 710 return cast<const Init *>(OperatorOrVal); 711 } 712 const Record *getOperator() const { 713 assert(!isLeaf()); 714 return cast<const Record *>(OperatorOrVal); 715 } 716 717 using child_iterator = pointee_iterator<decltype(Children)::iterator>; 718 using child_const_iterator = 719 pointee_iterator<decltype(Children)::const_iterator>; 720 721 iterator_range<child_iterator> children() { 722 return make_pointee_range(Children); 723 } 724 725 iterator_range<child_const_iterator> children() const { 726 return make_pointee_range(Children); 727 } 728 729 unsigned getNumChildren() const { return Children.size(); } 730 const TreePatternNode &getChild(unsigned N) const { 731 return *Children[N].get(); 732 } 733 TreePatternNode &getChild(unsigned N) { return *Children[N].get(); } 734 const TreePatternNodePtr &getChildShared(unsigned N) const { 735 return Children[N]; 736 } 737 TreePatternNodePtr &getChildSharedPtr(unsigned N) { return Children[N]; } 738 void setChild(unsigned i, TreePatternNodePtr N) { Children[i] = N; } 739 740 /// hasChild - Return true if N is any of our children. 741 bool hasChild(const TreePatternNode *N) const { 742 for (unsigned i = 0, e = Children.size(); i != e; ++i) 743 if (Children[i].get() == N) 744 return true; 745 return false; 746 } 747 748 bool hasProperTypeByHwMode() const; 749 bool hasPossibleType() const; 750 bool setDefaultMode(unsigned Mode); 751 752 bool hasAnyPredicate() const { return !PredicateCalls.empty(); } 753 754 const std::vector<TreePredicateCall> &getPredicateCalls() const { 755 return PredicateCalls; 756 } 757 void clearPredicateCalls() { PredicateCalls.clear(); } 758 void setPredicateCalls(const std::vector<TreePredicateCall> &Calls) { 759 assert(PredicateCalls.empty() && "Overwriting non-empty predicate list!"); 760 PredicateCalls = Calls; 761 } 762 void addPredicateCall(const TreePredicateCall &Call) { 763 assert(!Call.Fn.isAlwaysTrue() && "Empty predicate string!"); 764 assert(!is_contained(PredicateCalls, Call) && 765 "predicate applied recursively"); 766 PredicateCalls.push_back(Call); 767 } 768 void addPredicateCall(const TreePredicateFn &Fn, unsigned Scope) { 769 assert((Scope != 0) == Fn.usesOperands()); 770 addPredicateCall(TreePredicateCall(Fn, Scope)); 771 } 772 773 const Record *getTransformFn() const { return TransformFn; } 774 void setTransformFn(const Record *Fn) { TransformFn = Fn; } 775 776 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the 777 /// CodeGenIntrinsic information for it, otherwise return a null pointer. 778 const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const; 779 780 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern, 781 /// return the ComplexPattern information, otherwise return null. 782 const ComplexPattern * 783 getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const; 784 785 /// Returns the number of MachineInstr operands that would be produced by this 786 /// node if it mapped directly to an output Instruction's 787 /// operand. ComplexPattern specifies this explicitly; MIOperandInfo gives it 788 /// for Operands; otherwise 1. 789 unsigned getNumMIResults(const CodeGenDAGPatterns &CGP) const; 790 791 /// NodeHasProperty - Return true if this node has the specified property. 792 bool NodeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const; 793 794 /// TreeHasProperty - Return true if any node in this tree has the specified 795 /// property. 796 bool TreeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const; 797 798 /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is 799 /// marked isCommutative. 800 bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const; 801 802 void setGISelFlagsRecord(const Record *R) { GISelFlags = R; } 803 const Record *getGISelFlagsRecord() const { return GISelFlags; } 804 805 void print(raw_ostream &OS) const; 806 void dump() const; 807 808 public: // Higher level manipulation routines. 809 /// clone - Return a new copy of this tree. 810 /// 811 TreePatternNodePtr clone() const; 812 813 /// RemoveAllTypes - Recursively strip all the types of this tree. 814 void RemoveAllTypes(); 815 816 /// isIsomorphicTo - Return true if this node is recursively isomorphic to 817 /// the specified node. For this comparison, all of the state of the node 818 /// is considered, except for the assigned name. Nodes with differing names 819 /// that are otherwise identical are considered isomorphic. 820 bool isIsomorphicTo(const TreePatternNode &N, 821 const MultipleUseVarSet &DepVars) const; 822 823 /// SubstituteFormalArguments - Replace the formal arguments in this tree 824 /// with actual values specified by ArgMap. 825 void 826 SubstituteFormalArguments(std::map<std::string, TreePatternNodePtr> &ArgMap); 827 828 /// InlinePatternFragments - If \p T pattern refers to any pattern 829 /// fragments, return the set of inlined versions (this can be more than 830 /// one if a PatFrags record has multiple alternatives). 831 void InlinePatternFragments(TreePattern &TP, 832 std::vector<TreePatternNodePtr> &OutAlternatives); 833 834 /// ApplyTypeConstraints - Apply all of the type constraints relevant to 835 /// this node and its children in the tree. This returns true if it makes a 836 /// change, false otherwise. If a type contradiction is found, flag an error. 837 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters); 838 839 /// UpdateNodeType - Set the node type of N to VT if VT contains 840 /// information. If N already contains a conflicting type, then flag an 841 /// error. This returns true if any information was updated. 842 /// 843 bool UpdateNodeType(unsigned ResNo, const TypeSetByHwMode &InTy, 844 TreePattern &TP); 845 bool UpdateNodeType(unsigned ResNo, MVT::SimpleValueType InTy, 846 TreePattern &TP); 847 bool UpdateNodeType(unsigned ResNo, const ValueTypeByHwMode &InTy, 848 TreePattern &TP); 849 850 // Update node type with types inferred from an instruction operand or result 851 // def from the ins/outs lists. 852 // Return true if the type changed. 853 bool UpdateNodeTypeFromInst(unsigned ResNo, const Record *Operand, 854 TreePattern &TP); 855 856 /// ContainsUnresolvedType - Return true if this tree contains any 857 /// unresolved types. 858 bool ContainsUnresolvedType(TreePattern &TP) const; 859 860 /// canPatternMatch - If it is impossible for this pattern to match on this 861 /// target, fill in Reason and return false. Otherwise, return true. 862 bool canPatternMatch(std::string &Reason, 863 const CodeGenDAGPatterns &CDP) const; 864 }; 865 866 inline raw_ostream &operator<<(raw_ostream &OS, const TreePatternNode &TPN) { 867 TPN.print(OS); 868 return OS; 869 } 870 871 /// TreePattern - Represent a pattern, used for instructions, pattern 872 /// fragments, etc. 873 /// 874 class TreePattern { 875 /// Trees - The list of pattern trees which corresponds to this pattern. 876 /// Note that PatFrag's only have a single tree. 877 /// 878 std::vector<TreePatternNodePtr> Trees; 879 880 /// NamedNodes - This is all of the nodes that have names in the trees in this 881 /// pattern. 882 StringMap<SmallVector<TreePatternNode *, 1>> NamedNodes; 883 884 /// TheRecord - The actual TableGen record corresponding to this pattern. 885 /// 886 const Record *TheRecord; 887 888 /// Args - This is a list of all of the arguments to this pattern (for 889 /// PatFrag patterns), which are the 'node' markers in this pattern. 890 std::vector<std::string> Args; 891 892 /// CDP - the top-level object coordinating this madness. 893 /// 894 CodeGenDAGPatterns &CDP; 895 896 /// isInputPattern - True if this is an input pattern, something to match. 897 /// False if this is an output pattern, something to emit. 898 bool isInputPattern; 899 900 /// hasError - True if the currently processed nodes have unresolvable types 901 /// or other non-fatal errors 902 bool HasError; 903 904 /// It's important that the usage of operands in ComplexPatterns is 905 /// consistent: each named operand can be defined by at most one 906 /// ComplexPattern. This records the ComplexPattern instance and the operand 907 /// number for each operand encountered in a ComplexPattern to aid in that 908 /// check. 909 StringMap<std::pair<const Record *, unsigned>> ComplexPatternOperands; 910 911 TypeInfer Infer; 912 913 public: 914 /// TreePattern constructor - Parse the specified DagInits into the 915 /// current record. 916 TreePattern(const Record *TheRec, const ListInit *RawPat, bool isInput, 917 CodeGenDAGPatterns &ise); 918 TreePattern(const Record *TheRec, const DagInit *Pat, bool isInput, 919 CodeGenDAGPatterns &ise); 920 TreePattern(const Record *TheRec, TreePatternNodePtr Pat, bool isInput, 921 CodeGenDAGPatterns &ise); 922 923 /// getTrees - Return the tree patterns which corresponds to this pattern. 924 /// 925 const std::vector<TreePatternNodePtr> &getTrees() const { return Trees; } 926 unsigned getNumTrees() const { return Trees.size(); } 927 const TreePatternNodePtr &getTree(unsigned i) const { return Trees[i]; } 928 void setTree(unsigned i, TreePatternNodePtr Tree) { Trees[i] = Tree; } 929 const TreePatternNodePtr &getOnlyTree() const { 930 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!"); 931 return Trees[0]; 932 } 933 934 const StringMap<SmallVector<TreePatternNode *, 1>> &getNamedNodesMap() { 935 if (NamedNodes.empty()) 936 ComputeNamedNodes(); 937 return NamedNodes; 938 } 939 940 /// getRecord - Return the actual TableGen record corresponding to this 941 /// pattern. 942 /// 943 const Record *getRecord() const { return TheRecord; } 944 945 unsigned getNumArgs() const { return Args.size(); } 946 const std::string &getArgName(unsigned i) const { 947 assert(i < Args.size() && "Argument reference out of range!"); 948 return Args[i]; 949 } 950 std::vector<std::string> &getArgList() { return Args; } 951 952 CodeGenDAGPatterns &getDAGPatterns() const { return CDP; } 953 954 /// InlinePatternFragments - If this pattern refers to any pattern 955 /// fragments, inline them into place, giving us a pattern without any 956 /// PatFrags references. This may increase the number of trees in the 957 /// pattern if a PatFrags has multiple alternatives. 958 void InlinePatternFragments() { 959 std::vector<TreePatternNodePtr> Copy; 960 Trees.swap(Copy); 961 for (const TreePatternNodePtr &C : Copy) 962 C->InlinePatternFragments(*this, Trees); 963 } 964 965 /// InferAllTypes - Infer/propagate as many types throughout the expression 966 /// patterns as possible. Return true if all types are inferred, false 967 /// otherwise. Bail out if a type contradiction is found. 968 bool InferAllTypes( 969 const StringMap<SmallVector<TreePatternNode *, 1>> *NamedTypes = nullptr); 970 971 /// error - If this is the first error in the current resolution step, 972 /// print it and set the error flag. Otherwise, continue silently. 973 void error(const Twine &Msg); 974 bool hasError() const { return HasError; } 975 void resetError() { HasError = false; } 976 977 TypeInfer &getInfer() { return Infer; } 978 979 void print(raw_ostream &OS) const; 980 void dump() const; 981 982 private: 983 TreePatternNodePtr ParseTreePattern(const Init *DI, StringRef OpName); 984 void ComputeNamedNodes(); 985 void ComputeNamedNodes(TreePatternNode &N); 986 }; 987 988 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo, 989 const TypeSetByHwMode &InTy, 990 TreePattern &TP) { 991 TypeSetByHwMode VTS(InTy); 992 TP.getInfer().expandOverloads(VTS); 993 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS); 994 } 995 996 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo, 997 MVT::SimpleValueType InTy, 998 TreePattern &TP) { 999 TypeSetByHwMode VTS(InTy); 1000 TP.getInfer().expandOverloads(VTS); 1001 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS); 1002 } 1003 1004 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo, 1005 const ValueTypeByHwMode &InTy, 1006 TreePattern &TP) { 1007 TypeSetByHwMode VTS(InTy); 1008 TP.getInfer().expandOverloads(VTS); 1009 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS); 1010 } 1011 1012 /// DAGDefaultOperand - One of these is created for each OperandWithDefaultOps 1013 /// that has a set ExecuteAlways / DefaultOps field. 1014 struct DAGDefaultOperand { 1015 std::vector<TreePatternNodePtr> DefaultOps; 1016 }; 1017 1018 class DAGInstruction { 1019 std::vector<const Record *> Results; 1020 std::vector<const Record *> Operands; 1021 std::vector<const Record *> ImpResults; 1022 TreePatternNodePtr SrcPattern; 1023 TreePatternNodePtr ResultPattern; 1024 1025 public: 1026 DAGInstruction(std::vector<const Record *> &&Results, 1027 std::vector<const Record *> &&Operands, 1028 std::vector<const Record *> &&ImpResults, 1029 TreePatternNodePtr SrcPattern = nullptr, 1030 TreePatternNodePtr ResultPattern = nullptr) 1031 : Results(std::move(Results)), Operands(std::move(Operands)), 1032 ImpResults(std::move(ImpResults)), SrcPattern(SrcPattern), 1033 ResultPattern(ResultPattern) {} 1034 1035 unsigned getNumResults() const { return Results.size(); } 1036 unsigned getNumOperands() const { return Operands.size(); } 1037 unsigned getNumImpResults() const { return ImpResults.size(); } 1038 ArrayRef<const Record *> getImpResults() const { return ImpResults; } 1039 1040 const Record *getResult(unsigned RN) const { 1041 assert(RN < Results.size()); 1042 return Results[RN]; 1043 } 1044 1045 const Record *getOperand(unsigned ON) const { 1046 assert(ON < Operands.size()); 1047 return Operands[ON]; 1048 } 1049 1050 const Record *getImpResult(unsigned RN) const { 1051 assert(RN < ImpResults.size()); 1052 return ImpResults[RN]; 1053 } 1054 1055 TreePatternNodePtr getSrcPattern() const { return SrcPattern; } 1056 TreePatternNodePtr getResultPattern() const { return ResultPattern; } 1057 }; 1058 1059 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns 1060 /// processed to produce isel. 1061 class PatternToMatch { 1062 const Record *SrcRecord; // Originating Record for the pattern. 1063 const ListInit *Predicates; // Top level predicate conditions to match. 1064 TreePatternNodePtr SrcPattern; // Source pattern to match. 1065 TreePatternNodePtr DstPattern; // Resulting pattern. 1066 std::vector<const Record *> Dstregs; // Physical register defs being matched. 1067 std::string HwModeFeatures; 1068 int AddedComplexity; // Add to matching pattern complexity. 1069 bool GISelShouldIgnore; // Should GlobalISel ignore importing this pattern. 1070 unsigned ID; // Unique ID for the record. 1071 1072 public: 1073 PatternToMatch(const Record *srcrecord, const ListInit *preds, 1074 TreePatternNodePtr src, TreePatternNodePtr dst, 1075 ArrayRef<const Record *> dstregs, int complexity, unsigned uid, 1076 bool ignore, const Twine &hwmodefeatures = "") 1077 : SrcRecord(srcrecord), Predicates(preds), SrcPattern(src), 1078 DstPattern(dst), Dstregs(dstregs), HwModeFeatures(hwmodefeatures.str()), 1079 AddedComplexity(complexity), GISelShouldIgnore(ignore), ID(uid) {} 1080 1081 const Record *getSrcRecord() const { return SrcRecord; } 1082 const ListInit *getPredicates() const { return Predicates; } 1083 TreePatternNode &getSrcPattern() const { return *SrcPattern; } 1084 TreePatternNodePtr getSrcPatternShared() const { return SrcPattern; } 1085 TreePatternNode &getDstPattern() const { return *DstPattern; } 1086 TreePatternNodePtr getDstPatternShared() const { return DstPattern; } 1087 ArrayRef<const Record *> getDstRegs() const { return Dstregs; } 1088 StringRef getHwModeFeatures() const { return HwModeFeatures; } 1089 int getAddedComplexity() const { return AddedComplexity; } 1090 bool getGISelShouldIgnore() const { return GISelShouldIgnore; } 1091 unsigned getID() const { return ID; } 1092 1093 std::string getPredicateCheck() const; 1094 void 1095 getPredicateRecords(SmallVectorImpl<const Record *> &PredicateRecs) const; 1096 1097 /// Compute the complexity metric for the input pattern. This roughly 1098 /// corresponds to the number of nodes that are covered. 1099 int getPatternComplexity(const CodeGenDAGPatterns &CGP) const; 1100 }; 1101 1102 class CodeGenDAGPatterns { 1103 public: 1104 using NodeXForm = std::pair<const Record *, std::string>; 1105 1106 private: 1107 const RecordKeeper &Records; 1108 CodeGenTarget Target; 1109 CodeGenIntrinsicTable Intrinsics; 1110 1111 std::map<const Record *, SDNodeInfo, LessRecordByID> SDNodes; 1112 1113 std::map<const Record *, NodeXForm, LessRecordByID> SDNodeXForms; 1114 std::map<const Record *, ComplexPattern, LessRecordByID> ComplexPatterns; 1115 std::map<const Record *, std::unique_ptr<TreePattern>, LessRecordByID> 1116 PatternFragments; 1117 std::map<const Record *, DAGDefaultOperand, LessRecordByID> DefaultOperands; 1118 std::map<const Record *, DAGInstruction, LessRecordByID> Instructions; 1119 1120 // Specific SDNode definitions: 1121 const Record *intrinsic_void_sdnode; 1122 const Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode; 1123 1124 /// PatternsToMatch - All of the things we are matching on the DAG. The first 1125 /// value is the pattern to match, the second pattern is the result to 1126 /// emit. 1127 std::vector<PatternToMatch> PatternsToMatch; 1128 1129 TypeSetByHwMode LegalVTS; 1130 1131 using PatternRewriterFn = std::function<void(TreePattern *)>; 1132 PatternRewriterFn PatternRewriter; 1133 1134 unsigned NumScopes = 0; 1135 1136 public: 1137 CodeGenDAGPatterns(const RecordKeeper &R, 1138 PatternRewriterFn PatternRewriter = nullptr); 1139 1140 CodeGenTarget &getTargetInfo() { return Target; } 1141 const CodeGenTarget &getTargetInfo() const { return Target; } 1142 const TypeSetByHwMode &getLegalTypes() const { return LegalVTS; } 1143 1144 const Record *getSDNodeNamed(StringRef Name) const; 1145 1146 const SDNodeInfo &getSDNodeInfo(const Record *R) const { 1147 auto F = SDNodes.find(R); 1148 assert(F != SDNodes.end() && "Unknown node!"); 1149 return F->second; 1150 } 1151 1152 // Node transformation lookups. 1153 const NodeXForm &getSDNodeTransform(const Record *R) const { 1154 auto F = SDNodeXForms.find(R); 1155 assert(F != SDNodeXForms.end() && "Invalid transform!"); 1156 return F->second; 1157 } 1158 1159 const ComplexPattern &getComplexPattern(const Record *R) const { 1160 auto F = ComplexPatterns.find(R); 1161 assert(F != ComplexPatterns.end() && "Unknown addressing mode!"); 1162 return F->second; 1163 } 1164 1165 const CodeGenIntrinsic &getIntrinsic(const Record *R) const { 1166 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i) 1167 if (Intrinsics[i].TheDef == R) 1168 return Intrinsics[i]; 1169 llvm_unreachable("Unknown intrinsic!"); 1170 } 1171 1172 const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const { 1173 if (IID - 1 < Intrinsics.size()) 1174 return Intrinsics[IID - 1]; 1175 llvm_unreachable("Bad intrinsic ID!"); 1176 } 1177 1178 unsigned getIntrinsicID(const Record *R) const { 1179 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i) 1180 if (Intrinsics[i].TheDef == R) 1181 return i; 1182 llvm_unreachable("Unknown intrinsic!"); 1183 } 1184 1185 const DAGDefaultOperand &getDefaultOperand(const Record *R) const { 1186 auto F = DefaultOperands.find(R); 1187 assert(F != DefaultOperands.end() && "Isn't an analyzed default operand!"); 1188 return F->second; 1189 } 1190 1191 // Pattern Fragment information. 1192 TreePattern *getPatternFragment(const Record *R) const { 1193 auto F = PatternFragments.find(R); 1194 assert(F != PatternFragments.end() && "Invalid pattern fragment request!"); 1195 return F->second.get(); 1196 } 1197 TreePattern *getPatternFragmentIfRead(const Record *R) const { 1198 auto F = PatternFragments.find(R); 1199 if (F == PatternFragments.end()) 1200 return nullptr; 1201 return F->second.get(); 1202 } 1203 1204 using pf_iterator = decltype(PatternFragments)::const_iterator; 1205 pf_iterator pf_begin() const { return PatternFragments.begin(); } 1206 pf_iterator pf_end() const { return PatternFragments.end(); } 1207 iterator_range<pf_iterator> ptfs() const { return PatternFragments; } 1208 1209 // Patterns to match information. 1210 typedef std::vector<PatternToMatch>::const_iterator ptm_iterator; 1211 ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); } 1212 ptm_iterator ptm_end() const { return PatternsToMatch.end(); } 1213 iterator_range<ptm_iterator> ptms() const { return PatternsToMatch; } 1214 1215 /// Parse the Pattern for an instruction, and insert the result in DAGInsts. 1216 typedef std::map<const Record *, DAGInstruction, LessRecordByID> DAGInstMap; 1217 void parseInstructionPattern(CodeGenInstruction &CGI, const ListInit *Pattern, 1218 DAGInstMap &DAGInsts); 1219 1220 const DAGInstruction &getInstruction(const Record *R) const { 1221 auto F = Instructions.find(R); 1222 assert(F != Instructions.end() && "Unknown instruction!"); 1223 return F->second; 1224 } 1225 1226 const Record *get_intrinsic_void_sdnode() const { 1227 return intrinsic_void_sdnode; 1228 } 1229 const Record *get_intrinsic_w_chain_sdnode() const { 1230 return intrinsic_w_chain_sdnode; 1231 } 1232 const Record *get_intrinsic_wo_chain_sdnode() const { 1233 return intrinsic_wo_chain_sdnode; 1234 } 1235 1236 unsigned allocateScope() { return ++NumScopes; } 1237 1238 bool operandHasDefault(const Record *Op) const { 1239 return Op->isSubClassOf("OperandWithDefaultOps") && 1240 !getDefaultOperand(Op).DefaultOps.empty(); 1241 } 1242 1243 private: 1244 void ParseNodeInfo(); 1245 void ParseNodeTransforms(); 1246 void ParseComplexPatterns(); 1247 void ParsePatternFragments(bool OutFrags = false); 1248 void ParseDefaultOperands(); 1249 void ParseInstructions(); 1250 void ParsePatterns(); 1251 void ExpandHwModeBasedTypes(); 1252 void InferInstructionFlags(); 1253 void GenerateVariants(); 1254 void VerifyInstructionFlags(); 1255 1256 void ParseOnePattern(const Record *TheDef, TreePattern &Pattern, 1257 TreePattern &Result, 1258 ArrayRef<const Record *> InstImpResults, 1259 bool ShouldIgnore = false); 1260 void AddPatternToMatch(TreePattern *Pattern, PatternToMatch &&PTM); 1261 void FindPatternInputsAndOutputs( 1262 TreePattern &I, TreePatternNodePtr Pat, 1263 std::map<std::string, TreePatternNodePtr> &InstInputs, 1264 MapVector<std::string, TreePatternNodePtr, 1265 std::map<std::string, unsigned>> &InstResults, 1266 std::vector<const Record *> &InstImpResults); 1267 unsigned getNewUID(); 1268 }; 1269 1270 inline bool SDNodeInfo::ApplyTypeConstraints(TreePatternNode &N, 1271 TreePattern &TP) const { 1272 bool MadeChange = false; 1273 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) 1274 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP); 1275 return MadeChange; 1276 } 1277 1278 } // end namespace llvm 1279 1280 #endif // LLVM_UTILS_TABLEGEN_COMMON_CODEGENDAGPATTERNS_H 1281