MLIR 22.0.0git
Block.h
Go to the documentation of this file.
1//===- Block.h - MLIR Block Class -------------------------------*- C++ -*-===//
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 Block class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_IR_BLOCK_H
14#define MLIR_IR_BLOCK_H
15
17#include "mlir/IR/Visitors.h"
18
19#include "llvm/ADT/SmallPtrSet.h"
20
21namespace llvm {
22class BitVector;
23class raw_ostream;
24} // namespace llvm
25
26namespace mlir {
27class TypeRange;
28template <typename ValueRangeT>
29class ValueTypeRange;
30
31/// `Block` represents an ordered list of `Operation`s.
32class alignas(8) Block : public IRObjectWithUseList<BlockOperand>,
33 public llvm::ilist_node_with_parent<Block, Region> {
34public:
35 explicit Block() = default;
36 ~Block();
37
38 void clear() {
39 // Drop all references from within this block.
41
42 // Clear operations in the reverse order so that uses are destroyed
43 // before their defs.
44 while (!empty())
45 operations.pop_back();
46 }
47
48 /// Provide a 'getParent' method for ilist_node_with_parent methods.
49 /// We mark it as a const function because ilist_node_with_parent specifically
50 /// requires a 'getParent() const' method. Once ilist_node removes this
51 /// constraint, we should drop the const to fit the rest of the MLIR const
52 /// model.
53 Region *getParent() const;
54
55 /// Returns the closest surrounding operation that contains this block.
57
58 /// Return if this block is the entry block in the parent region.
59 bool isEntryBlock();
60
61 /// Insert this block (which must not already be in a region) right before
62 /// the specified block.
63 void insertBefore(Block *block);
64
65 /// Insert this block (which must not already be in a region) right after
66 /// the specified block.
67 void insertAfter(Block *block);
68
69 /// Unlink this block from its current region and insert it right before the
70 /// specific block.
71 void moveBefore(Block *block);
72
73 /// Unlink this block from its current region and insert it right before the
74 /// block that the given iterator points to in the region region.
75 void moveBefore(Region *region, llvm::iplist<Block>::iterator iterator);
76
77 /// Unlink this Block from its parent region and delete it.
78 void erase();
79
80 //===--------------------------------------------------------------------===//
81 // Block argument management
82 //===--------------------------------------------------------------------===//
83
84 // This is the list of arguments to the block.
86
87 BlockArgListType getArguments() { return arguments; }
88
89 /// Return a range containing the types of the arguments for this block.
91
92 using args_iterator = BlockArgListType::iterator;
93 using reverse_args_iterator = BlockArgListType::reverse_iterator;
94 args_iterator args_begin() { return getArguments().begin(); }
95 args_iterator args_end() { return getArguments().end(); }
98
99 bool args_empty() { return arguments.empty(); }
100
101 /// Add one value to the argument list.
103
104 /// Insert one value to the position in the argument list indicated by the
105 /// given iterator. The existing arguments are shifted. The block is expected
106 /// not to have predecessors.
108
109 /// Add one argument to the argument list for each type specified in the list.
110 /// `locs` is required to have the same number of elements as `types`.
112 ArrayRef<Location> locs);
113
114 /// Add one value to the argument list at the specified position.
115 BlockArgument insertArgument(unsigned index, Type type, Location loc);
116
117 /// Erase the argument at 'index' and remove it from the argument list.
118 void eraseArgument(unsigned index);
119 /// Erases 'num' arguments from the index 'start'.
120 void eraseArguments(unsigned start, unsigned num);
121 /// Erases the arguments that have their corresponding bit set in
122 /// `eraseIndices` and removes them from the argument list.
123 void eraseArguments(const BitVector &eraseIndices);
124 /// Erases arguments using the given predicate. If the predicate returns true,
125 /// that argument is erased.
126 void eraseArguments(function_ref<bool(BlockArgument)> shouldEraseFn);
127
128 unsigned getNumArguments() { return arguments.size(); }
129 BlockArgument getArgument(unsigned i) { return arguments[i]; }
130
131 //===--------------------------------------------------------------------===//
132 // Operation list management
133 //===--------------------------------------------------------------------===//
134
135 /// This is the list of operations in the block.
136 using OpListType = llvm::iplist<Operation>;
137 OpListType &getOperations() { return operations; }
138
139 // Iteration over the operations in the block.
140 using iterator = OpListType::iterator;
141 using reverse_iterator = OpListType::reverse_iterator;
142
143 iterator begin() { return operations.begin(); }
144 iterator end() { return operations.end(); }
145 reverse_iterator rbegin() { return operations.rbegin(); }
146 reverse_iterator rend() { return operations.rend(); }
147
148 bool empty() { return operations.empty(); }
149 void push_back(Operation *op) { operations.push_back(op); }
150 void push_front(Operation *op) { operations.push_front(op); }
151
152 Operation &back() { return operations.back(); }
153 Operation &front() { return operations.front(); }
154
155 /// Returns 'op' if 'op' lies in this block, or otherwise finds the
156 /// ancestor operation of 'op' that lies in this block. Returns nullptr if
157 /// the latter fails.
158 /// TODO: This is very specific functionality that should live somewhere else,
159 /// probably in Dominance.cpp.
161
162 /// This drops all operand uses from operations within this block, which is
163 /// an essential step in breaking cyclic dependences between references when
164 /// they are to be deleted.
165 void dropAllReferences();
166
167 /// This drops all uses of values defined in this block or in the blocks of
168 /// nested regions wherever the uses are located.
170
171 /// Returns true if the ordering of the child operations is valid, false
172 /// otherwise.
173 bool isOpOrderValid();
174
175 /// Invalidates the current ordering of operations.
176 void invalidateOpOrder();
177
178 /// Verifies the current ordering of child operations matches the
179 /// validOpOrder flag. Returns false if the order is valid, true otherwise.
180 bool verifyOpOrder();
181
182 /// Recomputes the ordering of child operations within the block.
183 void recomputeOpOrder();
184
185 /// This class provides iteration over the held operations of a block for a
186 /// specific operation type.
187 template <typename OpT>
189
190 /// Return an iterator range over the operations within this block that are of
191 /// 'OpT'.
192 template <typename OpT>
198 template <typename OpT>
202 template <typename OpT>
206
207 /// Return an iterator range over the operation within this block excluding
208 /// the terminator operation at the end. If the block has no terminator,
209 /// return an iterator range over the entire block. If it is unknown if the
210 /// block has a terminator (i.e., last block operation is unregistered), also
211 /// return an iterator range over the entire block.
213 if (begin() == end())
214 return {begin(), end()};
215 return without_terminator_impl();
216 }
217
218 //===--------------------------------------------------------------------===//
219 // Terminator management
220 //===--------------------------------------------------------------------===//
221
222 /// Get the terminator operation of this block. This function asserts that
223 /// the block might have a valid terminator operation.
225
226 /// Return "true" if this block might have a terminator. Return "true" if
227 /// the last operation is unregistered.
228 bool mightHaveTerminator();
229
230 //===--------------------------------------------------------------------===//
231 // Predecessors and successors.
232 //===--------------------------------------------------------------------===//
233
234 // Predecessor iteration.
239 pred_iterator pred_end() { return pred_iterator(nullptr); }
243
244 /// Return true if this block has no predecessors.
245 bool hasNoPredecessors() { return pred_begin() == pred_end(); }
246
247 /// Returns true if this blocks has no successors.
248 bool hasNoSuccessors() { return succ_begin() == succ_end(); }
249
250 /// If this block has exactly one predecessor, return it. Otherwise, return
251 /// null.
252 ///
253 /// Note that if a block has duplicate predecessors from a single block (e.g.
254 /// if you have a conditional branch with the same block as the true/false
255 /// destinations) is not considered to be a single predecessor.
257
258 /// If this block has a unique predecessor, i.e., all incoming edges originate
259 /// from one block, return it. Otherwise, return null.
261
262 // Indexed successor access.
263 unsigned getNumSuccessors();
264 Block *getSuccessor(unsigned i);
265
266 // Successor iteration.
267 using succ_iterator = SuccessorRange::iterator;
268 succ_iterator succ_begin() { return getSuccessors().begin(); }
271
272 /// Return "true" if there is a path from this block to the given block
273 /// (according to the successors relationship). Both blocks must be in the
274 /// same region. Paths that contain a block from `except` do not count.
275 /// This function returns "false" if `other` is in `except`.
276 ///
277 /// Note: This function performs a block graph traversal and its complexity
278 /// linear in the number of blocks in the parent region.
279 ///
280 /// Note: Reachability is a necessary but insufficient condition for
281 /// dominance. Do not use this function in places where you need to check for
282 /// dominance.
283 bool isReachable(Block *other, SmallPtrSet<Block *, 16> &&except = {});
284
285 //===--------------------------------------------------------------------===//
286 // Walkers
287 //===--------------------------------------------------------------------===//
288
289 /// Walk all nested operations, blocks (including this block) or regions,
290 /// depending on the type of callback.
291 ///
292 /// The order in which operations, blocks or regions at the same nesting
293 /// level are visited (e.g., lexicographical or reverse lexicographical order)
294 /// is determined by `Iterator`. The walk order for enclosing operations,
295 /// blocks or regions with respect to their nested ones is specified by
296 /// `Order` (post-order by default).
297 ///
298 /// A callback on a operation or block is allowed to erase that operation or
299 /// block if either:
300 /// * the walk is in post-order, or
301 /// * the walk is in pre-order and the walk is skipped after the erasure.
302 ///
303 /// See Operation::walk for more details.
304 template <WalkOrder Order = WalkOrder::PostOrder,
305 typename Iterator = ForwardIterator, typename FnT,
306 typename ArgT = detail::first_argument<FnT>,
307 typename RetT = detail::walkResultType<FnT>>
308 RetT walk(FnT &&callback) {
309 if constexpr (std::is_same<ArgT, Block *>::value &&
310 Order == WalkOrder::PreOrder) {
311 // Pre-order walk on blocks: invoke the callback on this block.
312 if constexpr (std::is_same<RetT, void>::value) {
313 callback(this);
314 } else {
315 RetT result = callback(this);
316 if (result.wasSkipped())
317 return WalkResult::advance();
318 if (result.wasInterrupted())
319 return WalkResult::interrupt();
320 }
321 }
322
323 // Walk nested operations, blocks or regions.
324 if constexpr (std::is_same<RetT, void>::value) {
325 walk<Order, Iterator>(begin(), end(), std::forward<FnT>(callback));
326 } else {
327 if (walk<Order, Iterator>(begin(), end(), std::forward<FnT>(callback))
328 .wasInterrupted())
329 return WalkResult::interrupt();
330 }
331
332 if constexpr (std::is_same<ArgT, Block *>::value &&
333 Order == WalkOrder::PostOrder) {
334 // Post-order walk on blocks: invoke the callback on this block.
335 return callback(this);
336 }
337 if constexpr (!std::is_same<RetT, void>::value)
338 return WalkResult::advance();
339 }
340
341 /// Walk all nested operations, blocks (excluding this block) or regions,
342 /// depending on the type of callback, in the specified [begin, end) range of
343 /// this block.
344 ///
345 /// The order in which operations, blocks or regions at the same nesting
346 /// level are visited (e.g., lexicographical or reverse lexicographical order)
347 /// is determined by `Iterator`. The walk order for enclosing operations,
348 /// blocks or regions with respect to their nested ones is specified by
349 /// `Order` (post-order by default).
350 ///
351 /// A callback on a operation or block is allowed to erase that operation or
352 /// block if either:
353 /// * the walk is in post-order, or
354 /// * the walk is in pre-order and the walk is skipped after the erasure.
355 ///
356 /// See Operation::walk for more details.
357 template <WalkOrder Order = WalkOrder::PostOrder,
358 typename Iterator = ForwardIterator, typename FnT,
359 typename RetT = detail::walkResultType<FnT>>
361 for (auto &op : llvm::make_early_inc_range(llvm::make_range(begin, end))) {
362 if constexpr (std::is_same<RetT, WalkResult>::value) {
363 if (detail::walk<Order, Iterator>(&op, callback).wasInterrupted())
364 return WalkResult::interrupt();
365 } else {
366 detail::walk<Order, Iterator>(&op, callback);
367 }
368 }
369 if constexpr (std::is_same<RetT, WalkResult>::value)
370 return WalkResult::advance();
371 }
372
373 //===--------------------------------------------------------------------===//
374 // Other
375 //===--------------------------------------------------------------------===//
376
377 /// Split the block into two blocks before the specified operation or
378 /// iterator.
379 ///
380 /// Note that all operations BEFORE the specified iterator stay as part of
381 /// the original basic block, and the rest of the operations in the original
382 /// block are moved to the new block, including the old terminator. The
383 /// original block is left without a terminator.
384 ///
385 /// The newly formed Block is returned, and the specified iterator is
386 /// invalidated.
387 Block *splitBlock(iterator splitBefore);
388 Block *splitBlock(Operation *splitBeforeOp) {
389 return splitBlock(iterator(splitBeforeOp));
390 }
391
392 /// Returns pointer to member of operation list.
394 return &Block::operations;
395 }
396
397 void print(raw_ostream &os);
398 void print(raw_ostream &os, AsmState &state);
399 void dump();
400
401 /// Print out the name of the block without printing its body.
402 /// NOTE: The printType argument is ignored. We keep it for compatibility
403 /// with LLVM dominator machinery that expects it to exist.
404 void printAsOperand(raw_ostream &os, bool printType = true);
405 void printAsOperand(raw_ostream &os, AsmState &state);
406
407private:
408 /// Same as `without_terminator`, but assumes that the block is not empty.
409 iterator_range<iterator> without_terminator_impl();
410
411 /// Pair of the parent object that owns this block and a bit that signifies if
412 /// the operations within this block have a valid ordering.
413 llvm::PointerIntPair<Region *, /*IntBits=*/1, bool> parentValidOpOrderPair;
414
415 /// This is the list of operations in the block.
416 OpListType operations;
417
418 /// This is the list of arguments to the block.
419 std::vector<BlockArgument> arguments;
420
421 Block(Block &) = delete;
422 void operator=(Block &) = delete;
423
424 friend struct llvm::ilist_traits<Block>;
425};
426
428} // namespace mlir
429
430namespace llvm {
431template <>
432struct DenseMapInfo<mlir::Block::iterator> {
441 static unsigned getHashValue(mlir::Block::iterator iter) {
442 return hash_value(iter.getNodePtr());
443 }
445 return lhs == rhs;
446 }
447};
448
449} // end namespace llvm
450
451#endif // MLIR_IR_BLOCK_H
lhs
This class provides management for the lifetime of the state used when printing the IR.
Definition AsmState.h:542
This class represents an argument of a Block.
Definition Value.h:309
A block operand represents an operand that holds a reference to a Block, e.g.
Block represents an ordered list of Operations.
Definition Block.h:33
void recomputeOpOrder()
Recomputes the ordering of child operations within the block.
Definition Block.cpp:136
MutableArrayRef< BlockArgument > BlockArgListType
Definition Block.h:85
OpListType::iterator iterator
Definition Block.h:140
Operation * findAncestorOpInBlock(Operation &op)
Returns 'op' if 'op' lies in this block, or otherwise finds the ancestor operation of 'op' that lies ...
Definition Block.cpp:74
ValueTypeRange< BlockArgListType > getArgumentTypes()
Return a range containing the types of the arguments for this block.
Definition Block.cpp:149
unsigned getNumSuccessors()
Definition Block.cpp:265
void push_front(Operation *op)
Definition Block.h:150
SuccessorRange::iterator succ_iterator
Definition Block.h:267
bool empty()
Definition Block.h:148
BlockArgument getArgument(unsigned i)
Definition Block.h:129
bool hasNoSuccessors()
Returns true if this blocks has no successors.
Definition Block.h:248
unsigned getNumArguments()
Definition Block.h:128
iterator_range< pred_iterator > getPredecessors()
Definition Block.h:240
op_iterator< OpT > op_begin()
Definition Block.h:199
void erase()
Unlink this Block from its parent region and delete it.
Definition Block.cpp:66
iterator_range< op_iterator< OpT > > getOps()
Return an iterator range over the operations within this block that are of 'OpT'.
Definition Block.h:193
detail::op_iterator< OpT, iterator > op_iterator
This class provides iteration over the held operations of a block for a specific operation type.
Definition Block.h:188
BlockArgument insertArgument(args_iterator it, Type type, Location loc)
Insert one value to the position in the argument list indicated by the given iterator.
Definition Block.cpp:187
iterator_range< args_iterator > addArguments(TypeRange types, ArrayRef< Location > locs)
Add one argument to the argument list for each type specified in the list.
Definition Block.cpp:160
Block * splitBlock(iterator splitBefore)
Split the block into two blocks before the specified operation or iterator.
Definition Block.cpp:318
Block()=default
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition Block.cpp:27
bool isOpOrderValid()
Returns true if the ordering of the child operations is valid, false otherwise.
Definition Block.cpp:104
OpListType & getOperations()
Definition Block.h:137
BlockArgListType::reverse_iterator reverse_args_iterator
Definition Block.h:93
args_iterator args_end()
Definition Block.h:95
Operation & front()
Definition Block.h:153
succ_iterator succ_end()
Definition Block.h:269
pred_iterator pred_begin()
Definition Block.h:236
void dropAllDefinedValueUses()
This drops all uses of values defined in this block or in the blocks of nested regions wherever the u...
Definition Block.cpp:94
bool verifyOpOrder()
Verifies the current ordering of child operations matches the validOpOrder flag.
Definition Block.cpp:115
SuccessorRange getSuccessors()
Definition Block.h:270
Operation & back()
Definition Block.h:152
void invalidateOpOrder()
Invalidates the current ordering of operations.
Definition Block.cpp:107
Block * getSinglePredecessor()
If this block has exactly one predecessor, return it.
Definition Block.cpp:280
void printAsOperand(raw_ostream &os, bool printType=true)
Print out the name of the block without printing its body.
reverse_args_iterator args_rend()
Definition Block.h:97
RetT walk(FnT &&callback)
Walk all nested operations, blocks (including this block) or regions, depending on the type of callba...
Definition Block.h:308
void insertAfter(Block *block)
Insert this block (which must not already be in a region) right after the specified block.
Definition Block.cpp:46
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:244
succ_iterator succ_begin()
Definition Block.h:268
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition Block.cpp:153
RetT walk(Block::iterator begin, Block::iterator end, FnT &&callback)
Walk all nested operations, blocks (excluding this block) or regions, depending on the type of callba...
Definition Block.h:360
void clear()
Definition Block.h:38
void eraseArguments(unsigned start, unsigned num)
Erases 'num' arguments from the index 'start'.
Definition Block.cpp:201
reverse_iterator rend()
Definition Block.h:146
void print(raw_ostream &os)
bool args_empty()
Definition Block.h:99
bool mightHaveTerminator()
Return "true" if this block might have a terminator.
Definition Block.cpp:250
BlockArgListType getArguments()
Definition Block.h:87
PredecessorIterator pred_iterator
Definition Block.h:235
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
Definition Block.h:212
op_iterator< OpT > op_end()
Definition Block.h:203
bool isReachable(Block *other, SmallPtrSet< Block *, 16 > &&except={})
Return "true" if there is a path from this block to the given block (according to the successors rela...
Definition Block.cpp:363
iterator end()
Definition Block.h:144
iterator begin()
Definition Block.h:143
Block * getUniquePredecessor()
If this block has a unique predecessor, i.e., all incoming edges originate from one block,...
Definition Block.cpp:291
void eraseArgument(unsigned index)
Erase the argument at 'index' and remove it from the argument list.
Definition Block.cpp:193
Block * getSuccessor(unsigned i)
Definition Block.cpp:269
args_iterator args_begin()
Definition Block.h:94
bool isEntryBlock()
Return if this block is the entry block in the parent region.
Definition Block.cpp:36
void dropAllReferences()
This drops all operand uses from operations within this block, which is an essential step in breaking...
Definition Block.cpp:89
Block * splitBlock(Operation *splitBeforeOp)
Definition Block.h:388
void insertBefore(Block *block)
Insert this block (which must not already be in a region) right before the specified block.
Definition Block.cpp:40
pred_iterator pred_end()
Definition Block.h:239
void moveBefore(Block *block)
Unlink this block from its current region and insert it right before the specific block.
Definition Block.cpp:54
void push_back(Operation *op)
Definition Block.h:149
reverse_args_iterator args_rbegin()
Definition Block.h:96
bool hasNoPredecessors()
Return true if this block has no predecessors.
Definition Block.h:245
static OpListType Block::* getSublistAccess(Operation *)
Returns pointer to member of operation list.
Definition Block.h:393
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
BlockArgListType::iterator args_iterator
Definition Block.h:92
reverse_iterator rbegin()
Definition Block.h:145
OpListType::reverse_iterator reverse_iterator
Definition Block.h:141
llvm::iplist< Operation > OpListType
This is the list of operations in the block.
Definition Block.h:136
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
Implement a predecessor iterator for blocks.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class implements the successor iterators for Block.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:37
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class implements iteration on the types of a given range of values.
Definition TypeRange.h:135
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
A utility iterator that filters out operations that are not 'OpT'.
This class provides iteration over the held operations of a block for a specific operation type.
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
void walk(Operation *op, function_ref< void(Region *)> callback, WalkOrder order)
Walk all of the regions, blocks, or operations nested under (and including) the given operation.
Definition Visitors.h:102
decltype(first_argument_type(std::declval< T >())) first_argument
Type definition of the first argument to the given callable 'T'.
Definition Visitors.h:90
decltype(walk(nullptr, std::declval< FnT >())) walkResultType
Utility to provide the return type of a templated walk method.
Definition Visitors.h:431
Include the generated interface declarations.
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)
WalkOrder
Traversal order for region, block and operation walk utilities.
Definition Visitors.h:28
llvm::function_ref< Fn > function_ref
Definition LLVM.h:152
static mlir::Block::iterator getEmptyKey()
Definition Block.h:433
static bool isEqual(mlir::Block::iterator lhs, mlir::Block::iterator rhs)
Definition Block.h:444
static mlir::Block::iterator getTombstoneKey()
Definition Block.h:437
static unsigned getHashValue(mlir::Block::iterator iter)
Definition Block.h:441
This iterator enumerates the elements in "forward" order.
Definition Visitors.h:31