xref: /llvm-project-15.0.7/mlir/lib/IR/Block.cpp (revision bb09ef95)
1 //===- Block.cpp - MLIR Block Class ---------------------------------------===//
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 #include "mlir/IR/Block.h"
10 #include "mlir/IR/Builders.h"
11 #include "mlir/IR/Operation.h"
12 using namespace mlir;
13 
14 //===----------------------------------------------------------------------===//
15 // BlockArgument
16 //===----------------------------------------------------------------------===//
17 
18 /// Returns the number of this argument.
19 unsigned BlockArgument::getArgNumber() const {
20   // Arguments are not stored in place, so we have to find it within the list.
21   auto argList = getOwner()->getArguments();
22   return std::distance(argList.begin(), llvm::find(argList, *this));
23 }
24 
25 //===----------------------------------------------------------------------===//
26 // Block
27 //===----------------------------------------------------------------------===//
28 
29 Block::~Block() {
30   assert(!verifyOpOrder() && "Expected valid operation ordering.");
31   clear();
32   for (BlockArgument arg : arguments)
33     arg.destroy();
34 }
35 
36 Region *Block::getParent() const { return parentValidOpOrderPair.getPointer(); }
37 
38 /// Returns the closest surrounding operation that contains this block or
39 /// nullptr if this block is unlinked.
40 Operation *Block::getParentOp() {
41   return getParent() ? getParent()->getParentOp() : nullptr;
42 }
43 
44 /// Return if this block is the entry block in the parent region.
45 bool Block::isEntryBlock() { return this == &getParent()->front(); }
46 
47 /// Insert this block (which must not already be in a region) right before the
48 /// specified block.
49 void Block::insertBefore(Block *block) {
50   assert(!getParent() && "already inserted into a block!");
51   assert(block->getParent() && "cannot insert before a block without a parent");
52   block->getParent()->getBlocks().insert(block->getIterator(), this);
53 }
54 
55 /// Unlink this block from its current region and insert it right before the
56 /// specific block.
57 void Block::moveBefore(Block *block) {
58   assert(block->getParent() && "cannot insert before a block without a parent");
59   block->getParent()->getBlocks().splice(
60       block->getIterator(), getParent()->getBlocks(), getIterator());
61 }
62 
63 /// Unlink this Block from its parent Region and delete it.
64 void Block::erase() {
65   assert(getParent() && "Block has no parent");
66   getParent()->getBlocks().erase(this);
67 }
68 
69 /// Returns 'op' if 'op' lies in this block, or otherwise finds the
70 /// ancestor operation of 'op' that lies in this block. Returns nullptr if
71 /// the latter fails.
72 Operation *Block::findAncestorOpInBlock(Operation &op) {
73   // Traverse up the operation hierarchy starting from the owner of operand to
74   // find the ancestor operation that resides in the block of 'forOp'.
75   auto *currOp = &op;
76   while (currOp->getBlock() != this) {
77     currOp = currOp->getParentOp();
78     if (!currOp)
79       return nullptr;
80   }
81   return currOp;
82 }
83 
84 /// This drops all operand uses from operations within this block, which is
85 /// an essential step in breaking cyclic dependences between references when
86 /// they are to be deleted.
87 void Block::dropAllReferences() {
88   for (Operation &i : *this)
89     i.dropAllReferences();
90 }
91 
92 void Block::dropAllDefinedValueUses() {
93   for (auto arg : getArguments())
94     arg.dropAllUses();
95   for (auto &op : *this)
96     op.dropAllDefinedValueUses();
97   dropAllUses();
98 }
99 
100 /// Returns true if the ordering of the child operations is valid, false
101 /// otherwise.
102 bool Block::isOpOrderValid() { return parentValidOpOrderPair.getInt(); }
103 
104 /// Invalidates the current ordering of operations.
105 void Block::invalidateOpOrder() {
106   // Validate the current ordering.
107   assert(!verifyOpOrder());
108   parentValidOpOrderPair.setInt(false);
109 }
110 
111 /// Verifies the current ordering of child operations. Returns false if the
112 /// order is valid, true otherwise.
113 bool Block::verifyOpOrder() {
114   // The order is already known to be invalid.
115   if (!isOpOrderValid())
116     return false;
117   // The order is valid if there are less than 2 operations.
118   if (operations.empty() || std::next(operations.begin()) == operations.end())
119     return false;
120 
121   Operation *prev = nullptr;
122   for (auto &i : *this) {
123     // The previous operation must have a smaller order index than the next as
124     // it appears earlier in the list.
125     if (prev && prev->orderIndex != Operation::kInvalidOrderIdx &&
126         prev->orderIndex >= i.orderIndex)
127       return true;
128     prev = &i;
129   }
130   return false;
131 }
132 
133 /// Recomputes the ordering of child operations within the block.
134 void Block::recomputeOpOrder() {
135   parentValidOpOrderPair.setInt(true);
136 
137   unsigned orderIndex = 0;
138   for (auto &op : *this)
139     op.orderIndex = (orderIndex += Operation::kOrderStride);
140 }
141 
142 //===----------------------------------------------------------------------===//
143 // Argument list management.
144 //===----------------------------------------------------------------------===//
145 
146 /// Return a range containing the types of the arguments for this block.
147 auto Block::getArgumentTypes() -> ValueTypeRange<BlockArgListType> {
148   return ValueTypeRange<BlockArgListType>(getArguments());
149 }
150 
151 BlockArgument Block::addArgument(Type type) {
152   BlockArgument arg = BlockArgument::create(type, this);
153   arguments.push_back(arg);
154   return arg;
155 }
156 
157 /// Add one argument to the argument list for each type specified in the list.
158 auto Block::addArguments(TypeRange types) -> iterator_range<args_iterator> {
159   size_t initialSize = arguments.size();
160   arguments.reserve(initialSize + types.size());
161   for (auto type : types)
162     addArgument(type);
163   return {arguments.data() + initialSize, arguments.data() + arguments.size()};
164 }
165 
166 BlockArgument Block::insertArgument(unsigned index, Type type) {
167   auto arg = BlockArgument::create(type, this);
168   assert(index <= arguments.size());
169   arguments.insert(arguments.begin() + index, arg);
170   return arg;
171 }
172 
173 void Block::eraseArgument(unsigned index) {
174   assert(index < arguments.size());
175   arguments[index].destroy();
176   arguments.erase(arguments.begin() + index);
177 }
178 
179 /// Insert one value to the given position of the argument list. The existing
180 /// arguments are shifted. The block is expected not to have predecessors.
181 BlockArgument Block::insertArgument(args_iterator it, Type type) {
182   assert(llvm::empty(getPredecessors()) &&
183          "cannot insert arguments to blocks with predecessors");
184 
185   // Use the args_iterator (on the BlockArgListType) to compute the insertion
186   // iterator in the underlying argument storage.
187   size_t distance = std::distance(args_begin(), it);
188   auto arg = BlockArgument::create(type, this);
189   arguments.insert(std::next(arguments.begin(), distance), arg);
190   return arg;
191 }
192 
193 //===----------------------------------------------------------------------===//
194 // Terminator management
195 //===----------------------------------------------------------------------===//
196 
197 /// Get the terminator operation of this block. This function asserts that
198 /// the block has a valid terminator operation.
199 Operation *Block::getTerminator() {
200   assert(!empty() && !back().isKnownNonTerminator());
201   return &back();
202 }
203 
204 // Indexed successor access.
205 unsigned Block::getNumSuccessors() {
206   return empty() ? 0 : back().getNumSuccessors();
207 }
208 
209 Block *Block::getSuccessor(unsigned i) {
210   assert(i < getNumSuccessors());
211   return getTerminator()->getSuccessor(i);
212 }
213 
214 /// If this block has exactly one predecessor, return it.  Otherwise, return
215 /// null.
216 ///
217 /// Note that multiple edges from a single block (e.g. if you have a cond
218 /// branch with the same block as the true/false destinations) is not
219 /// considered to be a single predecessor.
220 Block *Block::getSinglePredecessor() {
221   auto it = pred_begin();
222   if (it == pred_end())
223     return nullptr;
224   auto *firstPred = *it;
225   ++it;
226   return it == pred_end() ? firstPred : nullptr;
227 }
228 
229 /// If this block has a unique predecessor, i.e., all incoming edges originate
230 /// from one block, return it. Otherwise, return null.
231 Block *Block::getUniquePredecessor() {
232   auto it = pred_begin(), e = pred_end();
233   if (it == e)
234     return nullptr;
235 
236   // Check for any conflicting predecessors.
237   auto *firstPred = *it;
238   for (++it; it != e; ++it)
239     if (*it != firstPred)
240       return nullptr;
241   return firstPred;
242 }
243 
244 //===----------------------------------------------------------------------===//
245 // Other
246 //===----------------------------------------------------------------------===//
247 
248 /// Split the block into two blocks before the specified operation or
249 /// iterator.
250 ///
251 /// Note that all operations BEFORE the specified iterator stay as part of
252 /// the original basic block, and the rest of the operations in the original
253 /// block are moved to the new block, including the old terminator.  The
254 /// original block is left without a terminator.
255 ///
256 /// The newly formed Block is returned, and the specified iterator is
257 /// invalidated.
258 Block *Block::splitBlock(iterator splitBefore) {
259   // Start by creating a new basic block, and insert it immediate after this
260   // one in the containing region.
261   auto newBB = new Block();
262   getParent()->getBlocks().insert(std::next(Region::iterator(this)), newBB);
263 
264   // Move all of the operations from the split point to the end of the region
265   // into the new block.
266   newBB->getOperations().splice(newBB->end(), getOperations(), splitBefore,
267                                 end());
268   return newBB;
269 }
270 
271 //===----------------------------------------------------------------------===//
272 // Predecessors
273 //===----------------------------------------------------------------------===//
274 
275 Block *PredecessorIterator::unwrap(BlockOperand &value) {
276   return value.getOwner()->getBlock();
277 }
278 
279 /// Get the successor number in the predecessor terminator.
280 unsigned PredecessorIterator::getSuccessorIndex() const {
281   return I->getOperandNumber();
282 }
283 
284 //===----------------------------------------------------------------------===//
285 // SuccessorRange
286 //===----------------------------------------------------------------------===//
287 
288 SuccessorRange::SuccessorRange(Block *block) : SuccessorRange(nullptr, 0) {
289   if (Operation *term = block->getTerminator())
290     if ((count = term->getNumSuccessors()))
291       base = term->getBlockOperands().data();
292 }
293 
294 SuccessorRange::SuccessorRange(Operation *term) : SuccessorRange(nullptr, 0) {
295   if ((count = term->getNumSuccessors()))
296     base = term->getBlockOperands().data();
297 }
298 
299 //===----------------------------------------------------------------------===//
300 // BlockRange
301 //===----------------------------------------------------------------------===//
302 
303 BlockRange::BlockRange(ArrayRef<Block *> blocks) : BlockRange(nullptr, 0) {
304   if ((count = blocks.size()))
305     base = blocks.data();
306 }
307 
308 BlockRange::BlockRange(SuccessorRange successors)
309     : BlockRange(successors.begin().getBase(), successors.size()) {}
310 
311 /// See `llvm::detail::indexed_accessor_range_base` for details.
312 BlockRange::OwnerT BlockRange::offset_base(OwnerT object, ptrdiff_t index) {
313   if (auto *operand = object.dyn_cast<BlockOperand *>())
314     return {operand + index};
315   return {object.dyn_cast<Block *const *>() + index};
316 }
317 
318 /// See `llvm::detail::indexed_accessor_range_base` for details.
319 Block *BlockRange::dereference_iterator(OwnerT object, ptrdiff_t index) {
320   if (const auto *operand = object.dyn_cast<BlockOperand *>())
321     return operand[index].get();
322   return object.dyn_cast<Block *const *>()[index];
323 }
324