xref: /llvm-project-15.0.7/mlir/lib/IR/Region.cpp (revision 3d2c9069)
1 //===- Region.cpp - MLIR Region 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/Region.h"
10 #include "mlir/IR/BlockAndValueMapping.h"
11 #include "mlir/IR/Operation.h"
12 using namespace mlir;
13 
14 Region::Region(Operation *container) : container(container) {}
15 
16 Region::~Region() {
17   // Operations may have cyclic references, which need to be dropped before we
18   // can start deleting them.
19   dropAllReferences();
20 }
21 
22 /// Return the context this region is inserted in. The region must have a valid
23 /// parent container.
24 MLIRContext *Region::getContext() {
25   assert(container && "region is not attached to a container");
26   return container->getContext();
27 }
28 
29 /// Return a location for this region. This is the location attached to the
30 /// parent container. The region must have a valid parent container.
31 Location Region::getLoc() {
32   assert(container && "region is not attached to a container");
33   return container->getLoc();
34 }
35 
36 /// Return a range containing the types of the arguments for this region.
37 auto Region::getArgumentTypes() -> ValueTypeRange<BlockArgListType> {
38   return ValueTypeRange<BlockArgListType>(getArguments());
39 }
40 
41 /// Add one argument to the argument list for each type specified in the list.
42 iterator_range<Region::args_iterator> Region::addArguments(TypeRange types) {
43   return front().addArguments(types);
44 }
45 
46 Region *Region::getParentRegion() {
47   assert(container && "region is not attached to a container");
48   return container->getParentRegion();
49 }
50 
51 Operation *Region::getParentOp() { return container; }
52 
53 bool Region::isProperAncestor(Region *other) {
54   if (this == other)
55     return false;
56 
57   while ((other = other->getParentRegion())) {
58     if (this == other)
59       return true;
60   }
61   return false;
62 }
63 
64 /// Return the number of this region in the parent operation.
65 unsigned Region::getRegionNumber() {
66   // Regions are always stored consecutively, so use pointer subtraction to
67   // figure out what number this is.
68   return this - &getParentOp()->getRegions()[0];
69 }
70 
71 /// Clone the internal blocks from this region into `dest`. Any
72 /// cloned blocks are appended to the back of dest.
73 void Region::cloneInto(Region *dest, BlockAndValueMapping &mapper) {
74   assert(dest && "expected valid region to clone into");
75   cloneInto(dest, dest->end(), mapper);
76 }
77 
78 /// Clone this region into 'dest' before the given position in 'dest'.
79 void Region::cloneInto(Region *dest, Region::iterator destPos,
80                        BlockAndValueMapping &mapper) {
81   assert(dest && "expected valid region to clone into");
82   assert(this != dest && "cannot clone region into itself");
83 
84   // If the list is empty there is nothing to clone.
85   if (empty())
86     return;
87 
88   for (Block &block : *this) {
89     Block *newBlock = new Block();
90     mapper.map(&block, newBlock);
91 
92     // Clone the block arguments. The user might be deleting arguments to the
93     // block by specifying them in the mapper. If so, we don't add the
94     // argument to the cloned block.
95     for (auto arg : block.getArguments())
96       if (!mapper.contains(arg))
97         mapper.map(arg, newBlock->addArgument(arg.getType()));
98 
99     // Clone and remap the operations within this block.
100     for (auto &op : block)
101       newBlock->push_back(op.clone(mapper));
102 
103     dest->getBlocks().insert(destPos, newBlock);
104   }
105 
106   // Now that each of the blocks have been cloned, go through and remap the
107   // operands of each of the operations.
108   auto remapOperands = [&](Operation *op) {
109     for (auto &operand : op->getOpOperands())
110       if (auto mappedOp = mapper.lookupOrNull(operand.get()))
111         operand.set(mappedOp);
112     for (auto &succOp : op->getBlockOperands())
113       if (auto *mappedOp = mapper.lookupOrNull(succOp.get()))
114         succOp.set(mappedOp);
115   };
116 
117   for (iterator it(mapper.lookup(&front())); it != destPos; ++it)
118     it->walk(remapOperands);
119 }
120 
121 /// Returns 'block' if 'block' lies in this region, or otherwise finds the
122 /// ancestor of 'block' that lies in this region. Returns nullptr if the latter
123 /// fails.
124 Block *Region::findAncestorBlockInRegion(Block &block) {
125   Block *currBlock = &block;
126   while (currBlock->getParent() != this) {
127     Operation *parentOp = currBlock->getParentOp();
128     if (!parentOp || !parentOp->getBlock())
129       return nullptr;
130     currBlock = parentOp->getBlock();
131   }
132   return currBlock;
133 }
134 
135 /// Returns 'op' if 'op' lies in this region, or otherwise finds the
136 /// ancestor of 'op' that lies in this region. Returns nullptr if the
137 /// latter fails.
138 Operation *Region::findAncestorOpInRegion(Operation &op) {
139   Operation *curOp = &op;
140   while (Region *opRegion = curOp->getParentRegion()) {
141     if (opRegion == this)
142       return curOp;
143 
144     curOp = opRegion->getParentOp();
145     if (!curOp)
146       return nullptr;
147   }
148   return nullptr;
149 }
150 
151 void Region::dropAllReferences() {
152   for (Block &b : *this)
153     b.dropAllReferences();
154 }
155 
156 Region *llvm::ilist_traits<::mlir::Block>::getParentRegion() {
157   size_t Offset(
158       size_t(&((Region *)nullptr->*Region::getSublistAccess(nullptr))));
159   iplist<Block> *Anchor(static_cast<iplist<Block> *>(this));
160   return reinterpret_cast<Region *>(reinterpret_cast<char *>(Anchor) - Offset);
161 }
162 
163 /// This is a trait method invoked when a basic block is added to a region.
164 /// We keep the region pointer up to date.
165 void llvm::ilist_traits<::mlir::Block>::addNodeToList(Block *block) {
166   assert(!block->getParent() && "already in a region!");
167   block->parentValidOpOrderPair.setPointer(getParentRegion());
168 }
169 
170 /// This is a trait method invoked when an operation is removed from a
171 /// region.  We keep the region pointer up to date.
172 void llvm::ilist_traits<::mlir::Block>::removeNodeFromList(Block *block) {
173   assert(block->getParent() && "not already in a region!");
174   block->parentValidOpOrderPair.setPointer(nullptr);
175 }
176 
177 /// This is a trait method invoked when an operation is moved from one block
178 /// to another.  We keep the block pointer up to date.
179 void llvm::ilist_traits<::mlir::Block>::transferNodesFromList(
180     ilist_traits<Block> &otherList, block_iterator first, block_iterator last) {
181   // If we are transferring operations within the same function, the parent
182   // pointer doesn't need to be updated.
183   auto *curParent = getParentRegion();
184   if (curParent == otherList.getParentRegion())
185     return;
186 
187   // Update the 'parent' member of each Block.
188   for (; first != last; ++first)
189     first->parentValidOpOrderPair.setPointer(curParent);
190 }
191 
192 //===----------------------------------------------------------------------===//
193 // Region::OpIterator
194 //===----------------------------------------------------------------------===//
195 
196 Region::OpIterator::OpIterator(Region *region, bool end)
197     : region(region), block(end ? region->end() : region->begin()) {
198   if (!region->empty())
199     skipOverBlocksWithNoOps();
200 }
201 
202 Region::OpIterator &Region::OpIterator::operator++() {
203   // We increment over operations, if we reach the last use then move to next
204   // block.
205   if (operation != block->end())
206     ++operation;
207   if (operation == block->end()) {
208     ++block;
209     skipOverBlocksWithNoOps();
210   }
211   return *this;
212 }
213 
214 void Region::OpIterator::skipOverBlocksWithNoOps() {
215   while (block != region->end() && block->empty())
216     ++block;
217 
218   // If we are at the last block, then set the operation to first operation of
219   // next block (sentinel value used for end).
220   if (block == region->end())
221     operation = {};
222   else
223     operation = block->begin();
224 }
225 
226 //===----------------------------------------------------------------------===//
227 // RegionRange
228 //===----------------------------------------------------------------------===//
229 
230 RegionRange::RegionRange(MutableArrayRef<Region> regions)
231     : RegionRange(regions.data(), regions.size()) {}
232 RegionRange::RegionRange(ArrayRef<std::unique_ptr<Region>> regions)
233     : RegionRange(regions.data(), regions.size()) {}
234 
235 /// See `llvm::detail::indexed_accessor_range_base` for details.
236 RegionRange::OwnerT RegionRange::offset_base(const OwnerT &owner,
237                                              ptrdiff_t index) {
238   if (auto *operand = owner.dyn_cast<const std::unique_ptr<Region> *>())
239     return operand + index;
240   return &owner.get<Region *>()[index];
241 }
242 /// See `llvm::detail::indexed_accessor_range_base` for details.
243 Region *RegionRange::dereference_iterator(const OwnerT &owner,
244                                           ptrdiff_t index) {
245   if (auto *operand = owner.dyn_cast<const std::unique_ptr<Region> *>())
246     return operand[index].get();
247   return &owner.get<Region *>()[index];
248 }
249