/3rd_party/llvm/utils/TableGen/CodeGenDAGPatterns.cpp

https://code.google.com/p/softart/ · C++ · 3598 lines · 2441 code · 551 blank · 606 comment · 992 complexity · 50d18ca4d9763c33a656f73137f5068a MD5 · raw file

Large files are truncated click here to view the full file

  1. //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the CodeGenDAGPatterns class, which is used to read and
  11. // represent the patterns present in a .td file for instructions.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CodeGenDAGPatterns.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Support/Debug.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include "llvm/TableGen/Error.h"
  21. #include "llvm/TableGen/Record.h"
  22. #include <algorithm>
  23. #include <cstdio>
  24. #include <set>
  25. using namespace llvm;
  26. //===----------------------------------------------------------------------===//
  27. // EEVT::TypeSet Implementation
  28. //===----------------------------------------------------------------------===//
  29. static inline bool isInteger(MVT::SimpleValueType VT) {
  30. return MVT(VT).isInteger();
  31. }
  32. static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
  33. return MVT(VT).isFloatingPoint();
  34. }
  35. static inline bool isVector(MVT::SimpleValueType VT) {
  36. return MVT(VT).isVector();
  37. }
  38. static inline bool isScalar(MVT::SimpleValueType VT) {
  39. return !MVT(VT).isVector();
  40. }
  41. EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
  42. if (VT == MVT::iAny)
  43. EnforceInteger(TP);
  44. else if (VT == MVT::fAny)
  45. EnforceFloatingPoint(TP);
  46. else if (VT == MVT::vAny)
  47. EnforceVector(TP);
  48. else {
  49. assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
  50. VT == MVT::iPTRAny) && "Not a concrete type!");
  51. TypeVec.push_back(VT);
  52. }
  53. }
  54. EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
  55. assert(!VTList.empty() && "empty list?");
  56. TypeVec.append(VTList.begin(), VTList.end());
  57. if (!VTList.empty())
  58. assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
  59. VTList[0] != MVT::fAny);
  60. // Verify no duplicates.
  61. array_pod_sort(TypeVec.begin(), TypeVec.end());
  62. assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
  63. }
  64. /// FillWithPossibleTypes - Set to all legal types and return true, only valid
  65. /// on completely unknown type sets.
  66. bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
  67. bool (*Pred)(MVT::SimpleValueType),
  68. const char *PredicateName) {
  69. assert(isCompletelyUnknown());
  70. ArrayRef<MVT::SimpleValueType> LegalTypes =
  71. TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
  72. if (TP.hasError())
  73. return false;
  74. for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
  75. if (Pred == 0 || Pred(LegalTypes[i]))
  76. TypeVec.push_back(LegalTypes[i]);
  77. // If we have nothing that matches the predicate, bail out.
  78. if (TypeVec.empty()) {
  79. TP.error("Type inference contradiction found, no " +
  80. std::string(PredicateName) + " types found");
  81. return false;
  82. }
  83. // No need to sort with one element.
  84. if (TypeVec.size() == 1) return true;
  85. // Remove duplicates.
  86. array_pod_sort(TypeVec.begin(), TypeVec.end());
  87. TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
  88. return true;
  89. }
  90. /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
  91. /// integer value type.
  92. bool EEVT::TypeSet::hasIntegerTypes() const {
  93. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  94. if (isInteger(TypeVec[i]))
  95. return true;
  96. return false;
  97. }
  98. /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
  99. /// a floating point value type.
  100. bool EEVT::TypeSet::hasFloatingPointTypes() const {
  101. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  102. if (isFloatingPoint(TypeVec[i]))
  103. return true;
  104. return false;
  105. }
  106. /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
  107. /// value type.
  108. bool EEVT::TypeSet::hasVectorTypes() const {
  109. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  110. if (isVector(TypeVec[i]))
  111. return true;
  112. return false;
  113. }
  114. std::string EEVT::TypeSet::getName() const {
  115. if (TypeVec.empty()) return "<empty>";
  116. std::string Result;
  117. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
  118. std::string VTName = llvm::getEnumName(TypeVec[i]);
  119. // Strip off MVT:: prefix if present.
  120. if (VTName.substr(0,5) == "MVT::")
  121. VTName = VTName.substr(5);
  122. if (i) Result += ':';
  123. Result += VTName;
  124. }
  125. if (TypeVec.size() == 1)
  126. return Result;
  127. return "{" + Result + "}";
  128. }
  129. /// MergeInTypeInfo - This merges in type information from the specified
  130. /// argument. If 'this' changes, it returns true. If the two types are
  131. /// contradictory (e.g. merge f32 into i32) then this flags an error.
  132. bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
  133. if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
  134. return false;
  135. if (isCompletelyUnknown()) {
  136. *this = InVT;
  137. return true;
  138. }
  139. assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
  140. // Handle the abstract cases, seeing if we can resolve them better.
  141. switch (TypeVec[0]) {
  142. default: break;
  143. case MVT::iPTR:
  144. case MVT::iPTRAny:
  145. if (InVT.hasIntegerTypes()) {
  146. EEVT::TypeSet InCopy(InVT);
  147. InCopy.EnforceInteger(TP);
  148. InCopy.EnforceScalar(TP);
  149. if (InCopy.isConcrete()) {
  150. // If the RHS has one integer type, upgrade iPTR to i32.
  151. TypeVec[0] = InVT.TypeVec[0];
  152. return true;
  153. }
  154. // If the input has multiple scalar integers, this doesn't add any info.
  155. if (!InCopy.isCompletelyUnknown())
  156. return false;
  157. }
  158. break;
  159. }
  160. // If the input constraint is iAny/iPTR and this is an integer type list,
  161. // remove non-integer types from the list.
  162. if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
  163. hasIntegerTypes()) {
  164. bool MadeChange = EnforceInteger(TP);
  165. // If we're merging in iPTR/iPTRAny and the node currently has a list of
  166. // multiple different integer types, replace them with a single iPTR.
  167. if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
  168. TypeVec.size() != 1) {
  169. TypeVec.resize(1);
  170. TypeVec[0] = InVT.TypeVec[0];
  171. MadeChange = true;
  172. }
  173. return MadeChange;
  174. }
  175. // If this is a type list and the RHS is a typelist as well, eliminate entries
  176. // from this list that aren't in the other one.
  177. bool MadeChange = false;
  178. TypeSet InputSet(*this);
  179. for (unsigned i = 0; i != TypeVec.size(); ++i) {
  180. bool InInVT = false;
  181. for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
  182. if (TypeVec[i] == InVT.TypeVec[j]) {
  183. InInVT = true;
  184. break;
  185. }
  186. if (InInVT) continue;
  187. TypeVec.erase(TypeVec.begin()+i--);
  188. MadeChange = true;
  189. }
  190. // If we removed all of our types, we have a type contradiction.
  191. if (!TypeVec.empty())
  192. return MadeChange;
  193. // FIXME: Really want an SMLoc here!
  194. TP.error("Type inference contradiction found, merging '" +
  195. InVT.getName() + "' into '" + InputSet.getName() + "'");
  196. return false;
  197. }
  198. /// EnforceInteger - Remove all non-integer types from this set.
  199. bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
  200. if (TP.hasError())
  201. return false;
  202. // If we know nothing, then get the full set.
  203. if (TypeVec.empty())
  204. return FillWithPossibleTypes(TP, isInteger, "integer");
  205. if (!hasFloatingPointTypes())
  206. return false;
  207. TypeSet InputSet(*this);
  208. // Filter out all the fp types.
  209. for (unsigned i = 0; i != TypeVec.size(); ++i)
  210. if (!isInteger(TypeVec[i]))
  211. TypeVec.erase(TypeVec.begin()+i--);
  212. if (TypeVec.empty()) {
  213. TP.error("Type inference contradiction found, '" +
  214. InputSet.getName() + "' needs to be integer");
  215. return false;
  216. }
  217. return true;
  218. }
  219. /// EnforceFloatingPoint - Remove all integer types from this set.
  220. bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
  221. if (TP.hasError())
  222. return false;
  223. // If we know nothing, then get the full set.
  224. if (TypeVec.empty())
  225. return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
  226. if (!hasIntegerTypes())
  227. return false;
  228. TypeSet InputSet(*this);
  229. // Filter out all the fp types.
  230. for (unsigned i = 0; i != TypeVec.size(); ++i)
  231. if (!isFloatingPoint(TypeVec[i]))
  232. TypeVec.erase(TypeVec.begin()+i--);
  233. if (TypeVec.empty()) {
  234. TP.error("Type inference contradiction found, '" +
  235. InputSet.getName() + "' needs to be floating point");
  236. return false;
  237. }
  238. return true;
  239. }
  240. /// EnforceScalar - Remove all vector types from this.
  241. bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
  242. if (TP.hasError())
  243. return false;
  244. // If we know nothing, then get the full set.
  245. if (TypeVec.empty())
  246. return FillWithPossibleTypes(TP, isScalar, "scalar");
  247. if (!hasVectorTypes())
  248. return false;
  249. TypeSet InputSet(*this);
  250. // Filter out all the vector types.
  251. for (unsigned i = 0; i != TypeVec.size(); ++i)
  252. if (!isScalar(TypeVec[i]))
  253. TypeVec.erase(TypeVec.begin()+i--);
  254. if (TypeVec.empty()) {
  255. TP.error("Type inference contradiction found, '" +
  256. InputSet.getName() + "' needs to be scalar");
  257. return false;
  258. }
  259. return true;
  260. }
  261. /// EnforceVector - Remove all vector types from this.
  262. bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
  263. if (TP.hasError())
  264. return false;
  265. // If we know nothing, then get the full set.
  266. if (TypeVec.empty())
  267. return FillWithPossibleTypes(TP, isVector, "vector");
  268. TypeSet InputSet(*this);
  269. bool MadeChange = false;
  270. // Filter out all the scalar types.
  271. for (unsigned i = 0; i != TypeVec.size(); ++i)
  272. if (!isVector(TypeVec[i])) {
  273. TypeVec.erase(TypeVec.begin()+i--);
  274. MadeChange = true;
  275. }
  276. if (TypeVec.empty()) {
  277. TP.error("Type inference contradiction found, '" +
  278. InputSet.getName() + "' needs to be a vector");
  279. return false;
  280. }
  281. return MadeChange;
  282. }
  283. /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
  284. /// this an other based on this information.
  285. bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
  286. if (TP.hasError())
  287. return false;
  288. // Both operands must be integer or FP, but we don't care which.
  289. bool MadeChange = false;
  290. if (isCompletelyUnknown())
  291. MadeChange = FillWithPossibleTypes(TP);
  292. if (Other.isCompletelyUnknown())
  293. MadeChange = Other.FillWithPossibleTypes(TP);
  294. // If one side is known to be integer or known to be FP but the other side has
  295. // no information, get at least the type integrality info in there.
  296. if (!hasFloatingPointTypes())
  297. MadeChange |= Other.EnforceInteger(TP);
  298. else if (!hasIntegerTypes())
  299. MadeChange |= Other.EnforceFloatingPoint(TP);
  300. if (!Other.hasFloatingPointTypes())
  301. MadeChange |= EnforceInteger(TP);
  302. else if (!Other.hasIntegerTypes())
  303. MadeChange |= EnforceFloatingPoint(TP);
  304. assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
  305. "Should have a type list now");
  306. // If one contains vectors but the other doesn't pull vectors out.
  307. if (!hasVectorTypes())
  308. MadeChange |= Other.EnforceScalar(TP);
  309. if (!hasVectorTypes())
  310. MadeChange |= EnforceScalar(TP);
  311. if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
  312. // If we are down to concrete types, this code does not currently
  313. // handle nodes which have multiple types, where some types are
  314. // integer, and some are fp. Assert that this is not the case.
  315. assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
  316. !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
  317. "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
  318. // Otherwise, if these are both vector types, either this vector
  319. // must have a larger bitsize than the other, or this element type
  320. // must be larger than the other.
  321. MVT Type(TypeVec[0]);
  322. MVT OtherType(Other.TypeVec[0]);
  323. if (hasVectorTypes() && Other.hasVectorTypes()) {
  324. if (Type.getSizeInBits() >= OtherType.getSizeInBits())
  325. if (Type.getVectorElementType().getSizeInBits()
  326. >= OtherType.getVectorElementType().getSizeInBits()) {
  327. TP.error("Type inference contradiction found, '" +
  328. getName() + "' element type not smaller than '" +
  329. Other.getName() +"'!");
  330. return false;
  331. }
  332. } else
  333. // For scalar types, the bitsize of this type must be larger
  334. // than that of the other.
  335. if (Type.getSizeInBits() >= OtherType.getSizeInBits()) {
  336. TP.error("Type inference contradiction found, '" +
  337. getName() + "' is not smaller than '" +
  338. Other.getName() +"'!");
  339. return false;
  340. }
  341. }
  342. // Handle int and fp as disjoint sets. This won't work for patterns
  343. // that have mixed fp/int types but those are likely rare and would
  344. // not have been accepted by this code previously.
  345. // Okay, find the smallest type from the current set and remove it from the
  346. // largest set.
  347. MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
  348. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  349. if (isInteger(TypeVec[i])) {
  350. SmallestInt = TypeVec[i];
  351. break;
  352. }
  353. for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
  354. if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
  355. SmallestInt = TypeVec[i];
  356. MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
  357. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  358. if (isFloatingPoint(TypeVec[i])) {
  359. SmallestFP = TypeVec[i];
  360. break;
  361. }
  362. for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
  363. if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
  364. SmallestFP = TypeVec[i];
  365. int OtherIntSize = 0;
  366. int OtherFPSize = 0;
  367. for (SmallVectorImpl<MVT::SimpleValueType>::iterator TVI =
  368. Other.TypeVec.begin();
  369. TVI != Other.TypeVec.end();
  370. /* NULL */) {
  371. if (isInteger(*TVI)) {
  372. ++OtherIntSize;
  373. if (*TVI == SmallestInt) {
  374. TVI = Other.TypeVec.erase(TVI);
  375. --OtherIntSize;
  376. MadeChange = true;
  377. continue;
  378. }
  379. } else if (isFloatingPoint(*TVI)) {
  380. ++OtherFPSize;
  381. if (*TVI == SmallestFP) {
  382. TVI = Other.TypeVec.erase(TVI);
  383. --OtherFPSize;
  384. MadeChange = true;
  385. continue;
  386. }
  387. }
  388. ++TVI;
  389. }
  390. // If this is the only type in the large set, the constraint can never be
  391. // satisfied.
  392. if ((Other.hasIntegerTypes() && OtherIntSize == 0) ||
  393. (Other.hasFloatingPointTypes() && OtherFPSize == 0)) {
  394. TP.error("Type inference contradiction found, '" +
  395. Other.getName() + "' has nothing larger than '" + getName() +"'!");
  396. return false;
  397. }
  398. // Okay, find the largest type in the Other set and remove it from the
  399. // current set.
  400. MVT::SimpleValueType LargestInt = MVT::Other;
  401. for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
  402. if (isInteger(Other.TypeVec[i])) {
  403. LargestInt = Other.TypeVec[i];
  404. break;
  405. }
  406. for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
  407. if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
  408. LargestInt = Other.TypeVec[i];
  409. MVT::SimpleValueType LargestFP = MVT::Other;
  410. for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
  411. if (isFloatingPoint(Other.TypeVec[i])) {
  412. LargestFP = Other.TypeVec[i];
  413. break;
  414. }
  415. for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
  416. if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
  417. LargestFP = Other.TypeVec[i];
  418. int IntSize = 0;
  419. int FPSize = 0;
  420. for (SmallVectorImpl<MVT::SimpleValueType>::iterator TVI =
  421. TypeVec.begin();
  422. TVI != TypeVec.end();
  423. /* NULL */) {
  424. if (isInteger(*TVI)) {
  425. ++IntSize;
  426. if (*TVI == LargestInt) {
  427. TVI = TypeVec.erase(TVI);
  428. --IntSize;
  429. MadeChange = true;
  430. continue;
  431. }
  432. } else if (isFloatingPoint(*TVI)) {
  433. ++FPSize;
  434. if (*TVI == LargestFP) {
  435. TVI = TypeVec.erase(TVI);
  436. --FPSize;
  437. MadeChange = true;
  438. continue;
  439. }
  440. }
  441. ++TVI;
  442. }
  443. // If this is the only type in the small set, the constraint can never be
  444. // satisfied.
  445. if ((hasIntegerTypes() && IntSize == 0) ||
  446. (hasFloatingPointTypes() && FPSize == 0)) {
  447. TP.error("Type inference contradiction found, '" +
  448. getName() + "' has nothing smaller than '" + Other.getName()+"'!");
  449. return false;
  450. }
  451. return MadeChange;
  452. }
  453. /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
  454. /// whose element is specified by VTOperand.
  455. bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
  456. TreePattern &TP) {
  457. if (TP.hasError())
  458. return false;
  459. // "This" must be a vector and "VTOperand" must be a scalar.
  460. bool MadeChange = false;
  461. MadeChange |= EnforceVector(TP);
  462. MadeChange |= VTOperand.EnforceScalar(TP);
  463. // If we know the vector type, it forces the scalar to agree.
  464. if (isConcrete()) {
  465. MVT IVT = getConcrete();
  466. IVT = IVT.getVectorElementType();
  467. return MadeChange |
  468. VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
  469. }
  470. // If the scalar type is known, filter out vector types whose element types
  471. // disagree.
  472. if (!VTOperand.isConcrete())
  473. return MadeChange;
  474. MVT::SimpleValueType VT = VTOperand.getConcrete();
  475. TypeSet InputSet(*this);
  476. // Filter out all the types which don't have the right element type.
  477. for (unsigned i = 0; i != TypeVec.size(); ++i) {
  478. assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
  479. if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
  480. TypeVec.erase(TypeVec.begin()+i--);
  481. MadeChange = true;
  482. }
  483. }
  484. if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
  485. TP.error("Type inference contradiction found, forcing '" +
  486. InputSet.getName() + "' to have a vector element");
  487. return false;
  488. }
  489. return MadeChange;
  490. }
  491. /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
  492. /// vector type specified by VTOperand.
  493. bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
  494. TreePattern &TP) {
  495. // "This" must be a vector and "VTOperand" must be a vector.
  496. bool MadeChange = false;
  497. MadeChange |= EnforceVector(TP);
  498. MadeChange |= VTOperand.EnforceVector(TP);
  499. // "This" must be larger than "VTOperand."
  500. MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
  501. // If we know the vector type, it forces the scalar types to agree.
  502. if (isConcrete()) {
  503. MVT IVT = getConcrete();
  504. IVT = IVT.getVectorElementType();
  505. EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
  506. MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
  507. } else if (VTOperand.isConcrete()) {
  508. MVT IVT = VTOperand.getConcrete();
  509. IVT = IVT.getVectorElementType();
  510. EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
  511. MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
  512. }
  513. return MadeChange;
  514. }
  515. //===----------------------------------------------------------------------===//
  516. // Helpers for working with extended types.
  517. /// Dependent variable map for CodeGenDAGPattern variant generation
  518. typedef std::map<std::string, int> DepVarMap;
  519. /// Const iterator shorthand for DepVarMap
  520. typedef DepVarMap::const_iterator DepVarMap_citer;
  521. static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
  522. if (N->isLeaf()) {
  523. if (isa<DefInit>(N->getLeafValue()))
  524. DepMap[N->getName()]++;
  525. } else {
  526. for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
  527. FindDepVarsOf(N->getChild(i), DepMap);
  528. }
  529. }
  530. /// Find dependent variables within child patterns
  531. static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
  532. DepVarMap depcounts;
  533. FindDepVarsOf(N, depcounts);
  534. for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
  535. if (i->second > 1) // std::pair<std::string, int>
  536. DepVars.insert(i->first);
  537. }
  538. }
  539. #ifndef NDEBUG
  540. /// Dump the dependent variable set:
  541. static void DumpDepVars(MultipleUseVarSet &DepVars) {
  542. if (DepVars.empty()) {
  543. DEBUG(errs() << "<empty set>");
  544. } else {
  545. DEBUG(errs() << "[ ");
  546. for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
  547. e = DepVars.end(); i != e; ++i) {
  548. DEBUG(errs() << (*i) << " ");
  549. }
  550. DEBUG(errs() << "]");
  551. }
  552. }
  553. #endif
  554. //===----------------------------------------------------------------------===//
  555. // TreePredicateFn Implementation
  556. //===----------------------------------------------------------------------===//
  557. /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
  558. TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
  559. assert((getPredCode().empty() || getImmCode().empty()) &&
  560. ".td file corrupt: can't have a node predicate *and* an imm predicate");
  561. }
  562. std::string TreePredicateFn::getPredCode() const {
  563. return PatFragRec->getRecord()->getValueAsString("PredicateCode");
  564. }
  565. std::string TreePredicateFn::getImmCode() const {
  566. return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
  567. }
  568. /// isAlwaysTrue - Return true if this is a noop predicate.
  569. bool TreePredicateFn::isAlwaysTrue() const {
  570. return getPredCode().empty() && getImmCode().empty();
  571. }
  572. /// Return the name to use in the generated code to reference this, this is
  573. /// "Predicate_foo" if from a pattern fragment "foo".
  574. std::string TreePredicateFn::getFnName() const {
  575. return "Predicate_" + PatFragRec->getRecord()->getName();
  576. }
  577. /// getCodeToRunOnSDNode - Return the code for the function body that
  578. /// evaluates this predicate. The argument is expected to be in "Node",
  579. /// not N. This handles casting and conversion to a concrete node type as
  580. /// appropriate.
  581. std::string TreePredicateFn::getCodeToRunOnSDNode() const {
  582. // Handle immediate predicates first.
  583. std::string ImmCode = getImmCode();
  584. if (!ImmCode.empty()) {
  585. std::string Result =
  586. " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
  587. return Result + ImmCode;
  588. }
  589. // Handle arbitrary node predicates.
  590. assert(!getPredCode().empty() && "Don't have any predicate code!");
  591. std::string ClassName;
  592. if (PatFragRec->getOnlyTree()->isLeaf())
  593. ClassName = "SDNode";
  594. else {
  595. Record *Op = PatFragRec->getOnlyTree()->getOperator();
  596. ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
  597. }
  598. std::string Result;
  599. if (ClassName == "SDNode")
  600. Result = " SDNode *N = Node;\n";
  601. else
  602. Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
  603. return Result + getPredCode();
  604. }
  605. //===----------------------------------------------------------------------===//
  606. // PatternToMatch implementation
  607. //
  608. /// getPatternSize - Return the 'size' of this pattern. We want to match large
  609. /// patterns before small ones. This is used to determine the size of a
  610. /// pattern.
  611. static unsigned getPatternSize(const TreePatternNode *P,
  612. const CodeGenDAGPatterns &CGP) {
  613. unsigned Size = 3; // The node itself.
  614. // If the root node is a ConstantSDNode, increases its size.
  615. // e.g. (set R32:$dst, 0).
  616. if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
  617. Size += 2;
  618. // FIXME: This is a hack to statically increase the priority of patterns
  619. // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
  620. // Later we can allow complexity / cost for each pattern to be (optionally)
  621. // specified. To get best possible pattern match we'll need to dynamically
  622. // calculate the complexity of all patterns a dag can potentially map to.
  623. const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
  624. if (AM)
  625. Size += AM->getNumOperands() * 3;
  626. // If this node has some predicate function that must match, it adds to the
  627. // complexity of this node.
  628. if (!P->getPredicateFns().empty())
  629. ++Size;
  630. // Count children in the count if they are also nodes.
  631. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
  632. TreePatternNode *Child = P->getChild(i);
  633. if (!Child->isLeaf() && Child->getNumTypes() &&
  634. Child->getType(0) != MVT::Other)
  635. Size += getPatternSize(Child, CGP);
  636. else if (Child->isLeaf()) {
  637. if (isa<IntInit>(Child->getLeafValue()))
  638. Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
  639. else if (Child->getComplexPatternInfo(CGP))
  640. Size += getPatternSize(Child, CGP);
  641. else if (!Child->getPredicateFns().empty())
  642. ++Size;
  643. }
  644. }
  645. return Size;
  646. }
  647. /// Compute the complexity metric for the input pattern. This roughly
  648. /// corresponds to the number of nodes that are covered.
  649. unsigned PatternToMatch::
  650. getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
  651. return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
  652. }
  653. /// getPredicateCheck - Return a single string containing all of this
  654. /// pattern's predicates concatenated with "&&" operators.
  655. ///
  656. std::string PatternToMatch::getPredicateCheck() const {
  657. std::string PredicateCheck;
  658. for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
  659. if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
  660. Record *Def = Pred->getDef();
  661. if (!Def->isSubClassOf("Predicate")) {
  662. #ifndef NDEBUG
  663. Def->dump();
  664. #endif
  665. llvm_unreachable("Unknown predicate type!");
  666. }
  667. if (!PredicateCheck.empty())
  668. PredicateCheck += " && ";
  669. PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
  670. }
  671. }
  672. return PredicateCheck;
  673. }
  674. //===----------------------------------------------------------------------===//
  675. // SDTypeConstraint implementation
  676. //
  677. SDTypeConstraint::SDTypeConstraint(Record *R) {
  678. OperandNo = R->getValueAsInt("OperandNum");
  679. if (R->isSubClassOf("SDTCisVT")) {
  680. ConstraintType = SDTCisVT;
  681. x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
  682. if (x.SDTCisVT_Info.VT == MVT::isVoid)
  683. PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
  684. } else if (R->isSubClassOf("SDTCisPtrTy")) {
  685. ConstraintType = SDTCisPtrTy;
  686. } else if (R->isSubClassOf("SDTCisInt")) {
  687. ConstraintType = SDTCisInt;
  688. } else if (R->isSubClassOf("SDTCisFP")) {
  689. ConstraintType = SDTCisFP;
  690. } else if (R->isSubClassOf("SDTCisVec")) {
  691. ConstraintType = SDTCisVec;
  692. } else if (R->isSubClassOf("SDTCisSameAs")) {
  693. ConstraintType = SDTCisSameAs;
  694. x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
  695. } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
  696. ConstraintType = SDTCisVTSmallerThanOp;
  697. x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
  698. R->getValueAsInt("OtherOperandNum");
  699. } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
  700. ConstraintType = SDTCisOpSmallerThanOp;
  701. x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
  702. R->getValueAsInt("BigOperandNum");
  703. } else if (R->isSubClassOf("SDTCisEltOfVec")) {
  704. ConstraintType = SDTCisEltOfVec;
  705. x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
  706. } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
  707. ConstraintType = SDTCisSubVecOfVec;
  708. x.SDTCisSubVecOfVec_Info.OtherOperandNum =
  709. R->getValueAsInt("OtherOpNum");
  710. } else {
  711. errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
  712. exit(1);
  713. }
  714. }
  715. /// getOperandNum - Return the node corresponding to operand #OpNo in tree
  716. /// N, and the result number in ResNo.
  717. static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
  718. const SDNodeInfo &NodeInfo,
  719. unsigned &ResNo) {
  720. unsigned NumResults = NodeInfo.getNumResults();
  721. if (OpNo < NumResults) {
  722. ResNo = OpNo;
  723. return N;
  724. }
  725. OpNo -= NumResults;
  726. if (OpNo >= N->getNumChildren()) {
  727. errs() << "Invalid operand number in type constraint "
  728. << (OpNo+NumResults) << " ";
  729. N->dump();
  730. errs() << '\n';
  731. exit(1);
  732. }
  733. return N->getChild(OpNo);
  734. }
  735. /// ApplyTypeConstraint - Given a node in a pattern, apply this type
  736. /// constraint to the nodes operands. This returns true if it makes a
  737. /// change, false otherwise. If a type contradiction is found, flag an error.
  738. bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
  739. const SDNodeInfo &NodeInfo,
  740. TreePattern &TP) const {
  741. if (TP.hasError())
  742. return false;
  743. unsigned ResNo = 0; // The result number being referenced.
  744. TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
  745. switch (ConstraintType) {
  746. case SDTCisVT:
  747. // Operand must be a particular type.
  748. return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
  749. case SDTCisPtrTy:
  750. // Operand must be same as target pointer type.
  751. return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
  752. case SDTCisInt:
  753. // Require it to be one of the legal integer VTs.
  754. return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
  755. case SDTCisFP:
  756. // Require it to be one of the legal fp VTs.
  757. return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
  758. case SDTCisVec:
  759. // Require it to be one of the legal vector VTs.
  760. return NodeToApply->getExtType(ResNo).EnforceVector(TP);
  761. case SDTCisSameAs: {
  762. unsigned OResNo = 0;
  763. TreePatternNode *OtherNode =
  764. getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
  765. return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
  766. OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
  767. }
  768. case SDTCisVTSmallerThanOp: {
  769. // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
  770. // have an integer type that is smaller than the VT.
  771. if (!NodeToApply->isLeaf() ||
  772. !isa<DefInit>(NodeToApply->getLeafValue()) ||
  773. !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
  774. ->isSubClassOf("ValueType")) {
  775. TP.error(N->getOperator()->getName() + " expects a VT operand!");
  776. return false;
  777. }
  778. MVT::SimpleValueType VT =
  779. getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
  780. EEVT::TypeSet TypeListTmp(VT, TP);
  781. unsigned OResNo = 0;
  782. TreePatternNode *OtherNode =
  783. getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
  784. OResNo);
  785. return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
  786. }
  787. case SDTCisOpSmallerThanOp: {
  788. unsigned BResNo = 0;
  789. TreePatternNode *BigOperand =
  790. getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
  791. BResNo);
  792. return NodeToApply->getExtType(ResNo).
  793. EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
  794. }
  795. case SDTCisEltOfVec: {
  796. unsigned VResNo = 0;
  797. TreePatternNode *VecOperand =
  798. getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
  799. VResNo);
  800. // Filter vector types out of VecOperand that don't have the right element
  801. // type.
  802. return VecOperand->getExtType(VResNo).
  803. EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
  804. }
  805. case SDTCisSubVecOfVec: {
  806. unsigned VResNo = 0;
  807. TreePatternNode *BigVecOperand =
  808. getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
  809. VResNo);
  810. // Filter vector types out of BigVecOperand that don't have the
  811. // right subvector type.
  812. return BigVecOperand->getExtType(VResNo).
  813. EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
  814. }
  815. }
  816. llvm_unreachable("Invalid ConstraintType!");
  817. }
  818. // Update the node type to match an instruction operand or result as specified
  819. // in the ins or outs lists on the instruction definition. Return true if the
  820. // type was actually changed.
  821. bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
  822. Record *Operand,
  823. TreePattern &TP) {
  824. // The 'unknown' operand indicates that types should be inferred from the
  825. // context.
  826. if (Operand->isSubClassOf("unknown_class"))
  827. return false;
  828. // The Operand class specifies a type directly.
  829. if (Operand->isSubClassOf("Operand"))
  830. return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
  831. TP);
  832. // PointerLikeRegClass has a type that is determined at runtime.
  833. if (Operand->isSubClassOf("PointerLikeRegClass"))
  834. return UpdateNodeType(ResNo, MVT::iPTR, TP);
  835. // Both RegisterClass and RegisterOperand operands derive their types from a
  836. // register class def.
  837. Record *RC = 0;
  838. if (Operand->isSubClassOf("RegisterClass"))
  839. RC = Operand;
  840. else if (Operand->isSubClassOf("RegisterOperand"))
  841. RC = Operand->getValueAsDef("RegClass");
  842. assert(RC && "Unknown operand type");
  843. CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
  844. return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
  845. }
  846. //===----------------------------------------------------------------------===//
  847. // SDNodeInfo implementation
  848. //
  849. SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
  850. EnumName = R->getValueAsString("Opcode");
  851. SDClassName = R->getValueAsString("SDClass");
  852. Record *TypeProfile = R->getValueAsDef("TypeProfile");
  853. NumResults = TypeProfile->getValueAsInt("NumResults");
  854. NumOperands = TypeProfile->getValueAsInt("NumOperands");
  855. // Parse the properties.
  856. Properties = 0;
  857. std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
  858. for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
  859. if (PropList[i]->getName() == "SDNPCommutative") {
  860. Properties |= 1 << SDNPCommutative;
  861. } else if (PropList[i]->getName() == "SDNPAssociative") {
  862. Properties |= 1 << SDNPAssociative;
  863. } else if (PropList[i]->getName() == "SDNPHasChain") {
  864. Properties |= 1 << SDNPHasChain;
  865. } else if (PropList[i]->getName() == "SDNPOutGlue") {
  866. Properties |= 1 << SDNPOutGlue;
  867. } else if (PropList[i]->getName() == "SDNPInGlue") {
  868. Properties |= 1 << SDNPInGlue;
  869. } else if (PropList[i]->getName() == "SDNPOptInGlue") {
  870. Properties |= 1 << SDNPOptInGlue;
  871. } else if (PropList[i]->getName() == "SDNPMayStore") {
  872. Properties |= 1 << SDNPMayStore;
  873. } else if (PropList[i]->getName() == "SDNPMayLoad") {
  874. Properties |= 1 << SDNPMayLoad;
  875. } else if (PropList[i]->getName() == "SDNPSideEffect") {
  876. Properties |= 1 << SDNPSideEffect;
  877. } else if (PropList[i]->getName() == "SDNPMemOperand") {
  878. Properties |= 1 << SDNPMemOperand;
  879. } else if (PropList[i]->getName() == "SDNPVariadic") {
  880. Properties |= 1 << SDNPVariadic;
  881. } else {
  882. errs() << "Unknown SD Node property '" << PropList[i]->getName()
  883. << "' on node '" << R->getName() << "'!\n";
  884. exit(1);
  885. }
  886. }
  887. // Parse the type constraints.
  888. std::vector<Record*> ConstraintList =
  889. TypeProfile->getValueAsListOfDefs("Constraints");
  890. TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
  891. }
  892. /// getKnownType - If the type constraints on this node imply a fixed type
  893. /// (e.g. all stores return void, etc), then return it as an
  894. /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
  895. MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
  896. unsigned NumResults = getNumResults();
  897. assert(NumResults <= 1 &&
  898. "We only work with nodes with zero or one result so far!");
  899. assert(ResNo == 0 && "Only handles single result nodes so far");
  900. for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
  901. // Make sure that this applies to the correct node result.
  902. if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
  903. continue;
  904. switch (TypeConstraints[i].ConstraintType) {
  905. default: break;
  906. case SDTypeConstraint::SDTCisVT:
  907. return TypeConstraints[i].x.SDTCisVT_Info.VT;
  908. case SDTypeConstraint::SDTCisPtrTy:
  909. return MVT::iPTR;
  910. }
  911. }
  912. return MVT::Other;
  913. }
  914. //===----------------------------------------------------------------------===//
  915. // TreePatternNode implementation
  916. //
  917. TreePatternNode::~TreePatternNode() {
  918. #if 0 // FIXME: implement refcounted tree nodes!
  919. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  920. delete getChild(i);
  921. #endif
  922. }
  923. static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
  924. if (Operator->getName() == "set" ||
  925. Operator->getName() == "implicit")
  926. return 0; // All return nothing.
  927. if (Operator->isSubClassOf("Intrinsic"))
  928. return CDP.getIntrinsic(Operator).IS.RetVTs.size();
  929. if (Operator->isSubClassOf("SDNode"))
  930. return CDP.getSDNodeInfo(Operator).getNumResults();
  931. if (Operator->isSubClassOf("PatFrag")) {
  932. // If we've already parsed this pattern fragment, get it. Otherwise, handle
  933. // the forward reference case where one pattern fragment references another
  934. // before it is processed.
  935. if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
  936. return PFRec->getOnlyTree()->getNumTypes();
  937. // Get the result tree.
  938. DagInit *Tree = Operator->getValueAsDag("Fragment");
  939. Record *Op = 0;
  940. if (Tree)
  941. if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
  942. Op = DI->getDef();
  943. assert(Op && "Invalid Fragment");
  944. return GetNumNodeResults(Op, CDP);
  945. }
  946. if (Operator->isSubClassOf("Instruction")) {
  947. CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
  948. // FIXME: Should allow access to all the results here.
  949. unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
  950. // Add on one implicit def if it has a resolvable type.
  951. if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
  952. ++NumDefsToAdd;
  953. return NumDefsToAdd;
  954. }
  955. if (Operator->isSubClassOf("SDNodeXForm"))
  956. return 1; // FIXME: Generalize SDNodeXForm
  957. Operator->dump();
  958. errs() << "Unhandled node in GetNumNodeResults\n";
  959. exit(1);
  960. }
  961. void TreePatternNode::print(raw_ostream &OS) const {
  962. if (isLeaf())
  963. OS << *getLeafValue();
  964. else
  965. OS << '(' << getOperator()->getName();
  966. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  967. OS << ':' << getExtType(i).getName();
  968. if (!isLeaf()) {
  969. if (getNumChildren() != 0) {
  970. OS << " ";
  971. getChild(0)->print(OS);
  972. for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
  973. OS << ", ";
  974. getChild(i)->print(OS);
  975. }
  976. }
  977. OS << ")";
  978. }
  979. for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
  980. OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
  981. if (TransformFn)
  982. OS << "<<X:" << TransformFn->getName() << ">>";
  983. if (!getName().empty())
  984. OS << ":$" << getName();
  985. }
  986. void TreePatternNode::dump() const {
  987. print(errs());
  988. }
  989. /// isIsomorphicTo - Return true if this node is recursively
  990. /// isomorphic to the specified node. For this comparison, the node's
  991. /// entire state is considered. The assigned name is ignored, since
  992. /// nodes with differing names are considered isomorphic. However, if
  993. /// the assigned name is present in the dependent variable set, then
  994. /// the assigned name is considered significant and the node is
  995. /// isomorphic if the names match.
  996. bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
  997. const MultipleUseVarSet &DepVars) const {
  998. if (N == this) return true;
  999. if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
  1000. getPredicateFns() != N->getPredicateFns() ||
  1001. getTransformFn() != N->getTransformFn())
  1002. return false;
  1003. if (isLeaf()) {
  1004. if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
  1005. if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
  1006. return ((DI->getDef() == NDI->getDef())
  1007. && (DepVars.find(getName()) == DepVars.end()
  1008. || getName() == N->getName()));
  1009. }
  1010. }
  1011. return getLeafValue() == N->getLeafValue();
  1012. }
  1013. if (N->getOperator() != getOperator() ||
  1014. N->getNumChildren() != getNumChildren()) return false;
  1015. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1016. if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
  1017. return false;
  1018. return true;
  1019. }
  1020. /// clone - Make a copy of this tree and all of its children.
  1021. ///
  1022. TreePatternNode *TreePatternNode::clone() const {
  1023. TreePatternNode *New;
  1024. if (isLeaf()) {
  1025. New = new TreePatternNode(getLeafValue(), getNumTypes());
  1026. } else {
  1027. std::vector<TreePatternNode*> CChildren;
  1028. CChildren.reserve(Children.size());
  1029. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1030. CChildren.push_back(getChild(i)->clone());
  1031. New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
  1032. }
  1033. New->setName(getName());
  1034. New->Types = Types;
  1035. New->setPredicateFns(getPredicateFns());
  1036. New->setTransformFn(getTransformFn());
  1037. return New;
  1038. }
  1039. /// RemoveAllTypes - Recursively strip all the types of this tree.
  1040. void TreePatternNode::RemoveAllTypes() {
  1041. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1042. Types[i] = EEVT::TypeSet(); // Reset to unknown type.
  1043. if (isLeaf()) return;
  1044. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1045. getChild(i)->RemoveAllTypes();
  1046. }
  1047. /// SubstituteFormalArguments - Replace the formal arguments in this tree
  1048. /// with actual values specified by ArgMap.
  1049. void TreePatternNode::
  1050. SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
  1051. if (isLeaf()) return;
  1052. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1053. TreePatternNode *Child = getChild(i);
  1054. if (Child->isLeaf()) {
  1055. Init *Val = Child->getLeafValue();
  1056. if (isa<DefInit>(Val) &&
  1057. cast<DefInit>(Val)->getDef()->getName() == "node") {
  1058. // We found a use of a formal argument, replace it with its value.
  1059. TreePatternNode *NewChild = ArgMap[Child->getName()];
  1060. assert(NewChild && "Couldn't find formal argument!");
  1061. assert((Child->getPredicateFns().empty() ||
  1062. NewChild->getPredicateFns() == Child->getPredicateFns()) &&
  1063. "Non-empty child predicate clobbered!");
  1064. setChild(i, NewChild);
  1065. }
  1066. } else {
  1067. getChild(i)->SubstituteFormalArguments(ArgMap);
  1068. }
  1069. }
  1070. }
  1071. /// InlinePatternFragments - If this pattern refers to any pattern
  1072. /// fragments, inline them into place, giving us a pattern without any
  1073. /// PatFrag references.
  1074. TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
  1075. if (TP.hasError())
  1076. return 0;
  1077. if (isLeaf())
  1078. return this; // nothing to do.
  1079. Record *Op = getOperator();
  1080. if (!Op->isSubClassOf("PatFrag")) {
  1081. // Just recursively inline children nodes.
  1082. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1083. TreePatternNode *Child = getChild(i);
  1084. TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
  1085. assert((Child->getPredicateFns().empty() ||
  1086. NewChild->getPredicateFns() == Child->getPredicateFns()) &&
  1087. "Non-empty child predicate clobbered!");
  1088. setChild(i, NewChild);
  1089. }
  1090. return this;
  1091. }
  1092. // Otherwise, we found a reference to a fragment. First, look up its
  1093. // TreePattern record.
  1094. TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
  1095. // Verify that we are passing the right number of operands.
  1096. if (Frag->getNumArgs() != Children.size()) {
  1097. TP.error("'" + Op->getName() + "' fragment requires " +
  1098. utostr(Frag->getNumArgs()) + " operands!");
  1099. return 0;
  1100. }
  1101. TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
  1102. TreePredicateFn PredFn(Frag);
  1103. if (!PredFn.isAlwaysTrue())
  1104. FragTree->addPredicateFn(PredFn);
  1105. // Resolve formal arguments to their actual value.
  1106. if (Frag->getNumArgs()) {
  1107. // Compute the map of formal to actual arguments.
  1108. std::map<std::string, TreePatternNode*> ArgMap;
  1109. for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
  1110. ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
  1111. FragTree->SubstituteFormalArguments(ArgMap);
  1112. }
  1113. FragTree->setName(getName());
  1114. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1115. FragTree->UpdateNodeType(i, getExtType(i), TP);
  1116. // Transfer in the old predicates.
  1117. for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
  1118. FragTree->addPredicateFn(getPredicateFns()[i]);
  1119. // Get a new copy of this fragment to stitch into here.
  1120. //delete this; // FIXME: implement refcounting!
  1121. // The fragment we inlined could have recursive inlining that is needed. See
  1122. // if there are any pattern fragments in it and inline them as needed.
  1123. return FragTree->InlinePatternFragments(TP);
  1124. }
  1125. /// getImplicitType - Check to see if the specified record has an implicit
  1126. /// type which should be applied to it. This will infer the type of register
  1127. /// references from the register file information, for example.
  1128. ///
  1129. /// When Unnamed is set, return the type of a DAG operand with no name, such as
  1130. /// the F8RC register class argument in:
  1131. ///
  1132. /// (COPY_TO_REGCLASS GPR:$src, F8RC)
  1133. ///
  1134. /// When Unnamed is false, return the type of a named DAG operand such as the
  1135. /// GPR:$src operand above.
  1136. ///
  1137. static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
  1138. bool NotRegisters,
  1139. bool Unnamed,
  1140. TreePattern &TP) {
  1141. // Check to see if this is a register operand.
  1142. if (R->isSubClassOf("RegisterOperand")) {
  1143. assert(ResNo == 0 && "Regoperand ref only has one result!");
  1144. if (NotRegisters)
  1145. return EEVT::TypeSet(); // Unknown.
  1146. Record *RegClass = R->getValueAsDef("RegClass");
  1147. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1148. return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
  1149. }
  1150. // Check to see if this is a register or a register class.
  1151. if (R->isSubClassOf("RegisterClass")) {
  1152. assert(ResNo == 0 && "Regclass ref only has one result!");
  1153. // An unnamed register class represents itself as an i32 immediate, for
  1154. // example on a COPY_TO_REGCLASS instruction.
  1155. if (Unnamed)
  1156. return EEVT::TypeSet(MVT::i32, TP);
  1157. // In a named operand, the register class provides the possible set of
  1158. // types.
  1159. if (NotRegisters)
  1160. return EEVT::TypeSet(); // Unknown.
  1161. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1162. return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
  1163. }
  1164. if (R->isSubClassOf("PatFrag")) {
  1165. assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
  1166. // Pattern fragment types will be resolved when they are inlined.
  1167. return EEVT::TypeSet(); // Unknown.
  1168. }
  1169. if (R->isSubClassOf("Register")) {
  1170. assert(ResNo == 0 && "Registers only produce one result!");
  1171. if (NotRegisters)
  1172. return EEVT::TypeSet(); // Unknown.
  1173. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1174. return EEVT::TypeSet(T.getRegisterVTs(R));
  1175. }
  1176. if (R->isSubClassOf("SubRegIndex")) {
  1177. assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
  1178. return EEVT::TypeSet();
  1179. }
  1180. if (R->isSubClassOf("ValueType")) {
  1181. assert(ResNo == 0 && "This node only has one result!");
  1182. // An unnamed VTSDNode represents itself as an MVT::Other immediate.
  1183. //
  1184. // (sext_inreg GPR:$src, i16)
  1185. // ~~~
  1186. if (Unnamed)
  1187. return EEVT::TypeSet(MVT::Other, TP);
  1188. // With a name, the ValueType simply provides the type of the named
  1189. // variable.
  1190. //
  1191. // (sext_inreg i32:$src, i16)
  1192. // ~~~~~~~~
  1193. if (NotRegisters)
  1194. return EEVT::TypeSet(); // Unknown.
  1195. return EEVT::TypeSet(getValueType(R), TP);
  1196. }
  1197. if (R->isSubClassOf("CondCode")) {
  1198. assert(ResNo == 0 && "This node only has one result!");
  1199. // Using a CondCodeSDNode.
  1200. return EEVT::TypeSet(MVT::Other, TP);
  1201. }
  1202. if (R->isSubClassOf("ComplexPattern")) {
  1203. assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
  1204. if (NotRegisters)
  1205. return EEVT::TypeSet(); // Unknown.
  1206. return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
  1207. TP);
  1208. }
  1209. if (R->isSubClassOf("PointerLikeRegClass")) {
  1210. assert(ResNo == 0 && "Regclass can only have one result!");
  1211. return EEVT::TypeSet(MVT::iPTR, TP);
  1212. }
  1213. if (R->getName() == "node" || R->getName() == "srcvalue" ||
  1214. R->getName() == "zero_reg") {
  1215. // Placeholder.
  1216. return EEVT::TypeSet(); // Unknown.
  1217. }
  1218. TP.error("Unknown node flavor used in pattern: " + R->getName());
  1219. return EEVT::TypeSet(MVT::Other, TP);
  1220. }
  1221. /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
  1222. /// CodeGenIntrinsic information for it, otherwise return a null pointer.
  1223. const CodeGenIntrinsic *TreePatternNode::
  1224. getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
  1225. if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
  1226. getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
  1227. getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
  1228. return 0;
  1229. unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
  1230. return &CDP.getIntrinsicInfo(IID);
  1231. }
  1232. /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
  1233. /// return the ComplexPattern information, otherwise return null.
  1234. const ComplexPattern *
  1235. TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
  1236. if (!isLeaf()) return 0;
  1237. DefInit *DI = dyn_cast<DefInit>(getLeafValue());
  1238. if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
  1239. return &CGP.getComplexPattern(DI->getDef());
  1240. return 0;
  1241. }
  1242. /// NodeHasProperty - Return true if this node has the specified property.
  1243. bool TreePatternNode::NodeHasProperty(SDNP Property,
  1244. const CodeGenDAGPatterns