-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
Copy pathControlFlowInterfaces.cpp
407 lines (354 loc) · 15.9 KB
/
ControlFlowInterfaces.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//===- ControlFlowInterfaces.cpp - ControlFlow Interfaces -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Interfaces/ControlFlowInterfaces.h"
#include "mlir/IR/BuiltinTypes.h"
#include "llvm/ADT/SmallPtrSet.h"
using namespace mlir;
//===----------------------------------------------------------------------===//
// ControlFlowInterfaces
//===----------------------------------------------------------------------===//
#include "mlir/Interfaces/ControlFlowInterfaces.cpp.inc"
SuccessorOperands::SuccessorOperands(MutableOperandRange forwardedOperands)
: producedOperandCount(0), forwardedOperands(forwardedOperands) {}
SuccessorOperands::SuccessorOperands(unsigned int producedOperandCount,
MutableOperandRange forwardedOperands)
: producedOperandCount(producedOperandCount),
forwardedOperands(std::move(forwardedOperands)) {}
//===----------------------------------------------------------------------===//
// BranchOpInterface
//===----------------------------------------------------------------------===//
/// Returns the `BlockArgument` corresponding to operand `operandIndex` in some
/// successor if 'operandIndex' is within the range of 'operands', or None if
/// `operandIndex` isn't a successor operand index.
Optional<BlockArgument>
detail::getBranchSuccessorArgument(const SuccessorOperands &operands,
unsigned operandIndex, Block *successor) {
OperandRange forwardedOperands = operands.getForwardedOperands();
// Check that the operands are valid.
if (forwardedOperands.empty())
return llvm::None;
// Check to ensure that this operand is within the range.
unsigned operandsStart = forwardedOperands.getBeginOperandIndex();
if (operandIndex < operandsStart ||
operandIndex >= (operandsStart + forwardedOperands.size()))
return llvm::None;
// Index the successor.
unsigned argIndex =
operands.getProducedOperandCount() + operandIndex - operandsStart;
return successor->getArgument(argIndex);
}
/// Verify that the given operands match those of the given successor block.
LogicalResult
detail::verifyBranchSuccessorOperands(Operation *op, unsigned succNo,
const SuccessorOperands &operands) {
// Check the count.
unsigned operandCount = operands.size();
Block *destBB = op->getSuccessor(succNo);
if (operandCount != destBB->getNumArguments())
return op->emitError() << "branch has " << operandCount
<< " operands for successor #" << succNo
<< ", but target block has "
<< destBB->getNumArguments();
// Check the types.
for (unsigned i = operands.getProducedOperandCount(); i != operandCount;
++i) {
if (!cast<BranchOpInterface>(op).areTypesCompatible(
operands[i].getType(), destBB->getArgument(i).getType()))
return op->emitError() << "type mismatch for bb argument #" << i
<< " of successor #" << succNo;
}
return success();
}
//===----------------------------------------------------------------------===//
// RegionBranchOpInterface
//===----------------------------------------------------------------------===//
/// Verify that types match along all region control flow edges originating from
/// `sourceNo` (region # if source is a region, llvm::None if source is parent
/// op). `getInputsTypesForRegion` is a function that returns the types of the
/// inputs that flow from `sourceIndex' to the given region, or llvm::None if
/// the exact type match verification is not necessary (e.g., if the Op verifies
/// the match itself).
static LogicalResult
verifyTypesAlongAllEdges(Operation *op, Optional<unsigned> sourceNo,
function_ref<Optional<TypeRange>(Optional<unsigned>)>
getInputsTypesForRegion) {
auto regionInterface = cast<RegionBranchOpInterface>(op);
SmallVector<RegionSuccessor, 2> successors;
unsigned numInputs;
if (sourceNo) {
Region &srcRegion = op->getRegion(sourceNo.getValue());
numInputs = srcRegion.getNumArguments();
} else {
numInputs = op->getNumOperands();
}
SmallVector<Attribute, 2> operands(numInputs, nullptr);
regionInterface.getSuccessorRegions(sourceNo, operands, successors);
for (RegionSuccessor &succ : successors) {
Optional<unsigned> succRegionNo;
if (!succ.isParent())
succRegionNo = succ.getSuccessor()->getRegionNumber();
auto printEdgeName = [&](InFlightDiagnostic &diag) -> InFlightDiagnostic & {
diag << "from ";
if (sourceNo)
diag << "Region #" << sourceNo.getValue();
else
diag << "parent operands";
diag << " to ";
if (succRegionNo)
diag << "Region #" << succRegionNo.getValue();
else
diag << "parent results";
return diag;
};
Optional<TypeRange> sourceTypes = getInputsTypesForRegion(succRegionNo);
if (!sourceTypes.hasValue())
continue;
TypeRange succInputsTypes = succ.getSuccessorInputs().getTypes();
if (sourceTypes->size() != succInputsTypes.size()) {
InFlightDiagnostic diag = op->emitOpError(" region control flow edge ");
return printEdgeName(diag) << ": source has " << sourceTypes->size()
<< " operands, but target successor needs "
<< succInputsTypes.size();
}
for (const auto &typesIdx :
llvm::enumerate(llvm::zip(*sourceTypes, succInputsTypes))) {
Type sourceType = std::get<0>(typesIdx.value());
Type inputType = std::get<1>(typesIdx.value());
if (!regionInterface.areTypesCompatible(sourceType, inputType)) {
InFlightDiagnostic diag = op->emitOpError(" along control flow edge ");
return printEdgeName(diag)
<< ": source type #" << typesIdx.index() << " " << sourceType
<< " should match input type #" << typesIdx.index() << " "
<< inputType;
}
}
}
return success();
}
/// Verify that types match along control flow edges described the given op.
LogicalResult detail::verifyTypesAlongControlFlowEdges(Operation *op) {
auto regionInterface = cast<RegionBranchOpInterface>(op);
auto inputTypesFromParent = [&](Optional<unsigned> regionNo) -> TypeRange {
if (regionNo.hasValue()) {
return regionInterface.getSuccessorEntryOperands(regionNo.getValue())
.getTypes();
}
// If the successor of a parent op is the parent itself
// RegionBranchOpInterface does not have an API to query what the entry
// operands will be in that case. Vend out the result types of the op in
// that case so that type checking succeeds for this case.
return op->getResultTypes();
};
// Verify types along control flow edges originating from the parent.
if (failed(verifyTypesAlongAllEdges(op, llvm::None, inputTypesFromParent)))
return failure();
// RegionBranchOpInterface should not be implemented by Ops that do not have
// attached regions.
assert(op->getNumRegions() != 0);
auto areTypesCompatible = [&](TypeRange lhs, TypeRange rhs) {
if (lhs.size() != rhs.size())
return false;
for (auto types : llvm::zip(lhs, rhs)) {
if (!regionInterface.areTypesCompatible(std::get<0>(types),
std::get<1>(types))) {
return false;
}
}
return true;
};
// Verify types along control flow edges originating from each region.
for (unsigned regionNo : llvm::seq(0U, op->getNumRegions())) {
Region ®ion = op->getRegion(regionNo);
// Since there can be multiple `ReturnLike` terminators or others
// implementing the `RegionBranchTerminatorOpInterface`, all should have the
// same operand types when passing them to the same region.
Optional<OperandRange> regionReturnOperands;
for (Block &block : region) {
Operation *terminator = block.getTerminator();
auto terminatorOperands =
getRegionBranchSuccessorOperands(terminator, regionNo);
if (!terminatorOperands)
continue;
if (!regionReturnOperands) {
regionReturnOperands = terminatorOperands;
continue;
}
// Found more than one ReturnLike terminator. Make sure the operand types
// match with the first one.
if (!areTypesCompatible(regionReturnOperands->getTypes(),
terminatorOperands->getTypes()))
return op->emitOpError("Region #")
<< regionNo
<< " operands mismatch between return-like terminators";
}
auto inputTypesFromRegion =
[&](Optional<unsigned> regionNo) -> Optional<TypeRange> {
// If there is no return-like terminator, the op itself should verify
// type consistency.
if (!regionReturnOperands)
return llvm::None;
// All successors get the same set of operand types.
return TypeRange(regionReturnOperands->getTypes());
};
if (failed(verifyTypesAlongAllEdges(op, regionNo, inputTypesFromRegion)))
return failure();
}
return success();
}
/// Return `true` if `a` and `b` are in mutually exclusive regions.
///
/// 1. Find the first common of `a` and `b` (ancestor) that implements
/// RegionBranchOpInterface.
/// 2. Determine the regions `regionA` and `regionB` in which `a` and `b` are
/// contained.
/// 3. Check if `regionA` and `regionB` are mutually exclusive. They are
/// mutually exclusive if they are not reachable from each other as per
/// RegionBranchOpInterface::getSuccessorRegions.
bool mlir::insideMutuallyExclusiveRegions(Operation *a, Operation *b) {
assert(a && "expected non-empty operation");
assert(b && "expected non-empty operation");
auto branchOp = a->getParentOfType<RegionBranchOpInterface>();
while (branchOp) {
// Check if b is inside branchOp. (We already know that a is.)
if (!branchOp->isProperAncestor(b)) {
// Check next enclosing RegionBranchOpInterface.
branchOp = branchOp->getParentOfType<RegionBranchOpInterface>();
continue;
}
// b is contained in branchOp. Retrieve the regions in which `a` and `b`
// are contained.
Region *regionA = nullptr, *regionB = nullptr;
for (Region &r : branchOp->getRegions()) {
if (r.findAncestorOpInRegion(*a)) {
assert(!regionA && "already found a region for a");
regionA = &r;
}
if (r.findAncestorOpInRegion(*b)) {
assert(!regionB && "already found a region for b");
regionB = &r;
}
}
assert(regionA && regionB && "could not find region of op");
// Helper function that checks if region `r` is reachable from region
// `begin`.
std::function<bool(Region *, Region *)> isRegionReachable =
[&](Region *begin, Region *r) {
if (begin == r)
return true;
if (begin == nullptr)
return false;
// Compute index of region.
int64_t beginIndex = -1;
for (const auto &it : llvm::enumerate(branchOp->getRegions()))
if (&it.value() == begin)
beginIndex = it.index();
assert(beginIndex != -1 && "could not find region in op");
// Retrieve all successors of the region.
SmallVector<RegionSuccessor> successors;
branchOp.getSuccessorRegions(beginIndex, successors);
// Call function recursively on all successors.
for (RegionSuccessor successor : successors)
if (isRegionReachable(successor.getSuccessor(), r))
return true;
return false;
};
// `a` and `b` are in mutually exclusive regions if neither region is
// reachable from the other region.
return !isRegionReachable(regionA, regionB) &&
!isRegionReachable(regionB, regionA);
}
// Could not find a common RegionBranchOpInterface among a's and b's
// ancestors.
return false;
}
bool RegionBranchOpInterface::isRepetitiveRegion(unsigned index) {
SmallVector<bool> visited(getOperation()->getNumRegions(), false);
visited[index] = true;
// Retrieve all successors of the region and enqueue them in the worklist.
SmallVector<unsigned> worklist;
auto enqueueAllSuccessors = [&](unsigned index) {
SmallVector<RegionSuccessor> successors;
this->getSuccessorRegions(index, successors);
for (RegionSuccessor successor : successors)
if (!successor.isParent())
worklist.push_back(successor.getSuccessor()->getRegionNumber());
};
enqueueAllSuccessors(index);
// Process all regions in the worklist via DFS.
while (!worklist.empty()) {
unsigned nextRegion = worklist.pop_back_val();
if (nextRegion == index)
return true;
if (visited[nextRegion])
continue;
visited[nextRegion] = true;
enqueueAllSuccessors(nextRegion);
}
return false;
}
Region *mlir::getEnclosingRepetitiveRegion(Operation *op) {
while (Region *region = op->getParentRegion()) {
op = region->getParentOp();
if (auto branchOp = dyn_cast<RegionBranchOpInterface>(op))
if (branchOp.isRepetitiveRegion(region->getRegionNumber()))
return region;
}
return nullptr;
}
Region *mlir::getEnclosingRepetitiveRegion(Value value) {
Region *region = value.getParentRegion();
while (region) {
Operation *op = region->getParentOp();
if (auto branchOp = dyn_cast<RegionBranchOpInterface>(op))
if (branchOp.isRepetitiveRegion(region->getRegionNumber()))
return region;
region = op->getParentRegion();
}
return nullptr;
}
//===----------------------------------------------------------------------===//
// RegionBranchTerminatorOpInterface
//===----------------------------------------------------------------------===//
/// Returns true if the given operation is either annotated with the
/// `ReturnLike` trait or implements the `RegionBranchTerminatorOpInterface`.
bool mlir::isRegionReturnLike(Operation *operation) {
return dyn_cast<RegionBranchTerminatorOpInterface>(operation) ||
operation->hasTrait<OpTrait::ReturnLike>();
}
/// Returns the mutable operands that are passed to the region with the given
/// `regionIndex`. If the operation does not implement the
/// `RegionBranchTerminatorOpInterface` and is not marked as `ReturnLike`, the
/// result will be `llvm::None`. In all other cases, the resulting
/// `OperandRange` represents all operands that are passed to the specified
/// successor region. If `regionIndex` is `llvm::None`, all operands that are
/// passed to the parent operation will be returned.
Optional<MutableOperandRange>
mlir::getMutableRegionBranchSuccessorOperands(Operation *operation,
Optional<unsigned> regionIndex) {
// Try to query a RegionBranchTerminatorOpInterface to determine
// all successor operands that will be passed to the successor
// input arguments.
if (auto regionTerminatorInterface =
dyn_cast<RegionBranchTerminatorOpInterface>(operation))
return regionTerminatorInterface.getMutableSuccessorOperands(regionIndex);
// TODO: The ReturnLike trait should imply a default implementation of the
// RegionBranchTerminatorOpInterface. This would make this code significantly
// easier. Furthermore, this may even make this function obsolete.
if (operation->hasTrait<OpTrait::ReturnLike>())
return MutableOperandRange(operation);
return llvm::None;
}
/// Returns the read only operands that are passed to the region with the given
/// `regionIndex`. See `getMutableRegionBranchSuccessorOperands` for more
/// information.
Optional<OperandRange>
mlir::getRegionBranchSuccessorOperands(Operation *operation,
Optional<unsigned> regionIndex) {
auto range = getMutableRegionBranchSuccessorOperands(operation, regionIndex);
return range ? Optional<OperandRange>(*range) : llvm::None;
}