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