CodeGenDAGPatterns.h 48 KB

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