xref: /llvm-project/mlir/lib/Reducer/ReductionNode.cpp (revision c484c7dd9d2382f07216ae9142ceb76272e21dc4)
1 //===- ReductionNode.cpp - Reduction Node Implementation -----------------===//
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 defines the reduction nodes which are used to track of the
10 // metadata for a specific generated variant within a reduction pass and are the
11 // building blocks of the reduction tree structure. A reduction tree is used to
12 // keep track of the different generated variants throughout a reduction pass in
13 // the MLIR Reduce tool.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "mlir/Reducer/ReductionNode.h"
18 #include "mlir/IR/BlockAndValueMapping.h"
19 #include "llvm/ADT/STLExtras.h"
20 
21 #include <algorithm>
22 #include <limits>
23 
24 using namespace mlir;
25 
26 ReductionNode::ReductionNode(
27     ReductionNode *parentNode, std::vector<Range> ranges,
28     llvm::SpecificBumpPtrAllocator<ReductionNode> &allocator)
29     /// Root node will have the parent pointer point to themselves.
30     : parent(parentNode == nullptr ? this : parentNode),
31       size(std::numeric_limits<size_t>::max()),
32       interesting(Tester::Interestingness::Untested), ranges(ranges),
33       startRanges(ranges), allocator(allocator) {
34   if (parent != this)
35     if (failed(initialize(parent->getModule(), parent->getRegion())))
36       llvm_unreachable("unexpected initialization failure");
37 }
38 
39 LogicalResult ReductionNode::initialize(ModuleOp parentModule,
40                                         Region &targetRegion) {
41   // Use the mapper help us find the corresponding region after module clone.
42   BlockAndValueMapping mapper;
43   module = cast<ModuleOp>(parentModule->clone(mapper));
44   // Use the first block of targetRegion to locate the cloned region.
45   Block *block = mapper.lookup(&*targetRegion.begin());
46   region = block->getParent();
47   return success();
48 }
49 
50 /// If we haven't explored any variants from this node, we will create N
51 /// variants, N is the length of `ranges` if N > 1. Otherwise, we will split the
52 /// max element in `ranges` and create 2 new variants for each call.
53 ArrayRef<ReductionNode *> ReductionNode::generateNewVariants() {
54   int oldNumVariant = getVariants().size();
55 
56   auto createNewNode = [this](std::vector<Range> ranges) {
57     return new (allocator.Allocate())
58         ReductionNode(this, std::move(ranges), allocator);
59   };
60 
61   // If we haven't created new variant, then we can create varients by removing
62   // each of them respectively. For example, given {{1, 3}, {4, 9}}, we can
63   // produce variants with range {{1, 3}} and {{4, 9}}.
64   if (variants.size() == 0 && getRanges().size() > 1) {
65     for (const Range &range : getRanges()) {
66       std::vector<Range> subRanges = getRanges();
67       llvm::erase_value(subRanges, range);
68       variants.push_back(createNewNode(std::move(subRanges)));
69     }
70 
71     return getVariants().drop_front(oldNumVariant);
72   }
73 
74   // At here, we have created the type of variants mentioned above. We would
75   // like to split the max range into 2 to create 2 new variants. Continue on
76   // the above example, we split the range {4, 9} into {4, 6}, {6, 9}, and
77   // create two variants with range {{1, 3}, {4, 6}} and {{1, 3}, {6, 9}}. The
78   // final ranges vector will be {{1, 3}, {4, 6}, {6, 9}}.
79   auto maxElement = std::max_element(
80       ranges.begin(), ranges.end(), [](const Range &lhs, const Range &rhs) {
81         return (lhs.second - lhs.first) > (rhs.second - rhs.first);
82       });
83 
84   // The length of range is less than 1, we can't split it to create new
85   // variant.
86   if (maxElement->second - maxElement->first <= 1)
87     return {};
88 
89   Range maxRange = *maxElement;
90   std::vector<Range> subRanges = getRanges();
91   auto subRangesIter = subRanges.begin() + (maxElement - ranges.begin());
92   int half = (maxRange.first + maxRange.second) / 2;
93   *subRangesIter = std::make_pair(maxRange.first, half);
94   variants.push_back(createNewNode(subRanges));
95   *subRangesIter = std::make_pair(half, maxRange.second);
96   variants.push_back(createNewNode(std::move(subRanges)));
97 
98   auto it = ranges.insert(maxElement, std::make_pair(half, maxRange.second));
99   it = ranges.insert(it, std::make_pair(maxRange.first, half));
100   // Remove the range that has been split.
101   ranges.erase(it + 2);
102 
103   return getVariants().drop_front(oldNumVariant);
104 }
105 
106 void ReductionNode::update(std::pair<Tester::Interestingness, size_t> result) {
107   std::tie(interesting, size) = result;
108   // After applying reduction, the number of operation in the region may have
109   // changed. Non-interesting case won't be explored thus it's safe to keep it
110   // in a stale status.
111   if (interesting == Tester::Interestingness::True) {
112     // This module may has been updated. Reset the range.
113     ranges.clear();
114     ranges.push_back({0, std::distance(region->op_begin(), region->op_end())});
115   }
116 }
117 
118 ArrayRef<ReductionNode *>
119 ReductionNode::iterator<SinglePath>::getNeighbors(ReductionNode *node) {
120   // Single Path: Traverses the smallest successful variant at each level until
121   // no new successful variants can be created at that level.
122   ArrayRef<ReductionNode *> variantsFromParent =
123       node->getParent()->getVariants();
124 
125   // The parent node created several variants and they may be waiting for
126   // examing interestingness. In Single Path approach, we will select the
127   // smallest variant to continue our exploration. Thus we should wait until the
128   // last variant to be examed then do the following traversal decision.
129   if (!llvm::all_of(variantsFromParent, [](ReductionNode *node) {
130         return node->isInteresting() != Tester::Interestingness::Untested;
131       })) {
132     return {};
133   }
134 
135   ReductionNode *smallest = nullptr;
136   for (ReductionNode *node : variantsFromParent) {
137     if (node->isInteresting() != Tester::Interestingness::True)
138       continue;
139     if (smallest == nullptr || node->getSize() < smallest->getSize())
140       smallest = node;
141   }
142 
143   if (smallest != nullptr &&
144       smallest->getSize() < node->getParent()->getSize()) {
145     // We got a smallest one, keep traversing from this node.
146     node = smallest;
147   } else {
148     // None of these variants is interesting, let the parent node to generate
149     // more variants.
150     node = node->getParent();
151   }
152 
153   return node->generateNewVariants();
154 }
155