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