GIMatchTree.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. //===- GIMatchTree.cpp - A decision tree to match GIMatchDag's ------------===//
  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. #include "GIMatchTree.h"
  9. #include "GIMatchDagPredicate.h"
  10. #include "../CodeGenInstruction.h"
  11. #include "llvm/Support/Debug.h"
  12. #include "llvm/Support/Format.h"
  13. #include "llvm/Support/ScopedPrinter.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. #include "llvm/TableGen/Error.h"
  16. #include "llvm/TableGen/Record.h"
  17. #define DEBUG_TYPE "gimatchtree"
  18. using namespace llvm;
  19. void GIMatchTree::writeDOTGraph(raw_ostream &OS) const {
  20. OS << "digraph \"matchtree\" {\n";
  21. writeDOTGraphNode(OS);
  22. OS << "}\n";
  23. }
  24. void GIMatchTree::writeDOTGraphNode(raw_ostream &OS) const {
  25. OS << format(" Node%p", this) << " [shape=record,label=\"{";
  26. if (Partitioner) {
  27. Partitioner->emitDescription(OS);
  28. OS << "|" << Partitioner->getNumPartitions() << " partitions|";
  29. } else
  30. OS << "No partitioner|";
  31. bool IsFullyTraversed = true;
  32. bool IsFullyTested = true;
  33. StringRef Separator = "";
  34. for (const auto &Leaf : PossibleLeaves) {
  35. OS << Separator << Leaf.getName();
  36. Separator = ",";
  37. if (!Leaf.isFullyTraversed())
  38. IsFullyTraversed = false;
  39. if (!Leaf.isFullyTested())
  40. IsFullyTested = false;
  41. }
  42. if (!Partitioner && !IsFullyTraversed)
  43. OS << "|Not fully traversed";
  44. if (!Partitioner && !IsFullyTested) {
  45. OS << "|Not fully tested";
  46. if (IsFullyTraversed) {
  47. for (const GIMatchTreeLeafInfo &Leaf : PossibleLeaves) {
  48. if (Leaf.isFullyTested())
  49. continue;
  50. OS << "\\n" << Leaf.getName() << ": " << &Leaf;
  51. for (const GIMatchDagPredicate *P : Leaf.untested_predicates())
  52. OS << *P;
  53. }
  54. }
  55. }
  56. OS << "}\"";
  57. if (!Partitioner &&
  58. (!IsFullyTraversed || !IsFullyTested || PossibleLeaves.size() > 1))
  59. OS << ",color=red";
  60. OS << "]\n";
  61. for (const auto &C : Children)
  62. C.writeDOTGraphNode(OS);
  63. writeDOTGraphEdges(OS);
  64. }
  65. void GIMatchTree::writeDOTGraphEdges(raw_ostream &OS) const {
  66. for (const auto &Child : enumerate(Children)) {
  67. OS << format(" Node%p", this) << " -> " << format("Node%p", &Child.value())
  68. << " [label=\"#" << Child.index() << " ";
  69. Partitioner->emitPartitionName(OS, Child.index());
  70. OS << "\"]\n";
  71. }
  72. }
  73. GIMatchTreeBuilderLeafInfo::GIMatchTreeBuilderLeafInfo(
  74. GIMatchTreeBuilder &Builder, StringRef Name, unsigned RootIdx,
  75. const GIMatchDag &MatchDag, void *Data)
  76. : Builder(Builder), Info(Name, RootIdx, Data), MatchDag(MatchDag),
  77. RemainingInstrNodes(BitVector(MatchDag.getNumInstrNodes(), true)),
  78. RemainingEdges(BitVector(MatchDag.getNumEdges(), true)),
  79. RemainingPredicates(BitVector(MatchDag.getNumPredicates(), true)),
  80. TraversableEdges(MatchDag.getNumEdges()),
  81. TestablePredicates(MatchDag.getNumPredicates()) {
  82. // Number all the predicates in this DAG
  83. for (auto &P : enumerate(MatchDag.predicates())) {
  84. PredicateIDs.insert(std::make_pair(P.value(), P.index()));
  85. }
  86. // Number all the predicate dependencies in this DAG and set up a bitvector
  87. // for each predicate indicating the unsatisfied dependencies.
  88. for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
  89. PredicateDepIDs.insert(std::make_pair(Dep.value(), Dep.index()));
  90. }
  91. UnsatisfiedPredDepsForPred.resize(MatchDag.getNumPredicates(),
  92. BitVector(PredicateDepIDs.size()));
  93. for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
  94. unsigned ID = PredicateIDs.lookup(Dep.value()->getPredicate());
  95. UnsatisfiedPredDepsForPred[ID].set(Dep.index());
  96. }
  97. }
  98. void GIMatchTreeBuilderLeafInfo::declareInstr(const GIMatchDagInstr *Instr, unsigned ID) {
  99. // Record the assignment of this instr to the given ID.
  100. auto InfoI = InstrNodeToInfo.insert(std::make_pair(
  101. Instr, GIMatchTreeInstrInfo(ID, Instr)));
  102. InstrIDToInfo.insert(std::make_pair(ID, &InfoI.first->second));
  103. if (Instr == nullptr)
  104. return;
  105. if (!Instr->getUserAssignedName().empty())
  106. Info.bindInstrVariable(Instr->getUserAssignedName(), ID);
  107. for (const auto &VarBinding : Instr->user_assigned_operand_names())
  108. Info.bindOperandVariable(VarBinding.second, ID, VarBinding.first);
  109. // Clear the bit indicating we haven't visited this instr.
  110. const auto &NodeI = find(MatchDag.instr_nodes(), Instr);
  111. assert(NodeI != MatchDag.instr_nodes_end() && "Instr isn't in this DAG");
  112. unsigned InstrIdx = MatchDag.getInstrNodeIdx(NodeI);
  113. RemainingInstrNodes.reset(InstrIdx);
  114. // When we declare an instruction, we don't expose any traversable edges just
  115. // yet. A partitioner has to check they exist and are registers before they
  116. // are traversable.
  117. // When we declare an instruction, we potentially activate some predicates.
  118. // Mark the dependencies that are now satisfied as a result of this
  119. // instruction and mark any predicates whose dependencies are fully
  120. // satisfied.
  121. for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
  122. if (Dep.value()->getRequiredMI() == Instr &&
  123. Dep.value()->getRequiredMO() == nullptr) {
  124. for (auto &DepsFor : enumerate(UnsatisfiedPredDepsForPred)) {
  125. DepsFor.value().reset(Dep.index());
  126. if (DepsFor.value().none())
  127. TestablePredicates.set(DepsFor.index());
  128. }
  129. }
  130. }
  131. }
  132. void GIMatchTreeBuilderLeafInfo::declareOperand(unsigned InstrID,
  133. unsigned OpIdx) {
  134. const GIMatchDagInstr *Instr = InstrIDToInfo.lookup(InstrID)->getInstrNode();
  135. OperandIDToInfo.insert(std::make_pair(
  136. std::make_pair(InstrID, OpIdx),
  137. GIMatchTreeOperandInfo(Instr, OpIdx)));
  138. // When an operand becomes reachable, we potentially activate some traversals.
  139. // Record the edges that can now be followed as a result of this
  140. // instruction.
  141. for (auto &E : enumerate(MatchDag.edges())) {
  142. if (E.value()->getFromMI() == Instr &&
  143. E.value()->getFromMO()->getIdx() == OpIdx) {
  144. TraversableEdges.set(E.index());
  145. }
  146. }
  147. // When an operand becomes reachable, we potentially activate some predicates.
  148. // Clear the dependencies that are now satisfied as a result of this
  149. // operand and activate any predicates whose dependencies are fully
  150. // satisfied.
  151. for (auto &Dep : enumerate(MatchDag.predicate_edges())) {
  152. if (Dep.value()->getRequiredMI() == Instr && Dep.value()->getRequiredMO() &&
  153. Dep.value()->getRequiredMO()->getIdx() == OpIdx) {
  154. for (auto &DepsFor : enumerate(UnsatisfiedPredDepsForPred)) {
  155. DepsFor.value().reset(Dep.index());
  156. if (DepsFor.value().none())
  157. TestablePredicates.set(DepsFor.index());
  158. }
  159. }
  160. }
  161. }
  162. void GIMatchTreeBuilder::addPartitionersForInstr(unsigned InstrIdx) {
  163. // Find the partitioners that can be used now that this node is
  164. // uncovered. Our choices are:
  165. // - Test the opcode
  166. addPartitioner(std::make_unique<GIMatchTreeOpcodePartitioner>(InstrIdx));
  167. }
  168. void GIMatchTreeBuilder::addPartitionersForOperand(unsigned InstrID,
  169. unsigned OpIdx) {
  170. LLVM_DEBUG(dbgs() << "Add partitioners for Instrs[" << InstrID
  171. << "].getOperand(" << OpIdx << ")\n");
  172. addPartitioner(
  173. std::make_unique<GIMatchTreeVRegDefPartitioner>(InstrID, OpIdx));
  174. }
  175. void GIMatchTreeBuilder::filterRedundantPartitioners() {
  176. // TODO: Filter partitioners for facts that are already known
  177. // - If we know the opcode, we can elide the num operand check so long as
  178. // the instruction has a fixed number of operands.
  179. // - If we know an exact number of operands then we can elide further number
  180. // of operand checks.
  181. // - If the current min number of operands exceeds the one we want to check
  182. // then we can elide it.
  183. }
  184. void GIMatchTreeBuilder::evaluatePartitioners() {
  185. // Determine the partitioning the partitioner would produce
  186. for (auto &Partitioner : Partitioners) {
  187. LLVM_DEBUG(dbgs() << " Weighing up ";
  188. Partitioner->emitDescription(dbgs()); dbgs() << "\n");
  189. Partitioner->repartition(Leaves);
  190. LLVM_DEBUG(Partitioner->emitPartitionResults(dbgs()));
  191. }
  192. }
  193. void GIMatchTreeBuilder::runStep() {
  194. LLVM_DEBUG(dbgs() << "Building match tree node for " << TreeNode << "\n");
  195. LLVM_DEBUG(dbgs() << " Rules reachable at this node:\n");
  196. for (const auto &Leaf : Leaves) {
  197. LLVM_DEBUG(dbgs() << " " << Leaf.getName() << " (" << &Leaf.getInfo() << "\n");
  198. TreeNode->addPossibleLeaf(Leaf.getInfo(), Leaf.isFullyTraversed(),
  199. Leaf.isFullyTested());
  200. }
  201. LLVM_DEBUG(dbgs() << " Partitioners available at this node:\n");
  202. #ifndef NDEBUG
  203. for (const auto &Partitioner : Partitioners)
  204. LLVM_DEBUG(dbgs() << " "; Partitioner->emitDescription(dbgs());
  205. dbgs() << "\n");
  206. #endif // ifndef NDEBUG
  207. // Check for unreachable rules. Rules are unreachable if they are preceeded by
  208. // a fully tested rule.
  209. // Note: This is only true for the current algorithm, if we allow the
  210. // algorithm to compare equally valid rules then they will become
  211. // reachable.
  212. {
  213. auto FullyTestedLeafI = Leaves.end();
  214. for (auto LeafI = Leaves.begin(), LeafE = Leaves.end();
  215. LeafI != LeafE; ++LeafI) {
  216. if (LeafI->isFullyTraversed() && LeafI->isFullyTested())
  217. FullyTestedLeafI = LeafI;
  218. else if (FullyTestedLeafI != Leaves.end()) {
  219. PrintError("Leaf " + LeafI->getName() + " is unreachable");
  220. PrintNote("Leaf " + FullyTestedLeafI->getName() +
  221. " will have already matched");
  222. }
  223. }
  224. }
  225. LLVM_DEBUG(dbgs() << " Eliminating redundant partitioners:\n");
  226. filterRedundantPartitioners();
  227. LLVM_DEBUG(dbgs() << " Partitioners remaining:\n");
  228. #ifndef NDEBUG
  229. for (const auto &Partitioner : Partitioners)
  230. LLVM_DEBUG(dbgs() << " "; Partitioner->emitDescription(dbgs());
  231. dbgs() << "\n");
  232. #endif // ifndef NDEBUG
  233. if (Partitioners.empty()) {
  234. // Nothing left to do but check we really did identify a single rule.
  235. if (Leaves.size() > 1) {
  236. LLVM_DEBUG(dbgs() << "Leaf contains multiple rules, drop after the first "
  237. "fully tested rule\n");
  238. auto FirstFullyTested =
  239. llvm::find_if(Leaves, [](const GIMatchTreeBuilderLeafInfo &X) {
  240. return X.isFullyTraversed() && X.isFullyTested() &&
  241. !X.getMatchDag().hasPostMatchPredicate();
  242. });
  243. if (FirstFullyTested != Leaves.end())
  244. FirstFullyTested++;
  245. #ifndef NDEBUG
  246. for (auto &Leaf : make_range(Leaves.begin(), FirstFullyTested))
  247. LLVM_DEBUG(dbgs() << " Kept " << Leaf.getName() << "\n");
  248. for (const auto &Leaf : make_range(FirstFullyTested, Leaves.end()))
  249. LLVM_DEBUG(dbgs() << " Dropped " << Leaf.getName() << "\n");
  250. #endif // ifndef NDEBUG
  251. TreeNode->dropLeavesAfter(
  252. std::distance(Leaves.begin(), FirstFullyTested));
  253. }
  254. for (const auto &Leaf : Leaves) {
  255. if (!Leaf.isFullyTraversed()) {
  256. PrintError("Leaf " + Leaf.getName() + " is not fully traversed");
  257. PrintNote("This indicates a missing partitioner within tblgen");
  258. Leaf.dump(errs());
  259. for (unsigned InstrIdx : Leaf.untested_instrs())
  260. PrintNote("Instr " + llvm::to_string(*Leaf.getInstr(InstrIdx)));
  261. for (unsigned EdgeIdx : Leaf.untested_edges())
  262. PrintNote("Edge " + llvm::to_string(*Leaf.getEdge(EdgeIdx)));
  263. }
  264. }
  265. // Copy out information about untested predicates so the user of the tree
  266. // can deal with them.
  267. for (auto LeafPair : zip(Leaves, TreeNode->possible_leaves())) {
  268. const GIMatchTreeBuilderLeafInfo &BuilderLeaf = std::get<0>(LeafPair);
  269. GIMatchTreeLeafInfo &TreeLeaf = std::get<1>(LeafPair);
  270. if (!BuilderLeaf.isFullyTested())
  271. for (unsigned PredicateIdx : BuilderLeaf.untested_predicates())
  272. TreeLeaf.addUntestedPredicate(BuilderLeaf.getPredicate(PredicateIdx));
  273. }
  274. return;
  275. }
  276. LLVM_DEBUG(dbgs() << " Weighing up partitioners:\n");
  277. evaluatePartitioners();
  278. // Select the best partitioner by its ability to partition
  279. // - Prefer partitioners that don't distinguish between partitions. This
  280. // is to fail early on decisions that must go a single way.
  281. auto PartitionerI = std::max_element(
  282. Partitioners.begin(), Partitioners.end(),
  283. [](const std::unique_ptr<GIMatchTreePartitioner> &A,
  284. const std::unique_ptr<GIMatchTreePartitioner> &B) {
  285. // We generally want partitioners that subdivide the
  286. // ruleset as much as possible since these take fewer
  287. // checks to converge on a particular rule. However,
  288. // it's important to note that one leaf can end up in
  289. // multiple partitions if the check isn't mutually
  290. // exclusive (e.g. getVRegDef() vs isReg()).
  291. // We therefore minimize average leaves per partition.
  292. return (double)A->getNumLeavesWithDupes() / A->getNumPartitions() >
  293. (double)B->getNumLeavesWithDupes() / B->getNumPartitions();
  294. });
  295. // Select a partitioner and partition the ruleset
  296. // Note that it's possible for a single rule to end up in multiple
  297. // partitions. For example, an opcode test on a rule without an opcode
  298. // predicate will result in it being passed to all partitions.
  299. std::unique_ptr<GIMatchTreePartitioner> Partitioner = std::move(*PartitionerI);
  300. Partitioners.erase(PartitionerI);
  301. LLVM_DEBUG(dbgs() << " Selected partitioner: ";
  302. Partitioner->emitDescription(dbgs()); dbgs() << "\n");
  303. assert(Partitioner->getNumPartitions() > 0 &&
  304. "Must always partition into at least one partition");
  305. TreeNode->setNumChildren(Partitioner->getNumPartitions());
  306. for (auto &C : enumerate(TreeNode->children())) {
  307. SubtreeBuilders.emplace_back(&C.value(), NextInstrID);
  308. Partitioner->applyForPartition(C.index(), *this, SubtreeBuilders.back());
  309. }
  310. TreeNode->setPartitioner(std::move(Partitioner));
  311. // Recurse into the subtree builders. Each one must get a copy of the
  312. // remaining partitioners as each path has to check everything.
  313. for (auto &SubtreeBuilder : SubtreeBuilders) {
  314. for (const auto &Partitioner : Partitioners)
  315. SubtreeBuilder.addPartitioner(Partitioner->clone());
  316. SubtreeBuilder.runStep();
  317. }
  318. }
  319. std::unique_ptr<GIMatchTree> GIMatchTreeBuilder::run() {
  320. unsigned NewInstrID = allocInstrID();
  321. // Start by recording the root instruction as instr #0 and set up the initial
  322. // partitioners.
  323. for (auto &Leaf : Leaves) {
  324. LLVM_DEBUG(Leaf.getMatchDag().writeDOTGraph(dbgs(), Leaf.getName()));
  325. GIMatchDagInstr *Root =
  326. *(Leaf.getMatchDag().roots().begin() + Leaf.getRootIdx());
  327. Leaf.declareInstr(Root, NewInstrID);
  328. }
  329. addPartitionersForInstr(NewInstrID);
  330. std::unique_ptr<GIMatchTree> TreeRoot = std::make_unique<GIMatchTree>();
  331. TreeNode = TreeRoot.get();
  332. runStep();
  333. return TreeRoot;
  334. }
  335. void GIMatchTreeOpcodePartitioner::emitPartitionName(raw_ostream &OS, unsigned Idx) const {
  336. if (PartitionToInstr[Idx] == nullptr) {
  337. OS << "* or nullptr";
  338. return;
  339. }
  340. OS << PartitionToInstr[Idx]->Namespace
  341. << "::" << PartitionToInstr[Idx]->TheDef->getName();
  342. }
  343. void GIMatchTreeOpcodePartitioner::repartition(
  344. GIMatchTreeBuilder::LeafVec &Leaves) {
  345. Partitions.clear();
  346. InstrToPartition.clear();
  347. PartitionToInstr.clear();
  348. TestedPredicates.clear();
  349. for (const auto &Leaf : enumerate(Leaves)) {
  350. bool AllOpcodes = true;
  351. GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
  352. BitVector TestedPredicatesForLeaf(
  353. Leaf.value().getMatchDag().getNumPredicates());
  354. // If the instruction isn't declared then we don't care about it. Ignore
  355. // it for now and add it to all partitions later once we know what
  356. // partitions we have.
  357. if (!InstrInfo) {
  358. LLVM_DEBUG(dbgs() << " " << Leaf.value().getName()
  359. << " doesn't care about Instr[" << InstrID << "]\n");
  360. assert(TestedPredicatesForLeaf.size() == Leaf.value().getMatchDag().getNumPredicates());
  361. TestedPredicates.push_back(TestedPredicatesForLeaf);
  362. continue;
  363. }
  364. // If the opcode is available to test then any opcode predicates will have
  365. // been enabled too.
  366. for (unsigned PIdx : Leaf.value().TestablePredicates.set_bits()) {
  367. const auto &P = Leaf.value().getPredicate(PIdx);
  368. SmallVector<const CodeGenInstruction *, 1> OpcodesForThisPredicate;
  369. if (const auto *OpcodeP = dyn_cast<const GIMatchDagOpcodePredicate>(P)) {
  370. // We've found _an_ opcode predicate, but we don't know if it's
  371. // checking this instruction yet.
  372. bool IsThisPredicate = false;
  373. for (const auto &PDep : Leaf.value().getMatchDag().predicate_edges()) {
  374. if (PDep->getRequiredMI() == InstrInfo->getInstrNode() &&
  375. PDep->getRequiredMO() == nullptr && PDep->getPredicate() == P) {
  376. IsThisPredicate = true;
  377. break;
  378. }
  379. }
  380. if (!IsThisPredicate)
  381. continue;
  382. // If we get here twice then we've somehow ended up with two opcode
  383. // predicates for one instruction in the same DAG. That should be
  384. // impossible.
  385. assert(AllOpcodes && "Conflicting opcode predicates");
  386. const CodeGenInstruction *Expected = OpcodeP->getInstr();
  387. OpcodesForThisPredicate.push_back(Expected);
  388. }
  389. if (const auto *OpcodeP =
  390. dyn_cast<const GIMatchDagOneOfOpcodesPredicate>(P)) {
  391. // We've found _an_ oneof(opcodes) predicate, but we don't know if it's
  392. // checking this instruction yet.
  393. bool IsThisPredicate = false;
  394. for (const auto &PDep : Leaf.value().getMatchDag().predicate_edges()) {
  395. if (PDep->getRequiredMI() == InstrInfo->getInstrNode() &&
  396. PDep->getRequiredMO() == nullptr && PDep->getPredicate() == P) {
  397. IsThisPredicate = true;
  398. break;
  399. }
  400. }
  401. if (!IsThisPredicate)
  402. continue;
  403. // If we get here twice then we've somehow ended up with two opcode
  404. // predicates for one instruction in the same DAG. That should be
  405. // impossible.
  406. assert(AllOpcodes && "Conflicting opcode predicates");
  407. append_range(OpcodesForThisPredicate, OpcodeP->getInstrs());
  408. }
  409. for (const CodeGenInstruction *Expected : OpcodesForThisPredicate) {
  410. // Mark this predicate as one we're testing.
  411. TestedPredicatesForLeaf.set(PIdx);
  412. // Partitions must be numbered 0, 1, .., N but instructions don't meet
  413. // that requirement. Assign a partition number to each opcode if we
  414. // lack one ...
  415. auto Partition = InstrToPartition.find(Expected);
  416. if (Partition == InstrToPartition.end()) {
  417. BitVector Contents(Leaves.size());
  418. Partition = InstrToPartition
  419. .insert(std::make_pair(Expected, Partitions.size()))
  420. .first;
  421. PartitionToInstr.push_back(Expected);
  422. Partitions.insert(std::make_pair(Partitions.size(), Contents));
  423. }
  424. // ... and mark this leaf as being in that partition.
  425. Partitions.find(Partition->second)->second.set(Leaf.index());
  426. AllOpcodes = false;
  427. LLVM_DEBUG(dbgs() << " " << Leaf.value().getName()
  428. << " is in partition " << Partition->second << "\n");
  429. }
  430. // TODO: This is where we would handle multiple choices of opcode
  431. // the end result will be that this leaf ends up in multiple
  432. // partitions similarly to AllOpcodes.
  433. }
  434. // If we never check the opcode, add it to every partition.
  435. if (AllOpcodes) {
  436. // Add a partition for the default case if we don't already have one.
  437. if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) {
  438. PartitionToInstr.push_back(nullptr);
  439. BitVector Contents(Leaves.size());
  440. Partitions.insert(std::make_pair(Partitions.size(), Contents));
  441. }
  442. LLVM_DEBUG(dbgs() << " " << Leaf.value().getName()
  443. << " is in all partitions (opcode not checked)\n");
  444. for (auto &Partition : Partitions)
  445. Partition.second.set(Leaf.index());
  446. }
  447. assert(TestedPredicatesForLeaf.size() == Leaf.value().getMatchDag().getNumPredicates());
  448. TestedPredicates.push_back(TestedPredicatesForLeaf);
  449. }
  450. if (Partitions.size() == 0) {
  451. // Add a partition for the default case if we don't already have one.
  452. if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) {
  453. PartitionToInstr.push_back(nullptr);
  454. BitVector Contents(Leaves.size());
  455. Partitions.insert(std::make_pair(Partitions.size(), Contents));
  456. }
  457. }
  458. // Add any leaves that don't care about this instruction to all partitions.
  459. for (const auto &Leaf : enumerate(Leaves)) {
  460. GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
  461. if (!InstrInfo) {
  462. // Add a partition for the default case if we don't already have one.
  463. if (InstrToPartition.insert(std::make_pair(nullptr, 0)).second) {
  464. PartitionToInstr.push_back(nullptr);
  465. BitVector Contents(Leaves.size());
  466. Partitions.insert(std::make_pair(Partitions.size(), Contents));
  467. }
  468. for (auto &Partition : Partitions)
  469. Partition.second.set(Leaf.index());
  470. }
  471. }
  472. }
  473. void GIMatchTreeOpcodePartitioner::applyForPartition(
  474. unsigned PartitionIdx, GIMatchTreeBuilder &Builder, GIMatchTreeBuilder &SubBuilder) {
  475. LLVM_DEBUG(dbgs() << " Making partition " << PartitionIdx << "\n");
  476. const CodeGenInstruction *CGI = PartitionToInstr[PartitionIdx];
  477. BitVector PossibleLeaves = getPossibleLeavesForPartition(PartitionIdx);
  478. // Consume any predicates we handled.
  479. for (auto &EnumeratedLeaf : enumerate(Builder.getPossibleLeaves())) {
  480. if (!PossibleLeaves[EnumeratedLeaf.index()])
  481. continue;
  482. auto &Leaf = EnumeratedLeaf.value();
  483. const auto &TestedPredicatesForLeaf =
  484. TestedPredicates[EnumeratedLeaf.index()];
  485. for (unsigned PredIdx : TestedPredicatesForLeaf.set_bits()) {
  486. LLVM_DEBUG(dbgs() << " " << Leaf.getName() << " tested predicate #"
  487. << PredIdx << " of " << TestedPredicatesForLeaf.size()
  488. << " " << *Leaf.getPredicate(PredIdx) << "\n");
  489. Leaf.RemainingPredicates.reset(PredIdx);
  490. Leaf.TestablePredicates.reset(PredIdx);
  491. }
  492. SubBuilder.addLeaf(Leaf);
  493. }
  494. // Nothing to do, we don't know anything about this instruction as a result
  495. // of this partitioner.
  496. if (CGI == nullptr)
  497. return;
  498. GIMatchTreeBuilder::LeafVec &NewLeaves = SubBuilder.getPossibleLeaves();
  499. // Find all the operands we know to exist and are referenced. This will
  500. // usually be all the referenced operands but there are some cases where
  501. // instructions are variadic. Such operands must be handled by partitioners
  502. // that check the number of operands.
  503. BitVector ReferencedOperands(1);
  504. for (auto &Leaf : NewLeaves) {
  505. GIMatchTreeInstrInfo *InstrInfo = Leaf.getInstrInfo(InstrID);
  506. // Skip any leaves that don't care about this instruction.
  507. if (!InstrInfo)
  508. continue;
  509. const GIMatchDagInstr *Instr = InstrInfo->getInstrNode();
  510. for (auto &E : enumerate(Leaf.getMatchDag().edges())) {
  511. if (E.value()->getFromMI() == Instr &&
  512. E.value()->getFromMO()->getIdx() < CGI->Operands.size()) {
  513. ReferencedOperands.resize(E.value()->getFromMO()->getIdx() + 1);
  514. ReferencedOperands.set(E.value()->getFromMO()->getIdx());
  515. }
  516. }
  517. }
  518. for (auto &Leaf : NewLeaves) {
  519. // Skip any leaves that don't care about this instruction.
  520. if (!Leaf.getInstrInfo(InstrID))
  521. continue;
  522. for (unsigned OpIdx : ReferencedOperands.set_bits()) {
  523. Leaf.declareOperand(InstrID, OpIdx);
  524. }
  525. }
  526. for (unsigned OpIdx : ReferencedOperands.set_bits()) {
  527. SubBuilder.addPartitionersForOperand(InstrID, OpIdx);
  528. }
  529. }
  530. void GIMatchTreeOpcodePartitioner::emitPartitionResults(
  531. raw_ostream &OS) const {
  532. OS << "Partitioning by opcode would produce " << Partitions.size()
  533. << " partitions\n";
  534. for (const auto &Partition : InstrToPartition) {
  535. if (Partition.first == nullptr)
  536. OS << "Default: ";
  537. else
  538. OS << Partition.first->TheDef->getName() << ": ";
  539. StringRef Separator = "";
  540. for (unsigned I : Partitions.find(Partition.second)->second.set_bits()) {
  541. OS << Separator << I;
  542. Separator = ", ";
  543. }
  544. OS << "\n";
  545. }
  546. }
  547. void GIMatchTreeOpcodePartitioner::generatePartitionSelectorCode(
  548. raw_ostream &OS, StringRef Indent) const {
  549. // Make sure not to emit empty switch or switch with just default
  550. if (PartitionToInstr.size() == 1 && PartitionToInstr[0] == nullptr) {
  551. OS << Indent << "Partition = 0;\n";
  552. } else if (PartitionToInstr.size()) {
  553. OS << Indent << "Partition = -1;\n"
  554. << Indent << "switch (MIs[" << InstrID << "]->getOpcode()) {\n";
  555. for (const auto &EnumInstr : enumerate(PartitionToInstr)) {
  556. if (EnumInstr.value() == nullptr)
  557. OS << Indent << "default:";
  558. else
  559. OS << Indent << "case " << EnumInstr.value()->Namespace
  560. << "::" << EnumInstr.value()->TheDef->getName() << ":";
  561. OS << " Partition = " << EnumInstr.index() << "; break;\n";
  562. }
  563. OS << Indent << "}\n";
  564. }
  565. OS << Indent
  566. << "// Default case but without conflicting with potential default case "
  567. "in selection.\n"
  568. << Indent << "if (Partition == -1) return false;\n";
  569. }
  570. void GIMatchTreeVRegDefPartitioner::addToPartition(bool Result,
  571. unsigned LeafIdx) {
  572. auto I = ResultToPartition.find(Result);
  573. if (I == ResultToPartition.end()) {
  574. ResultToPartition.insert(std::make_pair(Result, PartitionToResult.size()));
  575. PartitionToResult.push_back(Result);
  576. }
  577. I = ResultToPartition.find(Result);
  578. auto P = Partitions.find(I->second);
  579. if (P == Partitions.end())
  580. P = Partitions.insert(std::make_pair(I->second, BitVector())).first;
  581. P->second.resize(LeafIdx + 1);
  582. P->second.set(LeafIdx);
  583. }
  584. void GIMatchTreeVRegDefPartitioner::repartition(
  585. GIMatchTreeBuilder::LeafVec &Leaves) {
  586. Partitions.clear();
  587. for (const auto &Leaf : enumerate(Leaves)) {
  588. GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
  589. BitVector TraversedEdgesForLeaf(Leaf.value().getMatchDag().getNumEdges());
  590. // If the instruction isn't declared then we don't care about it. Ignore
  591. // it for now and add it to all partitions later once we know what
  592. // partitions we have.
  593. if (!InstrInfo) {
  594. TraversedEdges.push_back(TraversedEdgesForLeaf);
  595. continue;
  596. }
  597. // If this node has an use -> def edge from this operand then this
  598. // instruction must be in partition 1 (isVRegDef()).
  599. bool WantsEdge = false;
  600. for (unsigned EIdx : Leaf.value().TraversableEdges.set_bits()) {
  601. const auto &E = Leaf.value().getEdge(EIdx);
  602. if (E->getFromMI() != InstrInfo->getInstrNode() ||
  603. E->getFromMO()->getIdx() != OpIdx || E->isDefToUse())
  604. continue;
  605. // We're looking at the right edge. This leaf wants a vreg def so we'll
  606. // put it in partition 1.
  607. addToPartition(true, Leaf.index());
  608. TraversedEdgesForLeaf.set(EIdx);
  609. WantsEdge = true;
  610. }
  611. bool isNotReg = false;
  612. if (!WantsEdge && isNotReg) {
  613. // If this leaf doesn't have an edge and we _don't_ want a register,
  614. // then add it to partition 0.
  615. addToPartition(false, Leaf.index());
  616. } else if (!WantsEdge) {
  617. // If this leaf doesn't have an edge and we don't know what we want,
  618. // then add it to partition 0 and 1.
  619. addToPartition(false, Leaf.index());
  620. addToPartition(true, Leaf.index());
  621. }
  622. TraversedEdges.push_back(TraversedEdgesForLeaf);
  623. }
  624. // Add any leaves that don't care about this instruction to all partitions.
  625. for (const auto &Leaf : enumerate(Leaves)) {
  626. GIMatchTreeInstrInfo *InstrInfo = Leaf.value().getInstrInfo(InstrID);
  627. if (!InstrInfo)
  628. for (auto &Partition : Partitions) {
  629. Partition.second.resize(Leaf.index() + 1);
  630. Partition.second.set(Leaf.index());
  631. }
  632. }
  633. }
  634. void GIMatchTreeVRegDefPartitioner::applyForPartition(
  635. unsigned PartitionIdx, GIMatchTreeBuilder &Builder,
  636. GIMatchTreeBuilder &SubBuilder) {
  637. BitVector PossibleLeaves = getPossibleLeavesForPartition(PartitionIdx);
  638. std::vector<BitVector> TraversedEdgesByNewLeaves;
  639. // Consume any edges we handled.
  640. for (auto &EnumeratedLeaf : enumerate(Builder.getPossibleLeaves())) {
  641. if (!PossibleLeaves[EnumeratedLeaf.index()])
  642. continue;
  643. auto &Leaf = EnumeratedLeaf.value();
  644. const auto &TraversedEdgesForLeaf = TraversedEdges[EnumeratedLeaf.index()];
  645. TraversedEdgesByNewLeaves.push_back(TraversedEdgesForLeaf);
  646. Leaf.RemainingEdges.reset(TraversedEdgesForLeaf);
  647. Leaf.TraversableEdges.reset(TraversedEdgesForLeaf);
  648. SubBuilder.addLeaf(Leaf);
  649. }
  650. // Nothing to do. The only thing we know is that it isn't a vreg-def.
  651. if (PartitionToResult[PartitionIdx] == false)
  652. return;
  653. NewInstrID = SubBuilder.allocInstrID();
  654. GIMatchTreeBuilder::LeafVec &NewLeaves = SubBuilder.getPossibleLeaves();
  655. for (const auto I : zip(NewLeaves, TraversedEdgesByNewLeaves)) {
  656. auto &Leaf = std::get<0>(I);
  657. auto &TraversedEdgesForLeaf = std::get<1>(I);
  658. GIMatchTreeInstrInfo *InstrInfo = Leaf.getInstrInfo(InstrID);
  659. // Skip any leaves that don't care about this instruction.
  660. if (!InstrInfo)
  661. continue;
  662. for (unsigned EIdx : TraversedEdgesForLeaf.set_bits()) {
  663. const GIMatchDagEdge *E = Leaf.getEdge(EIdx);
  664. Leaf.declareInstr(E->getToMI(), NewInstrID);
  665. }
  666. }
  667. SubBuilder.addPartitionersForInstr(NewInstrID);
  668. }
  669. void GIMatchTreeVRegDefPartitioner::emitPartitionResults(
  670. raw_ostream &OS) const {
  671. OS << "Partitioning by vreg-def would produce " << Partitions.size()
  672. << " partitions\n";
  673. for (const auto &Partition : Partitions) {
  674. OS << Partition.first << " (";
  675. emitPartitionName(OS, Partition.first);
  676. OS << "): ";
  677. StringRef Separator = "";
  678. for (unsigned I : Partition.second.set_bits()) {
  679. OS << Separator << I;
  680. Separator = ", ";
  681. }
  682. OS << "\n";
  683. }
  684. }
  685. void GIMatchTreeVRegDefPartitioner::generatePartitionSelectorCode(
  686. raw_ostream &OS, StringRef Indent) const {
  687. OS << Indent << "Partition = -1;\n"
  688. << Indent << "if (MIs.size() <= " << NewInstrID << ") MIs.resize("
  689. << (NewInstrID + 1) << ");\n"
  690. << Indent << "MIs[" << NewInstrID << "] = nullptr;\n"
  691. << Indent << "if (MIs[" << InstrID << "]->getOperand(" << OpIdx
  692. << ").isReg())\n"
  693. << Indent << " MIs[" << NewInstrID << "] = MRI.getVRegDef(MIs[" << InstrID
  694. << "]->getOperand(" << OpIdx << ").getReg());\n";
  695. for (const auto &Pair : ResultToPartition)
  696. OS << Indent << "if (MIs[" << NewInstrID << "] "
  697. << (Pair.first ? "!=" : "==")
  698. << " nullptr) Partition = " << Pair.second << ";\n";
  699. OS << Indent << "if (Partition == -1) return false;\n";
  700. }