DAGISelMatcherOpt.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. //===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
  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 implements the DAG Matcher optimizer.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "DAGISelMatcher.h"
  13. #include "CodeGenDAGPatterns.h"
  14. #include "llvm/ADT/StringSet.h"
  15. #include "llvm/Support/Debug.h"
  16. #include "llvm/Support/raw_ostream.h"
  17. using namespace llvm;
  18. #define DEBUG_TYPE "isel-opt"
  19. /// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
  20. /// into single compound nodes like RecordChild.
  21. static void ContractNodes(std::unique_ptr<Matcher> &MatcherPtr,
  22. const CodeGenDAGPatterns &CGP) {
  23. // If we reached the end of the chain, we're done.
  24. Matcher *N = MatcherPtr.get();
  25. if (!N) return;
  26. // If we have a scope node, walk down all of the children.
  27. if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {
  28. for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
  29. std::unique_ptr<Matcher> Child(Scope->takeChild(i));
  30. ContractNodes(Child, CGP);
  31. Scope->resetChild(i, Child.release());
  32. }
  33. return;
  34. }
  35. // If we found a movechild node with a node that comes in a 'foochild' form,
  36. // transform it.
  37. if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) {
  38. Matcher *New = nullptr;
  39. if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext()))
  40. if (MC->getChildNo() < 8) // Only have RecordChild0...7
  41. New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor(),
  42. RM->getResultNo());
  43. if (CheckTypeMatcher *CT = dyn_cast<CheckTypeMatcher>(MC->getNext()))
  44. if (MC->getChildNo() < 8 && // Only have CheckChildType0...7
  45. CT->getResNo() == 0) // CheckChildType checks res #0
  46. New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());
  47. if (CheckSameMatcher *CS = dyn_cast<CheckSameMatcher>(MC->getNext()))
  48. if (MC->getChildNo() < 4) // Only have CheckChildSame0...3
  49. New = new CheckChildSameMatcher(MC->getChildNo(), CS->getMatchNumber());
  50. if (CheckIntegerMatcher *CI = dyn_cast<CheckIntegerMatcher>(MC->getNext()))
  51. if (MC->getChildNo() < 5) // Only have CheckChildInteger0...4
  52. New = new CheckChildIntegerMatcher(MC->getChildNo(), CI->getValue());
  53. if (auto *CCC = dyn_cast<CheckCondCodeMatcher>(MC->getNext()))
  54. if (MC->getChildNo() == 2) // Only have CheckChild2CondCode
  55. New = new CheckChild2CondCodeMatcher(CCC->getCondCodeName());
  56. if (New) {
  57. // Insert the new node.
  58. New->setNext(MatcherPtr.release());
  59. MatcherPtr.reset(New);
  60. // Remove the old one.
  61. MC->setNext(MC->getNext()->takeNext());
  62. return ContractNodes(MatcherPtr, CGP);
  63. }
  64. }
  65. // Zap movechild -> moveparent.
  66. if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))
  67. if (MoveParentMatcher *MP =
  68. dyn_cast<MoveParentMatcher>(MC->getNext())) {
  69. MatcherPtr.reset(MP->takeNext());
  70. return ContractNodes(MatcherPtr, CGP);
  71. }
  72. // Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
  73. if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))
  74. if (CompleteMatchMatcher *CM =
  75. dyn_cast<CompleteMatchMatcher>(EN->getNext())) {
  76. // We can only use MorphNodeTo if the result values match up.
  77. unsigned RootResultFirst = EN->getFirstResultSlot();
  78. bool ResultsMatch = true;
  79. for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)
  80. if (CM->getResult(i) != RootResultFirst+i)
  81. ResultsMatch = false;
  82. // If the selected node defines a subset of the glue/chain results, we
  83. // can't use MorphNodeTo. For example, we can't use MorphNodeTo if the
  84. // matched pattern has a chain but the root node doesn't.
  85. const PatternToMatch &Pattern = CM->getPattern();
  86. if (!EN->hasChain() &&
  87. Pattern.getSrcPattern()->NodeHasProperty(SDNPHasChain, CGP))
  88. ResultsMatch = false;
  89. // If the matched node has glue and the output root doesn't, we can't
  90. // use MorphNodeTo.
  91. //
  92. // NOTE: Strictly speaking, we don't have to check for glue here
  93. // because the code in the pattern generator doesn't handle it right. We
  94. // do it anyway for thoroughness.
  95. if (!EN->hasOutFlag() &&
  96. Pattern.getSrcPattern()->NodeHasProperty(SDNPOutGlue, CGP))
  97. ResultsMatch = false;
  98. // If the root result node defines more results than the source root node
  99. // *and* has a chain or glue input, then we can't match it because it
  100. // would end up replacing the extra result with the chain/glue.
  101. #if 0
  102. if ((EN->hasGlue() || EN->hasChain()) &&
  103. EN->getNumNonChainGlueVTs() > ... need to get no results reliably ...)
  104. ResultMatch = false;
  105. #endif
  106. if (ResultsMatch) {
  107. const SmallVectorImpl<MVT::SimpleValueType> &VTs = EN->getVTList();
  108. const SmallVectorImpl<unsigned> &Operands = EN->getOperandList();
  109. MatcherPtr.reset(new MorphNodeToMatcher(EN->getOpcodeName(),
  110. VTs, Operands,
  111. EN->hasChain(), EN->hasInFlag(),
  112. EN->hasOutFlag(),
  113. EN->hasMemRefs(),
  114. EN->getNumFixedArityOperands(),
  115. Pattern));
  116. return;
  117. }
  118. // FIXME2: Kill off all the SelectionDAG::SelectNodeTo and getMachineNode
  119. // variants.
  120. }
  121. ContractNodes(N->getNextPtr(), CGP);
  122. // If we have a CheckType/CheckChildType/Record node followed by a
  123. // CheckOpcode, invert the two nodes. We prefer to do structural checks
  124. // before type checks, as this opens opportunities for factoring on targets
  125. // like X86 where many operations are valid on multiple types.
  126. if ((isa<CheckTypeMatcher>(N) || isa<CheckChildTypeMatcher>(N) ||
  127. isa<RecordMatcher>(N)) &&
  128. isa<CheckOpcodeMatcher>(N->getNext())) {
  129. // Unlink the two nodes from the list.
  130. Matcher *CheckType = MatcherPtr.release();
  131. Matcher *CheckOpcode = CheckType->takeNext();
  132. Matcher *Tail = CheckOpcode->takeNext();
  133. // Relink them.
  134. MatcherPtr.reset(CheckOpcode);
  135. CheckOpcode->setNext(CheckType);
  136. CheckType->setNext(Tail);
  137. return ContractNodes(MatcherPtr, CGP);
  138. }
  139. }
  140. /// FindNodeWithKind - Scan a series of matchers looking for a matcher with a
  141. /// specified kind. Return null if we didn't find one otherwise return the
  142. /// matcher.
  143. static Matcher *FindNodeWithKind(Matcher *M, Matcher::KindTy Kind) {
  144. for (; M; M = M->getNext())
  145. if (M->getKind() == Kind)
  146. return M;
  147. return nullptr;
  148. }
  149. /// FactorNodes - Turn matches like this:
  150. /// Scope
  151. /// OPC_CheckType i32
  152. /// ABC
  153. /// OPC_CheckType i32
  154. /// XYZ
  155. /// into:
  156. /// OPC_CheckType i32
  157. /// Scope
  158. /// ABC
  159. /// XYZ
  160. ///
  161. static void FactorNodes(std::unique_ptr<Matcher> &InputMatcherPtr) {
  162. // Look for a push node. Iterates instead of recurses to reduce stack usage.
  163. ScopeMatcher *Scope = nullptr;
  164. std::unique_ptr<Matcher> *RebindableMatcherPtr = &InputMatcherPtr;
  165. while (!Scope) {
  166. // If we reached the end of the chain, we're done.
  167. Matcher *N = RebindableMatcherPtr->get();
  168. if (!N) return;
  169. // If this is not a push node, just scan for one.
  170. Scope = dyn_cast<ScopeMatcher>(N);
  171. if (!Scope)
  172. RebindableMatcherPtr = &(N->getNextPtr());
  173. }
  174. std::unique_ptr<Matcher> &MatcherPtr = *RebindableMatcherPtr;
  175. // Okay, pull together the children of the scope node into a vector so we can
  176. // inspect it more easily.
  177. SmallVector<Matcher*, 32> OptionsToMatch;
  178. for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {
  179. // Factor the subexpression.
  180. std::unique_ptr<Matcher> Child(Scope->takeChild(i));
  181. FactorNodes(Child);
  182. if (Child) {
  183. // If the child is a ScopeMatcher we can just merge its contents.
  184. if (auto *SM = dyn_cast<ScopeMatcher>(Child.get())) {
  185. for (unsigned j = 0, e = SM->getNumChildren(); j != e; ++j)
  186. OptionsToMatch.push_back(SM->takeChild(j));
  187. } else {
  188. OptionsToMatch.push_back(Child.release());
  189. }
  190. }
  191. }
  192. SmallVector<Matcher*, 32> NewOptionsToMatch;
  193. // Loop over options to match, merging neighboring patterns with identical
  194. // starting nodes into a shared matcher.
  195. for (unsigned OptionIdx = 0, e = OptionsToMatch.size(); OptionIdx != e;) {
  196. // Find the set of matchers that start with this node.
  197. Matcher *Optn = OptionsToMatch[OptionIdx++];
  198. if (OptionIdx == e) {
  199. NewOptionsToMatch.push_back(Optn);
  200. continue;
  201. }
  202. // See if the next option starts with the same matcher. If the two
  203. // neighbors *do* start with the same matcher, we can factor the matcher out
  204. // of at least these two patterns. See what the maximal set we can merge
  205. // together is.
  206. SmallVector<Matcher*, 8> EqualMatchers;
  207. EqualMatchers.push_back(Optn);
  208. // Factor all of the known-equal matchers after this one into the same
  209. // group.
  210. while (OptionIdx != e && OptionsToMatch[OptionIdx]->isEqual(Optn))
  211. EqualMatchers.push_back(OptionsToMatch[OptionIdx++]);
  212. // If we found a non-equal matcher, see if it is contradictory with the
  213. // current node. If so, we know that the ordering relation between the
  214. // current sets of nodes and this node don't matter. Look past it to see if
  215. // we can merge anything else into this matching group.
  216. unsigned Scan = OptionIdx;
  217. while (1) {
  218. // If we ran out of stuff to scan, we're done.
  219. if (Scan == e) break;
  220. Matcher *ScanMatcher = OptionsToMatch[Scan];
  221. // If we found an entry that matches out matcher, merge it into the set to
  222. // handle.
  223. if (Optn->isEqual(ScanMatcher)) {
  224. // If is equal after all, add the option to EqualMatchers and remove it
  225. // from OptionsToMatch.
  226. EqualMatchers.push_back(ScanMatcher);
  227. OptionsToMatch.erase(OptionsToMatch.begin()+Scan);
  228. --e;
  229. continue;
  230. }
  231. // If the option we're checking for contradicts the start of the list,
  232. // skip over it.
  233. if (Optn->isContradictory(ScanMatcher)) {
  234. ++Scan;
  235. continue;
  236. }
  237. // If we're scanning for a simple node, see if it occurs later in the
  238. // sequence. If so, and if we can move it up, it might be contradictory
  239. // or the same as what we're looking for. If so, reorder it.
  240. if (Optn->isSimplePredicateOrRecordNode()) {
  241. Matcher *M2 = FindNodeWithKind(ScanMatcher, Optn->getKind());
  242. if (M2 && M2 != ScanMatcher &&
  243. M2->canMoveBefore(ScanMatcher) &&
  244. (M2->isEqual(Optn) || M2->isContradictory(Optn))) {
  245. Matcher *MatcherWithoutM2 = ScanMatcher->unlinkNode(M2);
  246. M2->setNext(MatcherWithoutM2);
  247. OptionsToMatch[Scan] = M2;
  248. continue;
  249. }
  250. }
  251. // Otherwise, we don't know how to handle this entry, we have to bail.
  252. break;
  253. }
  254. if (Scan != e &&
  255. // Don't print it's obvious nothing extra could be merged anyway.
  256. Scan+1 != e) {
  257. LLVM_DEBUG(errs() << "Couldn't merge this:\n"; Optn->print(errs(), 4);
  258. errs() << "into this:\n";
  259. OptionsToMatch[Scan]->print(errs(), 4);
  260. if (Scan + 1 != e) OptionsToMatch[Scan + 1]->printOne(errs());
  261. if (Scan + 2 < e) OptionsToMatch[Scan + 2]->printOne(errs());
  262. errs() << "\n");
  263. }
  264. // If we only found one option starting with this matcher, no factoring is
  265. // possible.
  266. if (EqualMatchers.size() == 1) {
  267. NewOptionsToMatch.push_back(EqualMatchers[0]);
  268. continue;
  269. }
  270. // Factor these checks by pulling the first node off each entry and
  271. // discarding it. Take the first one off the first entry to reuse.
  272. Matcher *Shared = Optn;
  273. Optn = Optn->takeNext();
  274. EqualMatchers[0] = Optn;
  275. // Remove and delete the first node from the other matchers we're factoring.
  276. for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {
  277. Matcher *Tmp = EqualMatchers[i]->takeNext();
  278. delete EqualMatchers[i];
  279. EqualMatchers[i] = Tmp;
  280. }
  281. Shared->setNext(new ScopeMatcher(EqualMatchers));
  282. // Recursively factor the newly created node.
  283. FactorNodes(Shared->getNextPtr());
  284. NewOptionsToMatch.push_back(Shared);
  285. }
  286. // If we're down to a single pattern to match, then we don't need this scope
  287. // anymore.
  288. if (NewOptionsToMatch.size() == 1) {
  289. MatcherPtr.reset(NewOptionsToMatch[0]);
  290. return;
  291. }
  292. if (NewOptionsToMatch.empty()) {
  293. MatcherPtr.reset();
  294. return;
  295. }
  296. // If our factoring failed (didn't achieve anything) see if we can simplify in
  297. // other ways.
  298. // Check to see if all of the leading entries are now opcode checks. If so,
  299. // we can convert this Scope to be a OpcodeSwitch instead.
  300. bool AllOpcodeChecks = true, AllTypeChecks = true;
  301. for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
  302. // Check to see if this breaks a series of CheckOpcodeMatchers.
  303. if (AllOpcodeChecks &&
  304. !isa<CheckOpcodeMatcher>(NewOptionsToMatch[i])) {
  305. #if 0
  306. if (i > 3) {
  307. errs() << "FAILING OPC #" << i << "\n";
  308. NewOptionsToMatch[i]->dump();
  309. }
  310. #endif
  311. AllOpcodeChecks = false;
  312. }
  313. // Check to see if this breaks a series of CheckTypeMatcher's.
  314. if (AllTypeChecks) {
  315. CheckTypeMatcher *CTM =
  316. cast_or_null<CheckTypeMatcher>(FindNodeWithKind(NewOptionsToMatch[i],
  317. Matcher::CheckType));
  318. if (!CTM ||
  319. // iPTR checks could alias any other case without us knowing, don't
  320. // bother with them.
  321. CTM->getType() == MVT::iPTR ||
  322. // SwitchType only works for result #0.
  323. CTM->getResNo() != 0 ||
  324. // If the CheckType isn't at the start of the list, see if we can move
  325. // it there.
  326. !CTM->canMoveBefore(NewOptionsToMatch[i])) {
  327. #if 0
  328. if (i > 3 && AllTypeChecks) {
  329. errs() << "FAILING TYPE #" << i << "\n";
  330. NewOptionsToMatch[i]->dump();
  331. }
  332. #endif
  333. AllTypeChecks = false;
  334. }
  335. }
  336. }
  337. // If all the options are CheckOpcode's, we can form the SwitchOpcode, woot.
  338. if (AllOpcodeChecks) {
  339. StringSet<> Opcodes;
  340. SmallVector<std::pair<const SDNodeInfo*, Matcher*>, 8> Cases;
  341. for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
  342. CheckOpcodeMatcher *COM = cast<CheckOpcodeMatcher>(NewOptionsToMatch[i]);
  343. assert(Opcodes.insert(COM->getOpcode().getEnumName()).second &&
  344. "Duplicate opcodes not factored?");
  345. Cases.push_back(std::make_pair(&COM->getOpcode(), COM->takeNext()));
  346. delete COM;
  347. }
  348. MatcherPtr.reset(new SwitchOpcodeMatcher(Cases));
  349. return;
  350. }
  351. // If all the options are CheckType's, we can form the SwitchType, woot.
  352. if (AllTypeChecks) {
  353. DenseMap<unsigned, unsigned> TypeEntry;
  354. SmallVector<std::pair<MVT::SimpleValueType, Matcher*>, 8> Cases;
  355. for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i) {
  356. Matcher* M = FindNodeWithKind(NewOptionsToMatch[i], Matcher::CheckType);
  357. assert(M && isa<CheckTypeMatcher>(M) && "Unknown Matcher type");
  358. auto *CTM = cast<CheckTypeMatcher>(M);
  359. Matcher *MatcherWithoutCTM = NewOptionsToMatch[i]->unlinkNode(CTM);
  360. MVT::SimpleValueType CTMTy = CTM->getType();
  361. delete CTM;
  362. unsigned &Entry = TypeEntry[CTMTy];
  363. if (Entry != 0) {
  364. // If we have unfactored duplicate types, then we should factor them.
  365. Matcher *PrevMatcher = Cases[Entry-1].second;
  366. if (ScopeMatcher *SM = dyn_cast<ScopeMatcher>(PrevMatcher)) {
  367. SM->setNumChildren(SM->getNumChildren()+1);
  368. SM->resetChild(SM->getNumChildren()-1, MatcherWithoutCTM);
  369. continue;
  370. }
  371. Matcher *Entries[2] = { PrevMatcher, MatcherWithoutCTM };
  372. Cases[Entry-1].second = new ScopeMatcher(Entries);
  373. continue;
  374. }
  375. Entry = Cases.size()+1;
  376. Cases.push_back(std::make_pair(CTMTy, MatcherWithoutCTM));
  377. }
  378. // Make sure we recursively factor any scopes we may have created.
  379. for (auto &M : Cases) {
  380. if (ScopeMatcher *SM = dyn_cast<ScopeMatcher>(M.second)) {
  381. std::unique_ptr<Matcher> Scope(SM);
  382. FactorNodes(Scope);
  383. M.second = Scope.release();
  384. assert(M.second && "null matcher");
  385. }
  386. }
  387. if (Cases.size() != 1) {
  388. MatcherPtr.reset(new SwitchTypeMatcher(Cases));
  389. } else {
  390. // If we factored and ended up with one case, create it now.
  391. MatcherPtr.reset(new CheckTypeMatcher(Cases[0].first, 0));
  392. MatcherPtr->setNext(Cases[0].second);
  393. }
  394. return;
  395. }
  396. // Reassemble the Scope node with the adjusted children.
  397. Scope->setNumChildren(NewOptionsToMatch.size());
  398. for (unsigned i = 0, e = NewOptionsToMatch.size(); i != e; ++i)
  399. Scope->resetChild(i, NewOptionsToMatch[i]);
  400. }
  401. void
  402. llvm::OptimizeMatcher(std::unique_ptr<Matcher> &MatcherPtr,
  403. const CodeGenDAGPatterns &CGP) {
  404. ContractNodes(MatcherPtr, CGP);
  405. FactorNodes(MatcherPtr);
  406. }