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