CodeGenDAGPatterns.h 46 KB

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