1 //===- CodeGenDAGPatterns.h - Read DAG patterns from .td file ---*- C++ -*-===// 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 // This file declares the CodeGenDAGPatterns class, which is used to read and 11 // represent the patterns present in a .td file for instructions. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H 16 #define LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H 17 18 #include "CodeGenHwModes.h" 19 #include "CodeGenIntrinsics.h" 20 #include "CodeGenTarget.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringMap.h" 23 #include "llvm/ADT/StringSet.h" 24 #include "llvm/Support/ErrorHandling.h" 25 #include "llvm/Support/MathExtras.h" 26 #include <algorithm> 27 #include <array> 28 #include <map> 29 #include <set> 30 #include <vector> 31 32 namespace llvm { 33 34 class Record; 35 class Init; 36 class ListInit; 37 class DagInit; 38 class SDNodeInfo; 39 class TreePattern; 40 class TreePatternNode; 41 class CodeGenDAGPatterns; 42 class ComplexPattern; 43 44 /// This represents a set of MVTs. Since the underlying type for the MVT 45 /// is uint8_t, there are at most 256 values. To reduce the number of memory 46 /// allocations and deallocations, represent the set as a sequence of bits. 47 /// To reduce the allocations even further, make MachineValueTypeSet own 48 /// the storage and use std::array as the bit container. 49 struct MachineValueTypeSet { 50 static_assert(std::is_same<std::underlying_type<MVT::SimpleValueType>::type, 51 uint8_t>::value, 52 "Change uint8_t here to the SimpleValueType's type"); 53 static unsigned constexpr Capacity = std::numeric_limits<uint8_t>::max()+1; 54 using WordType = uint64_t; 55 static unsigned constexpr WordWidth = CHAR_BIT*sizeof(WordType); 56 static unsigned constexpr NumWords = Capacity/WordWidth; 57 static_assert(NumWords*WordWidth == Capacity, 58 "Capacity should be a multiple of WordWidth"); 59 60 LLVM_ATTRIBUTE_ALWAYS_INLINE 61 MachineValueTypeSet() { 62 clear(); 63 } 64 65 LLVM_ATTRIBUTE_ALWAYS_INLINE 66 unsigned size() const { 67 unsigned Count = 0; 68 for (WordType W : Words) 69 Count += countPopulation(W); 70 return Count; 71 } 72 LLVM_ATTRIBUTE_ALWAYS_INLINE 73 void clear() { 74 std::memset(Words.data(), 0, NumWords*sizeof(WordType)); 75 } 76 LLVM_ATTRIBUTE_ALWAYS_INLINE 77 bool empty() const { 78 for (WordType W : Words) 79 if (W != 0) 80 return false; 81 return true; 82 } 83 LLVM_ATTRIBUTE_ALWAYS_INLINE 84 unsigned count(MVT T) const { 85 return (Words[T.SimpleTy / WordWidth] >> (T.SimpleTy % WordWidth)) & 1; 86 } 87 std::pair<MachineValueTypeSet&,bool> insert(MVT T) { 88 bool V = count(T.SimpleTy); 89 Words[T.SimpleTy / WordWidth] |= WordType(1) << (T.SimpleTy % WordWidth); 90 return {*this, V}; 91 } 92 MachineValueTypeSet &insert(const MachineValueTypeSet &S) { 93 for (unsigned i = 0; i != NumWords; ++i) 94 Words[i] |= S.Words[i]; 95 return *this; 96 } 97 LLVM_ATTRIBUTE_ALWAYS_INLINE 98 void erase(MVT T) { 99 Words[T.SimpleTy / WordWidth] &= ~(WordType(1) << (T.SimpleTy % WordWidth)); 100 } 101 102 struct const_iterator { 103 // Some implementations of the C++ library require these traits to be 104 // defined. 105 using iterator_category = std::forward_iterator_tag; 106 using value_type = MVT; 107 using difference_type = ptrdiff_t; 108 using pointer = const MVT*; 109 using reference = const MVT&; 110 111 LLVM_ATTRIBUTE_ALWAYS_INLINE 112 MVT operator*() const { 113 assert(Pos != Capacity); 114 return MVT::SimpleValueType(Pos); 115 } 116 LLVM_ATTRIBUTE_ALWAYS_INLINE 117 const_iterator(const MachineValueTypeSet *S, bool End) : Set(S) { 118 Pos = End ? Capacity : find_from_pos(0); 119 } 120 LLVM_ATTRIBUTE_ALWAYS_INLINE 121 const_iterator &operator++() { 122 assert(Pos != Capacity); 123 Pos = find_from_pos(Pos+1); 124 return *this; 125 } 126 127 LLVM_ATTRIBUTE_ALWAYS_INLINE 128 bool operator==(const const_iterator &It) const { 129 return Set == It.Set && Pos == It.Pos; 130 } 131 LLVM_ATTRIBUTE_ALWAYS_INLINE 132 bool operator!=(const const_iterator &It) const { 133 return !operator==(It); 134 } 135 136 private: 137 unsigned find_from_pos(unsigned P) const { 138 unsigned SkipWords = P / WordWidth; 139 unsigned SkipBits = P % WordWidth; 140 unsigned Count = SkipWords * WordWidth; 141 142 // If P is in the middle of a word, process it manually here, because 143 // the trailing bits need to be masked off to use findFirstSet. 144 if (SkipBits != 0) { 145 WordType W = Set->Words[SkipWords]; 146 W &= maskLeadingOnes<WordType>(WordWidth-SkipBits); 147 if (W != 0) 148 return Count + findFirstSet(W); 149 Count += WordWidth; 150 SkipWords++; 151 } 152 153 for (unsigned i = SkipWords; i != NumWords; ++i) { 154 WordType W = Set->Words[i]; 155 if (W != 0) 156 return Count + findFirstSet(W); 157 Count += WordWidth; 158 } 159 return Capacity; 160 } 161 162 const MachineValueTypeSet *Set; 163 unsigned Pos; 164 }; 165 166 LLVM_ATTRIBUTE_ALWAYS_INLINE 167 const_iterator begin() const { return const_iterator(this, false); } 168 LLVM_ATTRIBUTE_ALWAYS_INLINE 169 const_iterator end() const { return const_iterator(this, true); } 170 171 LLVM_ATTRIBUTE_ALWAYS_INLINE 172 bool operator==(const MachineValueTypeSet &S) const { 173 return Words == S.Words; 174 } 175 LLVM_ATTRIBUTE_ALWAYS_INLINE 176 bool operator!=(const MachineValueTypeSet &S) const { 177 return !operator==(S); 178 } 179 180 private: 181 friend struct const_iterator; 182 std::array<WordType,NumWords> Words; 183 }; 184 185 struct TypeSetByHwMode : public InfoByHwMode<MachineValueTypeSet> { 186 using SetType = MachineValueTypeSet; 187 188 TypeSetByHwMode() = default; 189 TypeSetByHwMode(const TypeSetByHwMode &VTS) = default; 190 TypeSetByHwMode(MVT::SimpleValueType VT) 191 : TypeSetByHwMode(ValueTypeByHwMode(VT)) {} 192 TypeSetByHwMode(ValueTypeByHwMode VT) 193 : TypeSetByHwMode(ArrayRef<ValueTypeByHwMode>(&VT, 1)) {} 194 TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList); 195 196 SetType &getOrCreate(unsigned Mode) { 197 if (hasMode(Mode)) 198 return get(Mode); 199 return Map.insert({Mode,SetType()}).first->second; 200 } 201 202 bool isValueTypeByHwMode(bool AllowEmpty) const; 203 ValueTypeByHwMode getValueTypeByHwMode() const; 204 205 LLVM_ATTRIBUTE_ALWAYS_INLINE 206 bool isMachineValueType() const { 207 return isDefaultOnly() && Map.begin()->second.size() == 1; 208 } 209 210 LLVM_ATTRIBUTE_ALWAYS_INLINE 211 MVT getMachineValueType() const { 212 assert(isMachineValueType()); 213 return *Map.begin()->second.begin(); 214 } 215 216 bool isPossible() const; 217 218 LLVM_ATTRIBUTE_ALWAYS_INLINE 219 bool isDefaultOnly() const { 220 return Map.size() == 1 && Map.begin()->first == DefaultMode; 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 static void writeToStream(const SetType &S, raw_ostream &OS); 231 232 bool operator==(const TypeSetByHwMode &VTS) const; 233 bool operator!=(const TypeSetByHwMode &VTS) const { return !(*this == VTS); } 234 235 void dump() const; 236 void validate() const; 237 238 private: 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), ForceMode(0) {} 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); 262 bool MergeInTypeInfo(TypeSetByHwMode &Out, MVT::SimpleValueType InVT) { 263 return MergeInTypeInfo(Out, TypeSetByHwMode(InVT)); 264 } 265 bool MergeInTypeInfo(TypeSetByHwMode &Out, ValueTypeByHwMode InVT) { 266 return MergeInTypeInfo(Out, TypeSetByHwMode(InVT)); 267 } 268 269 /// Reduce the set \p Out to have at most one element for each mode. 270 bool forceArbitrary(TypeSetByHwMode &Out); 271 272 /// The following four functions ensure that upon return the set \p Out 273 /// will only contain types of the specified kind: integer, floating-point, 274 /// scalar, or vector. 275 /// If \p Out is empty, all legal types of the specified kind will be added 276 /// to it. Otherwise, all types that are not of the specified kind will be 277 /// removed from \p Out. 278 bool EnforceInteger(TypeSetByHwMode &Out); 279 bool EnforceFloatingPoint(TypeSetByHwMode &Out); 280 bool EnforceScalar(TypeSetByHwMode &Out); 281 bool EnforceVector(TypeSetByHwMode &Out); 282 283 /// If \p Out is empty, fill it with all legal types. Otherwise, leave it 284 /// unchanged. 285 bool EnforceAny(TypeSetByHwMode &Out); 286 /// Make sure that for each type in \p Small, there exists a larger type 287 /// in \p Big. 288 bool EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big); 289 /// 1. Ensure that for each type T in \p Vec, T is a vector type, and that 290 /// for each type U in \p Elem, U is a scalar type. 291 /// 2. Ensure that for each (scalar) type U in \p Elem, there exists a 292 /// (vector) type T in \p Vec, such that U is the element type of T. 293 bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, TypeSetByHwMode &Elem); 294 bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, 295 const ValueTypeByHwMode &VVT); 296 /// Ensure that for each type T in \p Sub, T is a vector type, and there 297 /// exists a type U in \p Vec such that U is a vector type with the same 298 /// element type as T and at least as many elements as T. 299 bool EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec, 300 TypeSetByHwMode &Sub); 301 /// 1. Ensure that \p V has a scalar type iff \p W has a scalar type. 302 /// 2. Ensure that for each vector type T in \p V, there exists a vector 303 /// type U in \p W, such that T and U have the same number of elements. 304 /// 3. Ensure that for each vector type U in \p W, there exists a vector 305 /// type T in \p V, such that T and U have the same number of elements 306 /// (reverse of 2). 307 bool EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W); 308 /// 1. Ensure that for each type T in \p A, there exists a type U in \p B, 309 /// such that T and U have equal size in bits. 310 /// 2. Ensure that for each type U in \p B, there exists a type T in \p A 311 /// such that T and U have equal size in bits (reverse of 1). 312 bool EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B); 313 314 /// For each overloaded type (i.e. of form *Any), replace it with the 315 /// corresponding subset of legal, specific types. 316 void expandOverloads(TypeSetByHwMode &VTS); 317 void expandOverloads(TypeSetByHwMode::SetType &Out, 318 const TypeSetByHwMode::SetType &Legal); 319 320 struct ValidateOnExit { 321 ValidateOnExit(TypeSetByHwMode &T) : VTS(T) {} 322 ~ValidateOnExit() { VTS.validate(); } 323 TypeSetByHwMode &VTS; 324 }; 325 326 TreePattern &TP; 327 unsigned ForceMode; // Mode to use when set. 328 bool CodeGen = false; // Set during generation of matcher code. 329 330 private: 331 TypeSetByHwMode getLegalTypes(); 332 333 /// Cached legal types. 334 bool LegalTypesCached = false; 335 TypeSetByHwMode::SetType LegalCache = {}; 336 }; 337 338 /// Set type used to track multiply used variables in patterns 339 typedef StringSet<> MultipleUseVarSet; 340 341 /// SDTypeConstraint - This is a discriminated union of constraints, 342 /// corresponding to the SDTypeConstraint tablegen class in Target.td. 343 struct SDTypeConstraint { 344 SDTypeConstraint(Record *R, const CodeGenHwModes &CGH); 345 346 unsigned OperandNo; // The operand # this constraint applies to. 347 enum { 348 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisVec, SDTCisSameAs, 349 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisEltOfVec, 350 SDTCisSubVecOfVec, SDTCVecEltisVT, SDTCisSameNumEltsAs, SDTCisSameSizeAs 351 } ConstraintType; 352 353 union { // The discriminated union. 354 struct { 355 unsigned OtherOperandNum; 356 } SDTCisSameAs_Info; 357 struct { 358 unsigned OtherOperandNum; 359 } SDTCisVTSmallerThanOp_Info; 360 struct { 361 unsigned BigOperandNum; 362 } SDTCisOpSmallerThanOp_Info; 363 struct { 364 unsigned OtherOperandNum; 365 } SDTCisEltOfVec_Info; 366 struct { 367 unsigned OtherOperandNum; 368 } SDTCisSubVecOfVec_Info; 369 struct { 370 unsigned OtherOperandNum; 371 } SDTCisSameNumEltsAs_Info; 372 struct { 373 unsigned OtherOperandNum; 374 } SDTCisSameSizeAs_Info; 375 } x; 376 377 // The VT for SDTCisVT and SDTCVecEltisVT. 378 // Must not be in the union because it has a non-trivial destructor. 379 ValueTypeByHwMode VVT; 380 381 /// ApplyTypeConstraint - Given a node in a pattern, apply this type 382 /// constraint to the nodes operands. This returns true if it makes a 383 /// change, false otherwise. If a type contradiction is found, an error 384 /// is flagged. 385 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo, 386 TreePattern &TP) const; 387 }; 388 389 /// SDNodeInfo - One of these records is created for each SDNode instance in 390 /// the target .td file. This represents the various dag nodes we will be 391 /// processing. 392 class SDNodeInfo { 393 Record *Def; 394 StringRef EnumName; 395 StringRef SDClassName; 396 unsigned Properties; 397 unsigned NumResults; 398 int NumOperands; 399 std::vector<SDTypeConstraint> TypeConstraints; 400 public: 401 // Parse the specified record. 402 SDNodeInfo(Record *R, const CodeGenHwModes &CGH); 403 404 unsigned getNumResults() const { return NumResults; } 405 406 /// getNumOperands - This is the number of operands required or -1 if 407 /// variadic. 408 int getNumOperands() const { return NumOperands; } 409 Record *getRecord() const { return Def; } 410 StringRef getEnumName() const { return EnumName; } 411 StringRef getSDClassName() const { return SDClassName; } 412 413 const std::vector<SDTypeConstraint> &getTypeConstraints() const { 414 return TypeConstraints; 415 } 416 417 /// getKnownType - If the type constraints on this node imply a fixed type 418 /// (e.g. all stores return void, etc), then return it as an 419 /// MVT::SimpleValueType. Otherwise, return MVT::Other. 420 MVT::SimpleValueType getKnownType(unsigned ResNo) const; 421 422 /// hasProperty - Return true if this node has the specified property. 423 /// 424 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); } 425 426 /// ApplyTypeConstraints - Given a node in a pattern, apply the type 427 /// constraints for this node to the operands of the node. This returns 428 /// true if it makes a change, false otherwise. If a type contradiction is 429 /// found, an error is flagged. 430 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const; 431 }; 432 433 /// TreePredicateFn - This is an abstraction that represents the predicates on 434 /// a PatFrag node. This is a simple one-word wrapper around a pointer to 435 /// provide nice accessors. 436 class TreePredicateFn { 437 /// PatFragRec - This is the TreePattern for the PatFrag that we 438 /// originally came from. 439 TreePattern *PatFragRec; 440 public: 441 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag. 442 TreePredicateFn(TreePattern *N); 443 444 445 TreePattern *getOrigPatFragRecord() const { return PatFragRec; } 446 447 /// isAlwaysTrue - Return true if this is a noop predicate. 448 bool isAlwaysTrue() const; 449 450 bool isImmediatePattern() const { return !getImmCode().empty(); } 451 452 /// getImmediatePredicateCode - Return the code that evaluates this pattern if 453 /// this is an immediate predicate. It is an error to call this on a 454 /// non-immediate pattern. 455 std::string getImmediatePredicateCode() const { 456 std::string Result = getImmCode(); 457 assert(!Result.empty() && "Isn't an immediate pattern!"); 458 return Result; 459 } 460 461 462 bool operator==(const TreePredicateFn &RHS) const { 463 return PatFragRec == RHS.PatFragRec; 464 } 465 466 bool operator!=(const TreePredicateFn &RHS) const { return !(*this == RHS); } 467 468 /// Return the name to use in the generated code to reference this, this is 469 /// "Predicate_foo" if from a pattern fragment "foo". 470 std::string getFnName() const; 471 472 /// getCodeToRunOnSDNode - Return the code for the function body that 473 /// evaluates this predicate. The argument is expected to be in "Node", 474 /// not N. This handles casting and conversion to a concrete node type as 475 /// appropriate. 476 std::string getCodeToRunOnSDNode() const; 477 478 /// Get the data type of the argument to getImmediatePredicateCode(). 479 std::string getImmType() const; 480 481 /// Get a string that describes the type returned by getImmType() but is 482 /// usable as part of an identifier. 483 std::string getImmTypeIdentifier() const; 484 485 private: 486 std::string getPredCode() const; 487 std::string getImmCode() const; 488 bool immCodeUsesAPInt() const; 489 bool immCodeUsesAPFloat() const; 490 }; 491 492 493 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped 494 /// patterns), and as such should be ref counted. We currently just leak all 495 /// TreePatternNode objects! 496 class TreePatternNode { 497 /// The type of each node result. Before and during type inference, each 498 /// result may be a set of possible types. After (successful) type inference, 499 /// each is a single concrete type. 500 std::vector<TypeSetByHwMode> Types; 501 502 /// Operator - The Record for the operator if this is an interior node (not 503 /// a leaf). 504 Record *Operator; 505 506 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf. 507 /// 508 Init *Val; 509 510 /// Name - The name given to this node with the :$foo notation. 511 /// 512 std::string Name; 513 514 /// PredicateFns - The predicate functions to execute on this node to check 515 /// for a match. If this list is empty, no predicate is involved. 516 std::vector<TreePredicateFn> PredicateFns; 517 518 /// TransformFn - The transformation function to execute on this node before 519 /// it can be substituted into the resulting instruction on a pattern match. 520 Record *TransformFn; 521 522 std::vector<TreePatternNode*> Children; 523 public: 524 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch, 525 unsigned NumResults) 526 : Operator(Op), Val(nullptr), TransformFn(nullptr), Children(Ch) { 527 Types.resize(NumResults); 528 } 529 TreePatternNode(Init *val, unsigned NumResults) // leaf ctor 530 : Operator(nullptr), Val(val), TransformFn(nullptr) { 531 Types.resize(NumResults); 532 } 533 ~TreePatternNode(); 534 535 bool hasName() const { return !Name.empty(); } 536 const std::string &getName() const { return Name; } 537 void setName(StringRef N) { Name.assign(N.begin(), N.end()); } 538 539 bool isLeaf() const { return Val != nullptr; } 540 541 // Type accessors. 542 unsigned getNumTypes() const { return Types.size(); } 543 ValueTypeByHwMode getType(unsigned ResNo) const { 544 return Types[ResNo].getValueTypeByHwMode(); 545 } 546 const std::vector<TypeSetByHwMode> &getExtTypes() const { return Types; } 547 const TypeSetByHwMode &getExtType(unsigned ResNo) const { 548 return Types[ResNo]; 549 } 550 TypeSetByHwMode &getExtType(unsigned ResNo) { return Types[ResNo]; } 551 void setType(unsigned ResNo, const TypeSetByHwMode &T) { Types[ResNo] = T; } 552 MVT::SimpleValueType getSimpleType(unsigned ResNo) const { 553 return Types[ResNo].getMachineValueType().SimpleTy; 554 } 555 556 bool hasConcreteType(unsigned ResNo) const { 557 return Types[ResNo].isValueTypeByHwMode(false); 558 } 559 bool isTypeCompletelyUnknown(unsigned ResNo, TreePattern &TP) const { 560 return Types[ResNo].empty(); 561 } 562 563 Init *getLeafValue() const { assert(isLeaf()); return Val; } 564 Record *getOperator() const { assert(!isLeaf()); return Operator; } 565 566 unsigned getNumChildren() const { return Children.size(); } 567 TreePatternNode *getChild(unsigned N) const { return Children[N]; } 568 void setChild(unsigned i, TreePatternNode *N) { 569 Children[i] = N; 570 } 571 572 /// hasChild - Return true if N is any of our children. 573 bool hasChild(const TreePatternNode *N) const { 574 for (unsigned i = 0, e = Children.size(); i != e; ++i) 575 if (Children[i] == N) return true; 576 return false; 577 } 578 579 bool hasProperTypeByHwMode() const; 580 bool hasPossibleType() const; 581 bool setDefaultMode(unsigned Mode); 582 583 bool hasAnyPredicate() const { return !PredicateFns.empty(); } 584 585 const std::vector<TreePredicateFn> &getPredicateFns() const { 586 return PredicateFns; 587 } 588 void clearPredicateFns() { PredicateFns.clear(); } 589 void setPredicateFns(const std::vector<TreePredicateFn> &Fns) { 590 assert(PredicateFns.empty() && "Overwriting non-empty predicate list!"); 591 PredicateFns = Fns; 592 } 593 void addPredicateFn(const TreePredicateFn &Fn) { 594 assert(!Fn.isAlwaysTrue() && "Empty predicate string!"); 595 if (!is_contained(PredicateFns, Fn)) 596 PredicateFns.push_back(Fn); 597 } 598 599 Record *getTransformFn() const { return TransformFn; } 600 void setTransformFn(Record *Fn) { TransformFn = Fn; } 601 602 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the 603 /// CodeGenIntrinsic information for it, otherwise return a null pointer. 604 const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const; 605 606 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern, 607 /// return the ComplexPattern information, otherwise return null. 608 const ComplexPattern * 609 getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const; 610 611 /// Returns the number of MachineInstr operands that would be produced by this 612 /// node if it mapped directly to an output Instruction's 613 /// operand. ComplexPattern specifies this explicitly; MIOperandInfo gives it 614 /// for Operands; otherwise 1. 615 unsigned getNumMIResults(const CodeGenDAGPatterns &CGP) const; 616 617 /// NodeHasProperty - Return true if this node has the specified property. 618 bool NodeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const; 619 620 /// TreeHasProperty - Return true if any node in this tree has the specified 621 /// property. 622 bool TreeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const; 623 624 /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is 625 /// marked isCommutative. 626 bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const; 627 628 void print(raw_ostream &OS) const; 629 void dump() const; 630 631 public: // Higher level manipulation routines. 632 633 /// clone - Return a new copy of this tree. 634 /// 635 TreePatternNode *clone() const; 636 637 /// RemoveAllTypes - Recursively strip all the types of this tree. 638 void RemoveAllTypes(); 639 640 /// isIsomorphicTo - Return true if this node is recursively isomorphic to 641 /// the specified node. For this comparison, all of the state of the node 642 /// is considered, except for the assigned name. Nodes with differing names 643 /// that are otherwise identical are considered isomorphic. 644 bool isIsomorphicTo(const TreePatternNode *N, 645 const MultipleUseVarSet &DepVars) const; 646 647 /// SubstituteFormalArguments - Replace the formal arguments in this tree 648 /// with actual values specified by ArgMap. 649 void SubstituteFormalArguments(std::map<std::string, 650 TreePatternNode*> &ArgMap); 651 652 /// InlinePatternFragments - If this pattern refers to any pattern 653 /// fragments, inline them into place, giving us a pattern without any 654 /// PatFrag references. 655 TreePatternNode *InlinePatternFragments(TreePattern &TP); 656 657 /// ApplyTypeConstraints - Apply all of the type constraints relevant to 658 /// this node and its children in the tree. This returns true if it makes a 659 /// change, false otherwise. If a type contradiction is found, flag an error. 660 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters); 661 662 /// UpdateNodeType - Set the node type of N to VT if VT contains 663 /// information. If N already contains a conflicting type, then flag an 664 /// error. This returns true if any information was updated. 665 /// 666 bool UpdateNodeType(unsigned ResNo, const TypeSetByHwMode &InTy, 667 TreePattern &TP); 668 bool UpdateNodeType(unsigned ResNo, MVT::SimpleValueType InTy, 669 TreePattern &TP); 670 bool UpdateNodeType(unsigned ResNo, ValueTypeByHwMode InTy, 671 TreePattern &TP); 672 673 // Update node type with types inferred from an instruction operand or result 674 // def from the ins/outs lists. 675 // Return true if the type changed. 676 bool UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand, TreePattern &TP); 677 678 /// ContainsUnresolvedType - Return true if this tree contains any 679 /// unresolved types. 680 bool ContainsUnresolvedType(TreePattern &TP) const; 681 682 /// canPatternMatch - If it is impossible for this pattern to match on this 683 /// target, fill in Reason and return false. Otherwise, return true. 684 bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP); 685 }; 686 687 inline raw_ostream &operator<<(raw_ostream &OS, const TreePatternNode &TPN) { 688 TPN.print(OS); 689 return OS; 690 } 691 692 693 /// TreePattern - Represent a pattern, used for instructions, pattern 694 /// fragments, etc. 695 /// 696 class TreePattern { 697 /// Trees - The list of pattern trees which corresponds to this pattern. 698 /// Note that PatFrag's only have a single tree. 699 /// 700 std::vector<TreePatternNode*> Trees; 701 702 /// NamedNodes - This is all of the nodes that have names in the trees in this 703 /// pattern. 704 StringMap<SmallVector<TreePatternNode*,1> > NamedNodes; 705 706 /// TheRecord - The actual TableGen record corresponding to this pattern. 707 /// 708 Record *TheRecord; 709 710 /// Args - This is a list of all of the arguments to this pattern (for 711 /// PatFrag patterns), which are the 'node' markers in this pattern. 712 std::vector<std::string> Args; 713 714 /// CDP - the top-level object coordinating this madness. 715 /// 716 CodeGenDAGPatterns &CDP; 717 718 /// isInputPattern - True if this is an input pattern, something to match. 719 /// False if this is an output pattern, something to emit. 720 bool isInputPattern; 721 722 /// hasError - True if the currently processed nodes have unresolvable types 723 /// or other non-fatal errors 724 bool HasError; 725 726 /// It's important that the usage of operands in ComplexPatterns is 727 /// consistent: each named operand can be defined by at most one 728 /// ComplexPattern. This records the ComplexPattern instance and the operand 729 /// number for each operand encountered in a ComplexPattern to aid in that 730 /// check. 731 StringMap<std::pair<Record *, unsigned>> ComplexPatternOperands; 732 733 TypeInfer Infer; 734 735 public: 736 737 /// TreePattern constructor - Parse the specified DagInits into the 738 /// current record. 739 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput, 740 CodeGenDAGPatterns &ise); 741 TreePattern(Record *TheRec, DagInit *Pat, bool isInput, 742 CodeGenDAGPatterns &ise); 743 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput, 744 CodeGenDAGPatterns &ise); 745 746 /// getTrees - Return the tree patterns which corresponds to this pattern. 747 /// 748 const std::vector<TreePatternNode*> &getTrees() const { return Trees; } 749 unsigned getNumTrees() const { return Trees.size(); } 750 TreePatternNode *getTree(unsigned i) const { return Trees[i]; } 751 TreePatternNode *getOnlyTree() const { 752 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!"); 753 return Trees[0]; 754 } 755 756 const StringMap<SmallVector<TreePatternNode*,1> > &getNamedNodesMap() { 757 if (NamedNodes.empty()) 758 ComputeNamedNodes(); 759 return NamedNodes; 760 } 761 762 /// getRecord - Return the actual TableGen record corresponding to this 763 /// pattern. 764 /// 765 Record *getRecord() const { return TheRecord; } 766 767 unsigned getNumArgs() const { return Args.size(); } 768 const std::string &getArgName(unsigned i) const { 769 assert(i < Args.size() && "Argument reference out of range!"); 770 return Args[i]; 771 } 772 std::vector<std::string> &getArgList() { return Args; } 773 774 CodeGenDAGPatterns &getDAGPatterns() const { return CDP; } 775 776 /// InlinePatternFragments - If this pattern refers to any pattern 777 /// fragments, inline them into place, giving us a pattern without any 778 /// PatFrag references. 779 void InlinePatternFragments() { 780 for (unsigned i = 0, e = Trees.size(); i != e; ++i) 781 Trees[i] = Trees[i]->InlinePatternFragments(*this); 782 } 783 784 /// InferAllTypes - Infer/propagate as many types throughout the expression 785 /// patterns as possible. Return true if all types are inferred, false 786 /// otherwise. Bail out if a type contradiction is found. 787 bool InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > 788 *NamedTypes=nullptr); 789 790 /// error - If this is the first error in the current resolution step, 791 /// print it and set the error flag. Otherwise, continue silently. 792 void error(const Twine &Msg); 793 bool hasError() const { 794 return HasError; 795 } 796 void resetError() { 797 HasError = false; 798 } 799 800 TypeInfer &getInfer() { return Infer; } 801 802 void print(raw_ostream &OS) const; 803 void dump() const; 804 805 private: 806 TreePatternNode *ParseTreePattern(Init *DI, StringRef OpName); 807 void ComputeNamedNodes(); 808 void ComputeNamedNodes(TreePatternNode *N); 809 }; 810 811 812 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo, 813 const TypeSetByHwMode &InTy, 814 TreePattern &TP) { 815 TypeSetByHwMode VTS(InTy); 816 TP.getInfer().expandOverloads(VTS); 817 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS); 818 } 819 820 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo, 821 MVT::SimpleValueType InTy, 822 TreePattern &TP) { 823 TypeSetByHwMode VTS(InTy); 824 TP.getInfer().expandOverloads(VTS); 825 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS); 826 } 827 828 inline bool TreePatternNode::UpdateNodeType(unsigned ResNo, 829 ValueTypeByHwMode InTy, 830 TreePattern &TP) { 831 TypeSetByHwMode VTS(InTy); 832 TP.getInfer().expandOverloads(VTS); 833 return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS); 834 } 835 836 837 /// DAGDefaultOperand - One of these is created for each OperandWithDefaultOps 838 /// that has a set ExecuteAlways / DefaultOps field. 839 struct DAGDefaultOperand { 840 std::vector<TreePatternNode*> DefaultOps; 841 }; 842 843 class DAGInstruction { 844 TreePattern *Pattern; 845 std::vector<Record*> Results; 846 std::vector<Record*> Operands; 847 std::vector<Record*> ImpResults; 848 TreePatternNode *ResultPattern; 849 public: 850 DAGInstruction(TreePattern *TP, 851 const std::vector<Record*> &results, 852 const std::vector<Record*> &operands, 853 const std::vector<Record*> &impresults) 854 : Pattern(TP), Results(results), Operands(operands), 855 ImpResults(impresults), ResultPattern(nullptr) {} 856 857 TreePattern *getPattern() const { return Pattern; } 858 unsigned getNumResults() const { return Results.size(); } 859 unsigned getNumOperands() const { return Operands.size(); } 860 unsigned getNumImpResults() const { return ImpResults.size(); } 861 const std::vector<Record*>& getImpResults() const { return ImpResults; } 862 863 void setResultPattern(TreePatternNode *R) { ResultPattern = R; } 864 865 Record *getResult(unsigned RN) const { 866 assert(RN < Results.size()); 867 return Results[RN]; 868 } 869 870 Record *getOperand(unsigned ON) const { 871 assert(ON < Operands.size()); 872 return Operands[ON]; 873 } 874 875 Record *getImpResult(unsigned RN) const { 876 assert(RN < ImpResults.size()); 877 return ImpResults[RN]; 878 } 879 880 TreePatternNode *getResultPattern() const { return ResultPattern; } 881 }; 882 883 /// This class represents a condition that has to be satisfied for a pattern 884 /// to be tried. It is a generalization of a class "Pattern" from Target.td: 885 /// in addition to the Target.td's predicates, this class can also represent 886 /// conditions associated with HW modes. Both types will eventually become 887 /// strings containing C++ code to be executed, the difference is in how 888 /// these strings are generated. 889 class Predicate { 890 public: 891 Predicate(Record *R, bool C = true) : Def(R), IfCond(C), IsHwMode(false) { 892 assert(R->isSubClassOf("Predicate") && 893 "Predicate objects should only be created for records derived" 894 "from Predicate class"); 895 } 896 Predicate(StringRef FS, bool C = true) : Def(nullptr), Features(FS.str()), 897 IfCond(C), IsHwMode(true) {} 898 899 /// Return a string which contains the C++ condition code that will serve 900 /// as a predicate during instruction selection. 901 std::string getCondString() const { 902 // The string will excute in a subclass of SelectionDAGISel. 903 // Cast to std::string explicitly to avoid ambiguity with StringRef. 904 std::string C = IsHwMode 905 ? std::string("MF->getSubtarget().checkFeatures(\"" + Features + "\")") 906 : std::string(Def->getValueAsString("CondString")); 907 return IfCond ? C : "!("+C+')'; 908 } 909 bool operator==(const Predicate &P) const { 910 return IfCond == P.IfCond && IsHwMode == P.IsHwMode && Def == P.Def; 911 } 912 bool operator<(const Predicate &P) const { 913 if (IsHwMode != P.IsHwMode) 914 return IsHwMode < P.IsHwMode; 915 assert(!Def == !P.Def && "Inconsistency between Def and IsHwMode"); 916 if (IfCond != P.IfCond) 917 return IfCond < P.IfCond; 918 if (Def) 919 return LessRecord()(Def, P.Def); 920 return Features < P.Features; 921 } 922 Record *Def; ///< Predicate definition from .td file, null for 923 ///< HW modes. 924 std::string Features; ///< Feature string for HW mode. 925 bool IfCond; ///< The boolean value that the condition has to 926 ///< evaluate to for this predicate to be true. 927 bool IsHwMode; ///< Does this predicate correspond to a HW mode? 928 }; 929 930 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns 931 /// processed to produce isel. 932 class PatternToMatch { 933 public: 934 PatternToMatch(Record *srcrecord, const std::vector<Predicate> &preds, 935 TreePatternNode *src, TreePatternNode *dst, 936 const std::vector<Record*> &dstregs, 937 int complexity, unsigned uid, unsigned setmode = 0) 938 : SrcRecord(srcrecord), SrcPattern(src), DstPattern(dst), 939 Predicates(preds), Dstregs(std::move(dstregs)), 940 AddedComplexity(complexity), ID(uid), ForceMode(setmode) {} 941 942 PatternToMatch(Record *srcrecord, std::vector<Predicate> &&preds, 943 TreePatternNode *src, TreePatternNode *dst, 944 std::vector<Record*> &&dstregs, 945 int complexity, unsigned uid, unsigned setmode = 0) 946 : SrcRecord(srcrecord), SrcPattern(src), DstPattern(dst), 947 Predicates(preds), Dstregs(std::move(dstregs)), 948 AddedComplexity(complexity), ID(uid), ForceMode(setmode) {} 949 950 Record *SrcRecord; // Originating Record for the pattern. 951 TreePatternNode *SrcPattern; // Source pattern to match. 952 TreePatternNode *DstPattern; // Resulting pattern. 953 std::vector<Predicate> Predicates; // Top level predicate conditions 954 // to match. 955 std::vector<Record*> Dstregs; // Physical register defs being matched. 956 int AddedComplexity; // Add to matching pattern complexity. 957 unsigned ID; // Unique ID for the record. 958 unsigned ForceMode; // Force this mode in type inference when set. 959 960 Record *getSrcRecord() const { return SrcRecord; } 961 TreePatternNode *getSrcPattern() const { return SrcPattern; } 962 TreePatternNode *getDstPattern() const { return DstPattern; } 963 const std::vector<Record*> &getDstRegs() const { return Dstregs; } 964 int getAddedComplexity() const { return AddedComplexity; } 965 const std::vector<Predicate> &getPredicates() const { return Predicates; } 966 967 std::string getPredicateCheck() const; 968 969 /// Compute the complexity metric for the input pattern. This roughly 970 /// corresponds to the number of nodes that are covered. 971 int getPatternComplexity(const CodeGenDAGPatterns &CGP) const; 972 }; 973 974 class CodeGenDAGPatterns { 975 RecordKeeper &Records; 976 CodeGenTarget Target; 977 CodeGenIntrinsicTable Intrinsics; 978 CodeGenIntrinsicTable TgtIntrinsics; 979 980 std::map<Record*, SDNodeInfo, LessRecordByID> SDNodes; 981 std::map<Record*, std::pair<Record*, std::string>, LessRecordByID> 982 SDNodeXForms; 983 std::map<Record*, ComplexPattern, LessRecordByID> ComplexPatterns; 984 std::map<Record *, std::unique_ptr<TreePattern>, LessRecordByID> 985 PatternFragments; 986 std::map<Record*, DAGDefaultOperand, LessRecordByID> DefaultOperands; 987 std::map<Record*, DAGInstruction, LessRecordByID> Instructions; 988 989 // Specific SDNode definitions: 990 Record *intrinsic_void_sdnode; 991 Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode; 992 993 /// PatternsToMatch - All of the things we are matching on the DAG. The first 994 /// value is the pattern to match, the second pattern is the result to 995 /// emit. 996 std::vector<PatternToMatch> PatternsToMatch; 997 998 TypeSetByHwMode LegalVTS; 999 1000 public: 1001 CodeGenDAGPatterns(RecordKeeper &R); 1002 1003 CodeGenTarget &getTargetInfo() { return Target; } 1004 const CodeGenTarget &getTargetInfo() const { return Target; } 1005 const TypeSetByHwMode &getLegalTypes() const { return LegalVTS; } 1006 1007 Record *getSDNodeNamed(const std::string &Name) const; 1008 1009 const SDNodeInfo &getSDNodeInfo(Record *R) const { 1010 auto F = SDNodes.find(R); 1011 assert(F != SDNodes.end() && "Unknown node!"); 1012 return F->second; 1013 } 1014 1015 // Node transformation lookups. 1016 typedef std::pair<Record*, std::string> NodeXForm; 1017 const NodeXForm &getSDNodeTransform(Record *R) const { 1018 auto F = SDNodeXForms.find(R); 1019 assert(F != SDNodeXForms.end() && "Invalid transform!"); 1020 return F->second; 1021 } 1022 1023 typedef std::map<Record*, NodeXForm, LessRecordByID>::const_iterator 1024 nx_iterator; 1025 nx_iterator nx_begin() const { return SDNodeXForms.begin(); } 1026 nx_iterator nx_end() const { return SDNodeXForms.end(); } 1027 1028 1029 const ComplexPattern &getComplexPattern(Record *R) const { 1030 auto F = ComplexPatterns.find(R); 1031 assert(F != ComplexPatterns.end() && "Unknown addressing mode!"); 1032 return F->second; 1033 } 1034 1035 const CodeGenIntrinsic &getIntrinsic(Record *R) const { 1036 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i) 1037 if (Intrinsics[i].TheDef == R) return Intrinsics[i]; 1038 for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i) 1039 if (TgtIntrinsics[i].TheDef == R) return TgtIntrinsics[i]; 1040 llvm_unreachable("Unknown intrinsic!"); 1041 } 1042 1043 const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const { 1044 if (IID-1 < Intrinsics.size()) 1045 return Intrinsics[IID-1]; 1046 if (IID-Intrinsics.size()-1 < TgtIntrinsics.size()) 1047 return TgtIntrinsics[IID-Intrinsics.size()-1]; 1048 llvm_unreachable("Bad intrinsic ID!"); 1049 } 1050 1051 unsigned getIntrinsicID(Record *R) const { 1052 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i) 1053 if (Intrinsics[i].TheDef == R) return i; 1054 for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i) 1055 if (TgtIntrinsics[i].TheDef == R) return i + Intrinsics.size(); 1056 llvm_unreachable("Unknown intrinsic!"); 1057 } 1058 1059 const DAGDefaultOperand &getDefaultOperand(Record *R) const { 1060 auto F = DefaultOperands.find(R); 1061 assert(F != DefaultOperands.end() &&"Isn't an analyzed default operand!"); 1062 return F->second; 1063 } 1064 1065 // Pattern Fragment information. 1066 TreePattern *getPatternFragment(Record *R) const { 1067 auto F = PatternFragments.find(R); 1068 assert(F != PatternFragments.end() && "Invalid pattern fragment request!"); 1069 return F->second.get(); 1070 } 1071 TreePattern *getPatternFragmentIfRead(Record *R) const { 1072 auto F = PatternFragments.find(R); 1073 if (F == PatternFragments.end()) 1074 return nullptr; 1075 return F->second.get(); 1076 } 1077 1078 typedef std::map<Record *, std::unique_ptr<TreePattern>, 1079 LessRecordByID>::const_iterator pf_iterator; 1080 pf_iterator pf_begin() const { return PatternFragments.begin(); } 1081 pf_iterator pf_end() const { return PatternFragments.end(); } 1082 iterator_range<pf_iterator> ptfs() const { return PatternFragments; } 1083 1084 // Patterns to match information. 1085 typedef std::vector<PatternToMatch>::const_iterator ptm_iterator; 1086 ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); } 1087 ptm_iterator ptm_end() const { return PatternsToMatch.end(); } 1088 iterator_range<ptm_iterator> ptms() const { return PatternsToMatch; } 1089 1090 /// Parse the Pattern for an instruction, and insert the result in DAGInsts. 1091 typedef std::map<Record*, DAGInstruction, LessRecordByID> DAGInstMap; 1092 const DAGInstruction &parseInstructionPattern( 1093 CodeGenInstruction &CGI, ListInit *Pattern, 1094 DAGInstMap &DAGInsts); 1095 1096 const DAGInstruction &getInstruction(Record *R) const { 1097 auto F = Instructions.find(R); 1098 assert(F != Instructions.end() && "Unknown instruction!"); 1099 return F->second; 1100 } 1101 1102 Record *get_intrinsic_void_sdnode() const { 1103 return intrinsic_void_sdnode; 1104 } 1105 Record *get_intrinsic_w_chain_sdnode() const { 1106 return intrinsic_w_chain_sdnode; 1107 } 1108 Record *get_intrinsic_wo_chain_sdnode() const { 1109 return intrinsic_wo_chain_sdnode; 1110 } 1111 1112 bool hasTargetIntrinsics() { return !TgtIntrinsics.empty(); } 1113 1114 private: 1115 void ParseNodeInfo(); 1116 void ParseNodeTransforms(); 1117 void ParseComplexPatterns(); 1118 void ParsePatternFragments(bool OutFrags = false); 1119 void ParseDefaultOperands(); 1120 void ParseInstructions(); 1121 void ParsePatterns(); 1122 void ExpandHwModeBasedTypes(); 1123 void InferInstructionFlags(); 1124 void GenerateVariants(); 1125 void VerifyInstructionFlags(); 1126 1127 std::vector<Predicate> makePredList(ListInit *L); 1128 1129 void AddPatternToMatch(TreePattern *Pattern, PatternToMatch &&PTM); 1130 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat, 1131 std::map<std::string, 1132 TreePatternNode*> &InstInputs, 1133 std::map<std::string, 1134 TreePatternNode*> &InstResults, 1135 std::vector<Record*> &InstImpResults); 1136 }; 1137 1138 1139 inline bool SDNodeInfo::ApplyTypeConstraints(TreePatternNode *N, 1140 TreePattern &TP) const { 1141 bool MadeChange = false; 1142 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) 1143 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP); 1144 return MadeChange; 1145 } 1146 } // end namespace llvm 1147 1148 #endif 1149