| 1 | //===- ValueBoundsOpInterface.cpp - Value Bounds -------------------------===// |
| 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/Interfaces/ValueBoundsOpInterface.h" |
| 10 | |
| 11 | #include "mlir/IR/BuiltinTypes.h" |
| 12 | #include "mlir/IR/Matchers.h" |
| 13 | #include "mlir/Interfaces/DestinationStyleOpInterface.h" |
| 14 | #include "mlir/Interfaces/ViewLikeInterface.h" |
| 15 | #include "llvm/ADT/APSInt.h" |
| 16 | #include "llvm/ADT/SmallVectorExtras.h" |
| 17 | #include "llvm/Support/Debug.h" |
| 18 | #include "llvm/Support/DebugLog.h" |
| 19 | |
| 20 | #include <utility> |
| 21 | |
| 22 | #define DEBUG_TYPE "value-bounds-op-interface" |
| 23 | |
| 24 | using namespace mlir; |
| 25 | using presburger::BoundType; |
| 26 | using presburger::VarKind; |
| 27 | |
| 28 | namespace mlir { |
| 29 | #include "mlir/Interfaces/ValueBoundsOpInterface.cpp.inc" |
| 30 | } // namespace mlir |
| 31 | |
| 32 | bool ValueBoundsConstraintSet::isProvablyNonNegative( |
| 33 | Value value, ValueBoundsConstraintSet &cstr) { |
| 34 | return cstr.populateAndCompare( |
| 35 | /*lhs=*/{value}, cmp: ValueBoundsConstraintSet::ComparisonOperator::GE, |
| 36 | /*rhs=*/{OpFoldResult(Builder(value.getContext()).getIndexAttr(value: 0))}); |
| 37 | } |
| 38 | |
| 39 | bool ValueBoundsConstraintSet::isProvablyNonPositive( |
| 40 | Value value, ValueBoundsConstraintSet &cstr) { |
| 41 | return cstr.populateAndCompare( |
| 42 | /*lhs=*/{value}, cmp: ValueBoundsConstraintSet::ComparisonOperator::LE, |
| 43 | /*rhs=*/{OpFoldResult(Builder(value.getContext()).getIndexAttr(value: 0))}); |
| 44 | } |
| 45 | |
| 46 | bool ValueBoundsConstraintSet::isProvablyPositive( |
| 47 | Value value, ValueBoundsConstraintSet &cstr) { |
| 48 | return cstr.populateAndCompare( |
| 49 | /*lhs=*/{value}, cmp: ValueBoundsConstraintSet::ComparisonOperator::GT, |
| 50 | /*rhs=*/{OpFoldResult(Builder(value.getContext()).getIndexAttr(value: 0))}); |
| 51 | } |
| 52 | |
| 53 | bool ValueBoundsConstraintSet::isProvablyNegative( |
| 54 | Value value, ValueBoundsConstraintSet &cstr) { |
| 55 | return cstr.populateAndCompare( |
| 56 | /*lhs=*/{value}, cmp: ValueBoundsConstraintSet::ComparisonOperator::LT, |
| 57 | /*rhs=*/{OpFoldResult(Builder(value.getContext()).getIndexAttr(value: 0))}); |
| 58 | } |
| 59 | |
| 60 | static Operation *getOwnerOfValue(Value value) { |
| 61 | if (auto bbArg = dyn_cast<BlockArgument>(Val&: value)) |
| 62 | return bbArg.getOwner()->getParentOp(); |
| 63 | return value.getDefiningOp(); |
| 64 | } |
| 65 | |
| 66 | HyperrectangularSlice::HyperrectangularSlice(ArrayRef<OpFoldResult> offsets, |
| 67 | ArrayRef<OpFoldResult> sizes, |
| 68 | ArrayRef<OpFoldResult> strides) |
| 69 | : mixedOffsets(offsets), mixedSizes(sizes), mixedStrides(strides) { |
| 70 | assert(offsets.size() == sizes.size() && |
| 71 | "expected same number of offsets, sizes, strides" ); |
| 72 | assert(offsets.size() == strides.size() && |
| 73 | "expected same number of offsets, sizes, strides" ); |
| 74 | } |
| 75 | |
| 76 | HyperrectangularSlice::HyperrectangularSlice(ArrayRef<OpFoldResult> offsets, |
| 77 | ArrayRef<OpFoldResult> sizes) |
| 78 | : mixedOffsets(offsets), mixedSizes(sizes) { |
| 79 | assert(offsets.size() == sizes.size() && |
| 80 | "expected same number of offsets and sizes" ); |
| 81 | // Assume that all strides are 1. |
| 82 | if (offsets.empty()) |
| 83 | return; |
| 84 | MLIRContext *ctx = offsets.front().getContext(); |
| 85 | mixedStrides.append(NumInputs: offsets.size(), Elt: Builder(ctx).getIndexAttr(value: 1)); |
| 86 | } |
| 87 | |
| 88 | HyperrectangularSlice::HyperrectangularSlice(OffsetSizeAndStrideOpInterface op) |
| 89 | : HyperrectangularSlice(op.getMixedOffsets(), op.getMixedSizes(), |
| 90 | op.getMixedStrides()) {} |
| 91 | |
| 92 | /// If ofr is a constant integer or an IntegerAttr, return the integer. |
| 93 | static std::optional<int64_t> getConstantIntValue(OpFoldResult ofr) { |
| 94 | // Case 1: Check for Constant integer. |
| 95 | if (auto val = llvm::dyn_cast_if_present<Value>(Val&: ofr)) { |
| 96 | APSInt intVal; |
| 97 | if (matchPattern(value: val, pattern: m_ConstantInt(bind_value: &intVal))) |
| 98 | return intVal.getSExtValue(); |
| 99 | return std::nullopt; |
| 100 | } |
| 101 | // Case 2: Check for IntegerAttr. |
| 102 | Attribute attr = llvm::dyn_cast_if_present<Attribute>(Val&: ofr); |
| 103 | if (auto intAttr = dyn_cast_or_null<IntegerAttr>(Val&: attr)) |
| 104 | return intAttr.getValue().getSExtValue(); |
| 105 | return std::nullopt; |
| 106 | } |
| 107 | |
| 108 | [[maybe_unused]] static bool isIndexOrIntegerType(Type type) { |
| 109 | return type.isIndex() || type.isInteger(); |
| 110 | } |
| 111 | |
| 112 | [[maybe_unused]] static bool isIndexLikeType(Type type, |
| 113 | ValueBoundsOptions options) { |
| 114 | return type.isIndex() || (options.allowIntegerType && type.isInteger()); |
| 115 | } |
| 116 | |
| 117 | ValueBoundsConstraintSet::Variable::Variable(OpFoldResult ofr) |
| 118 | : Variable(ofr, std::nullopt) {} |
| 119 | |
| 120 | ValueBoundsConstraintSet::Variable::Variable(Value indexValue) |
| 121 | : Variable(static_cast<OpFoldResult>(indexValue)) {} |
| 122 | |
| 123 | ValueBoundsConstraintSet::Variable::Variable(Value shapedValue, int64_t dim) |
| 124 | : Variable(static_cast<OpFoldResult>(shapedValue), std::optional(dim)) {} |
| 125 | |
| 126 | ValueBoundsConstraintSet::Variable::Variable(OpFoldResult ofr, |
| 127 | std::optional<int64_t> dim) { |
| 128 | Builder b(ofr.getContext()); |
| 129 | if (auto constInt = ::getConstantIntValue(ofr)) { |
| 130 | assert(!dim && "expected no dim for index/integer-typed values" ); |
| 131 | map = AffineMap::get(/*dimCount=*/0, /*symbolCount=*/0, |
| 132 | result: b.getAffineConstantExpr(constant: *constInt)); |
| 133 | return; |
| 134 | } |
| 135 | Value value = cast<Value>(Val&: ofr); |
| 136 | #ifndef NDEBUG |
| 137 | if (dim) { |
| 138 | assert(isa<ShapedType>(value.getType()) && "expected shaped type" ); |
| 139 | } else { |
| 140 | assert(isIndexOrIntegerType(value.getType()) && |
| 141 | "expected index or integer type" ); |
| 142 | } |
| 143 | #endif // NDEBUG |
| 144 | map = AffineMap::get(/*dimCount=*/0, /*symbolCount=*/1, |
| 145 | result: b.getAffineSymbolExpr(position: 0)); |
| 146 | mapOperands.emplace_back(Args&: value, Args&: dim); |
| 147 | } |
| 148 | |
| 149 | ValueBoundsConstraintSet::Variable::Variable(AffineMap map, |
| 150 | ArrayRef<Variable> mapOperands) { |
| 151 | assert(map.getNumResults() == 1 && "expected single result" ); |
| 152 | |
| 153 | // Turn all dims into symbols. |
| 154 | Builder b(map.getContext()); |
| 155 | // Inline size chosen empirically based on compilation profiling. |
| 156 | // Profiled: 490K calls, avg=1.5+-0.6. N=4 covers >99% of cases inline. |
| 157 | SmallVector<AffineExpr, 4> dimReplacements, symReplacements; |
| 158 | for (int64_t i = 0, e = map.getNumDims(); i < e; ++i) |
| 159 | dimReplacements.push_back(Elt: b.getAffineSymbolExpr(position: i)); |
| 160 | for (int64_t i = 0, e = map.getNumSymbols(); i < e; ++i) |
| 161 | symReplacements.push_back(Elt: b.getAffineSymbolExpr(position: i + map.getNumDims())); |
| 162 | AffineMap tmpMap = map.replaceDimsAndSymbols( |
| 163 | dimReplacements, symReplacements, /*numResultDims=*/0, |
| 164 | /*numResultSyms=*/map.getNumSymbols() + map.getNumDims()); |
| 165 | |
| 166 | // Inline operands. |
| 167 | DenseMap<AffineExpr, AffineExpr> replacements; |
| 168 | for (auto [index, var] : llvm::enumerate(First&: mapOperands)) { |
| 169 | assert(var.map.getNumResults() == 1 && "expected single result" ); |
| 170 | assert(var.map.getNumDims() == 0 && "expected only symbols" ); |
| 171 | SmallVector<AffineExpr> symReplacements; |
| 172 | for (auto valueDim : var.mapOperands) { |
| 173 | auto *it = llvm::find(Range&: this->mapOperands, Val: valueDim); |
| 174 | if (it != this->mapOperands.end()) { |
| 175 | // There is already a symbol for this operand. |
| 176 | symReplacements.push_back(Elt: b.getAffineSymbolExpr( |
| 177 | position: std::distance(first: this->mapOperands.begin(), last: it))); |
| 178 | } else { |
| 179 | // This is a new operand: add a new symbol. |
| 180 | symReplacements.push_back( |
| 181 | Elt: b.getAffineSymbolExpr(position: this->mapOperands.size())); |
| 182 | this->mapOperands.push_back(Elt: valueDim); |
| 183 | } |
| 184 | } |
| 185 | replacements[b.getAffineSymbolExpr(position: index)] = |
| 186 | var.map.getResult(idx: 0).replaceSymbols(symReplacements); |
| 187 | } |
| 188 | this->map = tmpMap.replace(map: replacements, /*numResultDims=*/0, |
| 189 | /*numResultSyms=*/this->mapOperands.size()); |
| 190 | } |
| 191 | |
| 192 | ValueBoundsConstraintSet::Variable::Variable(AffineMap map, |
| 193 | ValueRange mapOperands) |
| 194 | : Variable(map, llvm::map_to_vector(C&: mapOperands, |
| 195 | F: [](Value v) { return Variable(v); })) {} |
| 196 | |
| 197 | ValueBoundsConstraintSet::ValueBoundsConstraintSet( |
| 198 | MLIRContext *ctx, const StopConditionFn &stopCondition, |
| 199 | ValueBoundsOptions options, bool addConservativeSemiAffineBounds) |
| 200 | : builder(ctx), stopCondition(stopCondition), options(options), |
| 201 | addConservativeSemiAffineBounds(addConservativeSemiAffineBounds) { |
| 202 | assert(stopCondition && "expected non-null stop condition" ); |
| 203 | } |
| 204 | |
| 205 | char ValueBoundsConstraintSet::ID = 0; |
| 206 | |
| 207 | #ifndef NDEBUG |
| 208 | static void assertValidValueDim(Value value, std::optional<int64_t> dim, |
| 209 | ValueBoundsOptions options) { |
| 210 | if (isIndexLikeType(value.getType(), options)) { |
| 211 | assert(!dim.has_value() && "invalid dim value" ); |
| 212 | } else if (auto shapedType = dyn_cast<ShapedType>(value.getType())) { |
| 213 | assert(*dim >= 0 && "invalid dim value" ); |
| 214 | if (shapedType.hasRank()) |
| 215 | assert(*dim < shapedType.getRank() && "invalid dim value" ); |
| 216 | } else { |
| 217 | llvm_unreachable("unsupported type" ); |
| 218 | } |
| 219 | } |
| 220 | #endif // NDEBUG |
| 221 | |
| 222 | void ValueBoundsConstraintSet::addBound(BoundType type, int64_t pos, |
| 223 | AffineExpr expr) { |
| 224 | // Note: If `addConservativeSemiAffineBounds` is true then the bound |
| 225 | // computation function needs to handle the case that the constraints set |
| 226 | // could become empty. This is because the conservative bounds add assumptions |
| 227 | // (e.g. for `mod` it assumes `rhs > 0`). If these constraints are later found |
| 228 | // not to hold, then the bound is invalid. |
| 229 | LogicalResult status = cstr.addBound( |
| 230 | type, pos, |
| 231 | boundMap: AffineMap::get(dimCount: cstr.getNumDimVars(), symbolCount: cstr.getNumSymbolVars(), result: expr), |
| 232 | addConservativeSemiAffineBounds |
| 233 | ? FlatLinearConstraints::AddConservativeSemiAffineBounds::Yes |
| 234 | : FlatLinearConstraints::AddConservativeSemiAffineBounds::No); |
| 235 | if (failed(Result: status)) { |
| 236 | // Not all semi-affine expressions are not yet supported by |
| 237 | // FlatLinearConstraints. However, we can just ignore such failures here. |
| 238 | // Even without this bound, there may be enough information in the |
| 239 | // constraint system to compute the requested bound. In case this bound is |
| 240 | // actually needed, `computeBound` will return `failure`. |
| 241 | LDBG() << "Failed to add bound: " << expr << "\n" ; |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | AffineExpr ValueBoundsConstraintSet::getExpr(Value value, |
| 246 | std::optional<int64_t> dim) { |
| 247 | #ifndef NDEBUG |
| 248 | assertValidValueDim(value, dim, options); |
| 249 | #endif // NDEBUG |
| 250 | |
| 251 | // Check if the value/dim is statically known. In that case, an affine |
| 252 | // constant expression should be returned. This allows us to support |
| 253 | // multiplications with constants. (Multiplications of two columns in the |
| 254 | // constraint set is not supported.) |
| 255 | std::optional<int64_t> constSize = std::nullopt; |
| 256 | auto shapedType = dyn_cast<ShapedType>(Val: value.getType()); |
| 257 | if (shapedType) { |
| 258 | if (shapedType.hasRank() && !shapedType.isDynamicDim(idx: *dim)) |
| 259 | constSize = shapedType.getDimSize(idx: *dim); |
| 260 | } else if (auto constInt = ::getConstantIntValue(ofr: value)) { |
| 261 | constSize = *constInt; |
| 262 | } |
| 263 | |
| 264 | // If the value/dim is already mapped, return the corresponding expression |
| 265 | // directly. |
| 266 | ValueDim valueDim = std::make_pair(x&: value, y: dim.value_or(u: kIndexValue)); |
| 267 | if (valueDimToPosition.contains(Val: valueDim)) { |
| 268 | // If it is a constant, return an affine constant expression. Otherwise, |
| 269 | // return an affine expression that represents the respective column in the |
| 270 | // constraint set. |
| 271 | if (constSize) |
| 272 | return builder.getAffineConstantExpr(constant: *constSize); |
| 273 | return getPosExpr(pos: getPos(value, dim)); |
| 274 | } |
| 275 | |
| 276 | if (constSize) { |
| 277 | // Constant index value/dim: add column to the constraint set, add EQ bound |
| 278 | // and return an affine constant expression without pushing the newly added |
| 279 | // column to the worklist. |
| 280 | (void)insert(value, dim, /*isSymbol=*/true, /*addToWorklist=*/false); |
| 281 | if (shapedType) |
| 282 | bound(value)[*dim] == *constSize; |
| 283 | else |
| 284 | bound(value) == *constSize; |
| 285 | return builder.getAffineConstantExpr(constant: *constSize); |
| 286 | } |
| 287 | |
| 288 | // Dynamic value/dim: insert column to the constraint set and put it on the |
| 289 | // worklist. Return an affine expression that represents the newly inserted |
| 290 | // column in the constraint set. |
| 291 | return getPosExpr(pos: insert(value, dim, /*isSymbol=*/true)); |
| 292 | } |
| 293 | |
| 294 | AffineExpr ValueBoundsConstraintSet::getExpr(OpFoldResult ofr) { |
| 295 | if (Value value = llvm::dyn_cast_if_present<Value>(Val&: ofr)) |
| 296 | return getExpr(value, /*dim=*/std::nullopt); |
| 297 | auto constInt = ::getConstantIntValue(ofr); |
| 298 | assert(constInt.has_value() && "expected Integer constant" ); |
| 299 | return builder.getAffineConstantExpr(constant: *constInt); |
| 300 | } |
| 301 | |
| 302 | AffineExpr ValueBoundsConstraintSet::getExpr(int64_t constant) { |
| 303 | return builder.getAffineConstantExpr(constant); |
| 304 | } |
| 305 | |
| 306 | int64_t ValueBoundsConstraintSet::insert(Value value, |
| 307 | std::optional<int64_t> dim, |
| 308 | bool isSymbol, bool addToWorklist) { |
| 309 | #ifndef NDEBUG |
| 310 | assertValidValueDim(value, dim, options); |
| 311 | #endif // NDEBUG |
| 312 | |
| 313 | ValueDim valueDim = std::make_pair(x&: value, y: dim.value_or(u: kIndexValue)); |
| 314 | assert(!valueDimToPosition.contains(valueDim) && "already mapped" ); |
| 315 | int64_t pos = isSymbol ? cstr.appendVar(kind: VarKind::Symbol) |
| 316 | : cstr.appendVar(kind: VarKind::SetDim); |
| 317 | LDBG() << "Inserting constraint set column " << pos << " for: " << value |
| 318 | << " (dim: " << dim.value_or(u: kIndexValue) |
| 319 | << ", owner: " << getOwnerOfValue(value)->getName() << ")" ; |
| 320 | positionToValueDim.insert(I: positionToValueDim.begin() + pos, Elt: valueDim); |
| 321 | // Update reverse mapping. |
| 322 | for (int64_t i = pos, e = positionToValueDim.size(); i < e; ++i) |
| 323 | if (positionToValueDim[i].has_value()) |
| 324 | valueDimToPosition[*positionToValueDim[i]] = i; |
| 325 | |
| 326 | // Do not add block arguments from non-entry blocks to the worklist. The |
| 327 | // ValueBoundsOpInterface cannot derive any bounds for such values (they |
| 328 | // arise from unstructured control flow), so putting them on the worklist |
| 329 | // would be a no-op. More importantly, suppressing the worklist push ensures |
| 330 | // that processWorklist never calls getExpr on such a value a second time, |
| 331 | // which would otherwise cause the same value to be looked up as already |
| 332 | // mapped (triggering an unintended bug path). |
| 333 | if (addToWorklist && |
| 334 | (!isa<BlockArgument>(Val: value) || |
| 335 | cast<BlockArgument>(Val&: value).getOwner()->isEntryBlock())) { |
| 336 | LDBG() << "Push to worklist: " << value |
| 337 | << " (dim: " << dim.value_or(u: kIndexValue) << ")" ; |
| 338 | worklist.push(x: valueDim); |
| 339 | } |
| 340 | |
| 341 | return pos; |
| 342 | } |
| 343 | |
| 344 | int64_t ValueBoundsConstraintSet::insert(bool isSymbol) { |
| 345 | int64_t pos = isSymbol ? cstr.appendVar(kind: VarKind::Symbol) |
| 346 | : cstr.appendVar(kind: VarKind::SetDim); |
| 347 | LDBG() << "Inserting anonymous constraint set column " << pos; |
| 348 | positionToValueDim.insert(I: positionToValueDim.begin() + pos, Elt: std::nullopt); |
| 349 | // Update reverse mapping. |
| 350 | for (int64_t i = pos, e = positionToValueDim.size(); i < e; ++i) |
| 351 | if (positionToValueDim[i].has_value()) |
| 352 | valueDimToPosition[*positionToValueDim[i]] = i; |
| 353 | return pos; |
| 354 | } |
| 355 | |
| 356 | int64_t ValueBoundsConstraintSet::insert(AffineMap map, |
| 357 | const ValueDimList &operands, |
| 358 | bool isSymbol) { |
| 359 | assert(map.getNumResults() == 1 && "expected affine map with one result" ); |
| 360 | int64_t pos = insert(isSymbol); |
| 361 | |
| 362 | // Add map and operands to the constraint set. Dimensions are converted to |
| 363 | // symbols. All operands are added to the worklist (unless they were already |
| 364 | // processed). |
| 365 | auto mapper = [&](std::pair<Value, std::optional<int64_t>> v) { |
| 366 | return getExpr(value: v.first, dim: v.second); |
| 367 | }; |
| 368 | SmallVector<AffineExpr> dimReplacements = llvm::map_to_vector( |
| 369 | C: ArrayRef(operands).take_front(N: map.getNumDims()), F&: mapper); |
| 370 | SmallVector<AffineExpr> symReplacements = llvm::map_to_vector( |
| 371 | C: ArrayRef(operands).drop_front(N: map.getNumDims()), F&: mapper); |
| 372 | addBound( |
| 373 | type: presburger::BoundType::EQ, pos, |
| 374 | expr: map.getResult(idx: 0).replaceDimsAndSymbols(dimReplacements, symReplacements)); |
| 375 | |
| 376 | return pos; |
| 377 | } |
| 378 | |
| 379 | int64_t ValueBoundsConstraintSet::insert(const Variable &var, bool isSymbol) { |
| 380 | return insert(map: var.map, operands: var.mapOperands, isSymbol); |
| 381 | } |
| 382 | |
| 383 | int64_t ValueBoundsConstraintSet::getPos(Value value, |
| 384 | std::optional<int64_t> dim) const { |
| 385 | #ifndef NDEBUG |
| 386 | assertValidValueDim(value, dim, options); |
| 387 | #endif // NDEBUG |
| 388 | LDBG() << "Getting pos for: " << value |
| 389 | << " (dim: " << dim.value_or(u: kIndexValue) |
| 390 | << ", owner: " << getOwnerOfValue(value)->getName() << ")" ; |
| 391 | auto it = |
| 392 | valueDimToPosition.find(Val: std::make_pair(x&: value, y: dim.value_or(u: kIndexValue))); |
| 393 | assert(it != valueDimToPosition.end() && "expected mapped entry" ); |
| 394 | return it->second; |
| 395 | } |
| 396 | |
| 397 | AffineExpr ValueBoundsConstraintSet::getPosExpr(int64_t pos) { |
| 398 | assert(pos >= 0 && pos < cstr.getNumDimAndSymbolVars() && "invalid position" ); |
| 399 | return pos < cstr.getNumDimVars() |
| 400 | ? builder.getAffineDimExpr(position: pos) |
| 401 | : builder.getAffineSymbolExpr(position: pos - cstr.getNumDimVars()); |
| 402 | } |
| 403 | |
| 404 | bool ValueBoundsConstraintSet::isMapped(Value value, |
| 405 | std::optional<int64_t> dim) const { |
| 406 | auto it = |
| 407 | valueDimToPosition.find(Val: std::make_pair(x&: value, y: dim.value_or(u: kIndexValue))); |
| 408 | return it != valueDimToPosition.end(); |
| 409 | } |
| 410 | |
| 411 | void ValueBoundsConstraintSet::processWorklist() { |
| 412 | LDBG() << "Processing value bounds worklist..." ; |
| 413 | while (!worklist.empty()) { |
| 414 | ValueDim valueDim = worklist.front(); |
| 415 | worklist.pop(); |
| 416 | assert(valueDimToPosition.contains(valueDim) && |
| 417 | "expected mapped worklist entry" ); |
| 418 | Value value = valueDim.first; |
| 419 | int64_t dim = valueDim.second; |
| 420 | |
| 421 | // Check for static dim size. |
| 422 | if (dim != kIndexValue) { |
| 423 | auto shapedType = cast<ShapedType>(Val: value.getType()); |
| 424 | if (shapedType.hasRank() && !shapedType.isDynamicDim(idx: dim)) { |
| 425 | bound(value)[dim] == getExpr(constant: shapedType.getDimSize(idx: dim)); |
| 426 | continue; |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | // Do not process any further if the stop condition is met. |
| 431 | auto maybeDim = dim == kIndexValue ? std::nullopt : std::make_optional(t&: dim); |
| 432 | if (stopCondition(value, maybeDim, *this)) { |
| 433 | LDBG() << "Stop condition met for: " << value << " (dim: " << maybeDim |
| 434 | << ")" ; |
| 435 | continue; |
| 436 | } |
| 437 | |
| 438 | // Query `ValueBoundsOpInterface` for constraints. New items may be added to |
| 439 | // the worklist. |
| 440 | auto valueBoundsOp = |
| 441 | dyn_cast<ValueBoundsOpInterface>(Val: getOwnerOfValue(value)); |
| 442 | LDBG() << "Query value bounds for: " << value |
| 443 | << " (owner: " << getOwnerOfValue(value)->getName() << ")" ; |
| 444 | if (valueBoundsOp) { |
| 445 | if (dim == kIndexValue) { |
| 446 | valueBoundsOp.populateBoundsForIndexValue(value, cstr&: *this); |
| 447 | } else { |
| 448 | valueBoundsOp.populateBoundsForShapedValueDim(value, dim, cstr&: *this); |
| 449 | } |
| 450 | continue; |
| 451 | } |
| 452 | LDBG() << "--> ValueBoundsOpInterface not implemented" ; |
| 453 | |
| 454 | // If the op does not implement `ValueBoundsOpInterface`, check if it |
| 455 | // implements the `DestinationStyleOpInterface`. OpResults of such ops are |
| 456 | // tied to OpOperands. Tied values have the same shape. |
| 457 | auto dstOp = value.getDefiningOp<DestinationStyleOpInterface>(); |
| 458 | if (!dstOp || dim == kIndexValue) |
| 459 | continue; |
| 460 | Value tiedOperand = dstOp.getTiedOpOperand(opResult: cast<OpResult>(Val&: value))->get(); |
| 461 | bound(value)[dim] == getExpr(value: tiedOperand, dim); |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | void ValueBoundsConstraintSet::projectOut(int64_t pos) { |
| 466 | assert(pos >= 0 && pos < static_cast<int64_t>(positionToValueDim.size()) && |
| 467 | "invalid position" ); |
| 468 | cstr.projectOut(pos); |
| 469 | if (positionToValueDim[pos].has_value()) { |
| 470 | bool erased = valueDimToPosition.erase(Val: *positionToValueDim[pos]); |
| 471 | (void)erased; |
| 472 | assert(erased && "inconsistent reverse mapping" ); |
| 473 | } |
| 474 | positionToValueDim.erase(CI: positionToValueDim.begin() + pos); |
| 475 | // Update reverse mapping. |
| 476 | for (int64_t i = pos, e = positionToValueDim.size(); i < e; ++i) |
| 477 | if (positionToValueDim[i].has_value()) |
| 478 | valueDimToPosition[*positionToValueDim[i]] = i; |
| 479 | } |
| 480 | |
| 481 | void ValueBoundsConstraintSet::projectOut( |
| 482 | function_ref<bool(ValueDim)> condition) { |
| 483 | int64_t nextPos = 0; |
| 484 | while (nextPos < static_cast<int64_t>(positionToValueDim.size())) { |
| 485 | if (positionToValueDim[nextPos].has_value() && |
| 486 | condition(*positionToValueDim[nextPos])) { |
| 487 | projectOut(pos: nextPos); |
| 488 | // The column was projected out so another column is now at that position. |
| 489 | // Do not increase the counter. |
| 490 | } else { |
| 491 | ++nextPos; |
| 492 | } |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | void ValueBoundsConstraintSet::projectOutAnonymous( |
| 497 | std::optional<int64_t> except) { |
| 498 | int64_t nextPos = 0; |
| 499 | while (nextPos < static_cast<int64_t>(positionToValueDim.size())) { |
| 500 | if (positionToValueDim[nextPos].has_value() || except == nextPos) { |
| 501 | ++nextPos; |
| 502 | } else { |
| 503 | projectOut(pos: nextPos); |
| 504 | // The column was projected out so another column is now at that position. |
| 505 | // Do not increase the counter. |
| 506 | } |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | LogicalResult ValueBoundsConstraintSet::computeBound( |
| 511 | AffineMap &resultMap, ValueDimList &mapOperands, presburger::BoundType type, |
| 512 | const Variable &var, StopConditionFn stopCondition, |
| 513 | ValueBoundsOptions options) { |
| 514 | MLIRContext *ctx = var.getContext(); |
| 515 | int64_t ubAdjustment = options.closedUB ? 0 : 1; |
| 516 | Builder b(ctx); |
| 517 | mapOperands.clear(); |
| 518 | |
| 519 | // Process the backward slice of `value` (i.e., reverse use-def chain) until |
| 520 | // `stopCondition` is met. |
| 521 | ValueBoundsConstraintSet cstr(ctx, stopCondition, options); |
| 522 | int64_t pos = cstr.insert(var, /*isSymbol=*/false); |
| 523 | assert(pos == 0 && "expected first column" ); |
| 524 | cstr.processWorklist(); |
| 525 | |
| 526 | // Project out all variables (apart from `valueDim`) that do not match the |
| 527 | // stop condition. |
| 528 | cstr.projectOut(condition: [&](ValueDim p) { |
| 529 | auto maybeDim = |
| 530 | p.second == kIndexValue ? std::nullopt : std::make_optional(t&: p.second); |
| 531 | return !stopCondition(p.first, maybeDim, cstr); |
| 532 | }); |
| 533 | cstr.projectOutAnonymous(/*except=*/pos); |
| 534 | |
| 535 | // Compute lower and upper bounds for `valueDim`. |
| 536 | SmallVector<AffineMap> lb(1), ub(1); |
| 537 | cstr.cstr.getSliceBounds(offset: pos, num: 1, context: ctx, lbMaps: &lb, ubMaps: &ub, |
| 538 | /*closedUB=*/true); |
| 539 | |
| 540 | // Note: There are TODOs in the implementation of `getSliceBounds`. In such a |
| 541 | // case, no lower/upper bound can be computed at the moment. |
| 542 | // EQ, UB bounds: upper bound is needed. |
| 543 | if ((type != BoundType::LB) && |
| 544 | (ub.empty() || !ub[0] || ub[0].getNumResults() == 0)) |
| 545 | return failure(); |
| 546 | // EQ, LB bounds: lower bound is needed. |
| 547 | if ((type != BoundType::UB) && |
| 548 | (lb.empty() || !lb[0] || lb[0].getNumResults() == 0)) |
| 549 | return failure(); |
| 550 | |
| 551 | // TODO: Generate an affine map with multiple results. |
| 552 | if (type != BoundType::LB) |
| 553 | assert(ub.size() == 1 && ub[0].getNumResults() == 1 && |
| 554 | "multiple bounds not supported" ); |
| 555 | if (type != BoundType::UB) |
| 556 | assert(lb.size() == 1 && lb[0].getNumResults() == 1 && |
| 557 | "multiple bounds not supported" ); |
| 558 | |
| 559 | // EQ bound: lower and upper bound must match. |
| 560 | if (type == BoundType::EQ && ub[0] != lb[0]) |
| 561 | return failure(); |
| 562 | |
| 563 | AffineMap bound; |
| 564 | if (type == BoundType::EQ || type == BoundType::LB) { |
| 565 | bound = lb[0]; |
| 566 | } else { |
| 567 | // Computed UB is a closed bound. |
| 568 | bound = AffineMap::get(dimCount: ub[0].getNumDims(), symbolCount: ub[0].getNumSymbols(), |
| 569 | result: ub[0].getResult(idx: 0) + ubAdjustment); |
| 570 | } |
| 571 | |
| 572 | // Gather all SSA values that are used in the computed bound. |
| 573 | assert(cstr.cstr.getNumDimAndSymbolVars() == cstr.positionToValueDim.size() && |
| 574 | "inconsistent mapping state" ); |
| 575 | SmallVector<AffineExpr> replacementDims, replacementSymbols; |
| 576 | int64_t numDims = 0, numSymbols = 0; |
| 577 | for (int64_t i = 0; i < cstr.cstr.getNumDimAndSymbolVars(); ++i) { |
| 578 | // Skip `value`. |
| 579 | if (i == pos) |
| 580 | continue; |
| 581 | // Check if the position `i` is used in the generated bound. If so, it must |
| 582 | // be included in the generated affine.apply op. |
| 583 | bool used = false; |
| 584 | bool isDim = i < cstr.cstr.getNumDimVars(); |
| 585 | if (isDim) { |
| 586 | if (bound.isFunctionOfDim(position: i)) |
| 587 | used = true; |
| 588 | } else { |
| 589 | if (bound.isFunctionOfSymbol(position: i - cstr.cstr.getNumDimVars())) |
| 590 | used = true; |
| 591 | } |
| 592 | |
| 593 | if (!used) { |
| 594 | // Not used: Remove dim/symbol from the result. |
| 595 | if (isDim) { |
| 596 | replacementDims.push_back(Elt: b.getAffineConstantExpr(constant: 0)); |
| 597 | } else { |
| 598 | replacementSymbols.push_back(Elt: b.getAffineConstantExpr(constant: 0)); |
| 599 | } |
| 600 | continue; |
| 601 | } |
| 602 | |
| 603 | if (isDim) { |
| 604 | replacementDims.push_back(Elt: b.getAffineDimExpr(position: numDims++)); |
| 605 | } else { |
| 606 | replacementSymbols.push_back(Elt: b.getAffineSymbolExpr(position: numSymbols++)); |
| 607 | } |
| 608 | |
| 609 | assert(cstr.positionToValueDim[i].has_value() && |
| 610 | "cannot build affine map in terms of anonymous column" ); |
| 611 | ValueBoundsConstraintSet::ValueDim valueDim = *cstr.positionToValueDim[i]; |
| 612 | Value value = valueDim.first; |
| 613 | int64_t dim = valueDim.second; |
| 614 | if (dim == ValueBoundsConstraintSet::kIndexValue) { |
| 615 | // An index-typed/integer-typed value is used: it can be used directly in |
| 616 | // the computed bound. |
| 617 | assert(isIndexLikeType(value.getType(), options) && |
| 618 | "expected index or integer type" ); |
| 619 | mapOperands.push_back(Elt: std::make_pair(x&: value, y: std::nullopt)); |
| 620 | continue; |
| 621 | } |
| 622 | |
| 623 | assert(cast<ShapedType>(value.getType()).isDynamicDim(dim) && |
| 624 | "expected dynamic dim" ); |
| 625 | mapOperands.push_back(Elt: std::make_pair(x&: value, y&: dim)); |
| 626 | } |
| 627 | |
| 628 | resultMap = bound.replaceDimsAndSymbols(dimReplacements: replacementDims, symReplacements: replacementSymbols, |
| 629 | numResultDims: numDims, numResultSyms: numSymbols); |
| 630 | return success(); |
| 631 | } |
| 632 | |
| 633 | LogicalResult ValueBoundsConstraintSet::computeDependentBound( |
| 634 | AffineMap &resultMap, ValueDimList &mapOperands, presburger::BoundType type, |
| 635 | const Variable &var, ValueDimList dependencies, |
| 636 | ValueBoundsOptions options) { |
| 637 | return computeBound( |
| 638 | resultMap, mapOperands, type, var, |
| 639 | stopCondition: [&](Value v, std::optional<int64_t> d, ValueBoundsConstraintSet &cstr) { |
| 640 | return llvm::is_contained(Range&: dependencies, Element: std::make_pair(x&: v, y&: d)); |
| 641 | }, |
| 642 | options); |
| 643 | } |
| 644 | |
| 645 | LogicalResult ValueBoundsConstraintSet::computeIndependentBound( |
| 646 | AffineMap &resultMap, ValueDimList &mapOperands, presburger::BoundType type, |
| 647 | const Variable &var, ValueRange independencies, |
| 648 | ValueBoundsOptions options) { |
| 649 | // Return "true" if the given value is independent of all values in |
| 650 | // `independencies`. I.e., neither the value itself nor any value in the |
| 651 | // backward slice (reverse use-def chain) is contained in `independencies`. |
| 652 | auto isIndependent = [&](Value v) { |
| 653 | SmallVector<Value> worklist; |
| 654 | DenseSet<Value> visited; |
| 655 | worklist.push_back(Elt: v); |
| 656 | while (!worklist.empty()) { |
| 657 | Value next = worklist.pop_back_val(); |
| 658 | if (!visited.insert(V: next).second) |
| 659 | continue; |
| 660 | if (llvm::is_contained(Range&: independencies, Element: next)) |
| 661 | return false; |
| 662 | // TODO: DominanceInfo could be used to stop the traversal early. |
| 663 | Operation *op = next.getDefiningOp(); |
| 664 | if (!op) |
| 665 | continue; |
| 666 | worklist.append(in_start: op->getOperands().begin(), in_end: op->getOperands().end()); |
| 667 | } |
| 668 | return true; |
| 669 | }; |
| 670 | |
| 671 | // Reify bounds in terms of any independent values. |
| 672 | return computeBound( |
| 673 | resultMap, mapOperands, type, var, |
| 674 | stopCondition: [&](Value v, std::optional<int64_t> d, ValueBoundsConstraintSet &cstr) { |
| 675 | return isIndependent(v); |
| 676 | }, |
| 677 | options); |
| 678 | } |
| 679 | |
| 680 | FailureOr<int64_t> ValueBoundsConstraintSet::computeConstantBound( |
| 681 | presburger::BoundType type, const Variable &var, |
| 682 | const StopConditionFn &stopCondition, ValueBoundsOptions options) { |
| 683 | // Default stop condition if none was specified: Keep adding constraints until |
| 684 | // a bound could be computed. |
| 685 | int64_t pos = 0; |
| 686 | auto defaultStopCondition = [&](Value v, std::optional<int64_t> dim, |
| 687 | ValueBoundsConstraintSet &cstr) { |
| 688 | return cstr.cstr.getConstantBound64(type, pos).has_value(); |
| 689 | }; |
| 690 | |
| 691 | ValueBoundsConstraintSet cstr( |
| 692 | var.getContext(), stopCondition ? stopCondition : defaultStopCondition, |
| 693 | options); |
| 694 | pos = cstr.populateConstraints(map: var.map, mapOperands: var.mapOperands); |
| 695 | assert(pos == 0 && "expected `map` is the first column" ); |
| 696 | |
| 697 | // Compute constant bound for `valueDim`. |
| 698 | int64_t ubAdjustment = options.closedUB ? 0 : 1; |
| 699 | if (auto bound = cstr.cstr.getConstantBound64(type, pos)) |
| 700 | return type == BoundType::UB ? *bound + ubAdjustment : *bound; |
| 701 | return failure(); |
| 702 | } |
| 703 | |
| 704 | void ValueBoundsConstraintSet::populateConstraints(Value value, |
| 705 | std::optional<int64_t> dim) { |
| 706 | #ifndef NDEBUG |
| 707 | assertValidValueDim(value, dim, options); |
| 708 | #endif // NDEBUG |
| 709 | |
| 710 | // `getExpr` pushes the value/dim onto the worklist (unless it was already |
| 711 | // analyzed). |
| 712 | (void)getExpr(value, dim); |
| 713 | // Process all values/dims on the worklist. This may traverse and analyze |
| 714 | // additional IR, depending the current stop function. |
| 715 | processWorklist(); |
| 716 | } |
| 717 | |
| 718 | int64_t ValueBoundsConstraintSet::populateConstraints(AffineMap map, |
| 719 | ValueDimList operands) { |
| 720 | int64_t pos = insert(map, operands: std::move(operands), /*isSymbol=*/false); |
| 721 | // Process the backward slice of `operands` (i.e., reverse use-def chain) |
| 722 | // until `stopCondition` is met. |
| 723 | processWorklist(); |
| 724 | return pos; |
| 725 | } |
| 726 | |
| 727 | FailureOr<int64_t> |
| 728 | ValueBoundsConstraintSet::computeConstantDelta(Value value1, Value value2, |
| 729 | std::optional<int64_t> dim1, |
| 730 | std::optional<int64_t> dim2) { |
| 731 | #ifndef NDEBUG |
| 732 | assertValidValueDim(value1, dim1, /*options=*/{}); |
| 733 | assertValidValueDim(value2, dim2, /*options=*/{}); |
| 734 | #endif // NDEBUG |
| 735 | |
| 736 | Builder b(value1.getContext()); |
| 737 | AffineMap map = AffineMap::get(/*dimCount=*/2, /*symbolCount=*/0, |
| 738 | result: b.getAffineDimExpr(position: 0) - b.getAffineDimExpr(position: 1)); |
| 739 | return computeConstantBound(type: presburger::BoundType::EQ, |
| 740 | var: Variable(map, {{value1, dim1}, {value2, dim2}})); |
| 741 | } |
| 742 | |
| 743 | bool ValueBoundsConstraintSet::comparePos(int64_t lhsPos, |
| 744 | ComparisonOperator cmp, |
| 745 | int64_t rhsPos) { |
| 746 | // This function returns "true" if "lhs CMP rhs" is proven to hold. |
| 747 | // |
| 748 | // Example for ComparisonOperator::LE and index-typed values: We would like to |
| 749 | // prove that lhs <= rhs. Proof by contradiction: add the inverse |
| 750 | // relation (lhs > rhs) to the constraint set and check if the resulting |
| 751 | // constraint set is "empty" (i.e. has no solution). In that case, |
| 752 | // lhs > rhs must be incorrect and we can deduce that lhs <= rhs holds. |
| 753 | |
| 754 | // We cannot prove anything if the constraint set is already empty. |
| 755 | if (cstr.isEmpty()) { |
| 756 | LDBG() << "cannot compare value/dims: constraint system is already empty" ; |
| 757 | return false; |
| 758 | } |
| 759 | |
| 760 | // EQ can be expressed as LE and GE. |
| 761 | if (cmp == EQ) |
| 762 | return comparePos(lhsPos, cmp: ComparisonOperator::LE, rhsPos) && |
| 763 | comparePos(lhsPos, cmp: ComparisonOperator::GE, rhsPos); |
| 764 | |
| 765 | // Construct inequality. |
| 766 | // Inline size chosen empirically based on compilation profiling. |
| 767 | // Profiled: 3.2M calls, avg=4.0+-2.3. N=8 covers ~95% of cases inline. |
| 768 | SmallVector<int64_t, 8> eq(cstr.getNumCols(), 0); |
| 769 | if (cmp == LT || cmp == LE) { |
| 770 | ++eq[lhsPos]; |
| 771 | --eq[rhsPos]; |
| 772 | } else if (cmp == GT || cmp == GE) { |
| 773 | --eq[lhsPos]; |
| 774 | ++eq[rhsPos]; |
| 775 | } else { |
| 776 | llvm_unreachable("unsupported comparison operator" ); |
| 777 | } |
| 778 | if (cmp == LE || cmp == GE) |
| 779 | eq[cstr.getNumCols() - 1] -= 1; |
| 780 | |
| 781 | // Add inequality to the constraint set and check if it made the constraint |
| 782 | // set empty. |
| 783 | int64_t ineqPos = cstr.getNumInequalities(); |
| 784 | cstr.addInequality(inEq: eq); |
| 785 | bool isEmpty = cstr.isEmpty(); |
| 786 | cstr.removeInequality(pos: ineqPos); |
| 787 | return isEmpty; |
| 788 | } |
| 789 | |
| 790 | FailureOr<bool> ValueBoundsConstraintSet::strongComparePos( |
| 791 | int64_t lhsPos, ComparisonOperator cmp, int64_t rhsPos) { |
| 792 | auto strongCmp = [&](ComparisonOperator cmp, |
| 793 | ComparisonOperator negCmp) -> FailureOr<bool> { |
| 794 | if (comparePos(lhsPos, cmp, rhsPos)) |
| 795 | return true; |
| 796 | if (comparePos(lhsPos, cmp: negCmp, rhsPos)) |
| 797 | return false; |
| 798 | return failure(); |
| 799 | }; |
| 800 | switch (cmp) { |
| 801 | case ComparisonOperator::LT: |
| 802 | return strongCmp(ComparisonOperator::LT, ComparisonOperator::GE); |
| 803 | case ComparisonOperator::LE: |
| 804 | return strongCmp(ComparisonOperator::LE, ComparisonOperator::GT); |
| 805 | case ComparisonOperator::GT: |
| 806 | return strongCmp(ComparisonOperator::GT, ComparisonOperator::LE); |
| 807 | case ComparisonOperator::GE: |
| 808 | return strongCmp(ComparisonOperator::GE, ComparisonOperator::LT); |
| 809 | case ComparisonOperator::EQ: { |
| 810 | std::optional<bool> le = |
| 811 | strongComparePos(lhsPos, cmp: ComparisonOperator::LE, rhsPos); |
| 812 | if (!le) |
| 813 | return failure(); |
| 814 | if (!*le) |
| 815 | return false; |
| 816 | std::optional<bool> ge = |
| 817 | strongComparePos(lhsPos, cmp: ComparisonOperator::GE, rhsPos); |
| 818 | if (!ge) |
| 819 | return failure(); |
| 820 | if (!*ge) |
| 821 | return false; |
| 822 | return true; |
| 823 | } |
| 824 | } |
| 825 | llvm_unreachable("invalid comparison operator" ); |
| 826 | } |
| 827 | |
| 828 | bool ValueBoundsConstraintSet::populateAndCompare(const Variable &lhs, |
| 829 | ComparisonOperator cmp, |
| 830 | const Variable &rhs) { |
| 831 | int64_t lhsPos = populateConstraints(map: lhs.map, operands: lhs.mapOperands); |
| 832 | int64_t rhsPos = populateConstraints(map: rhs.map, operands: rhs.mapOperands); |
| 833 | return comparePos(lhsPos, cmp, rhsPos); |
| 834 | } |
| 835 | |
| 836 | bool ValueBoundsConstraintSet::compare(const Variable &lhs, |
| 837 | ComparisonOperator cmp, |
| 838 | const Variable &rhs) { |
| 839 | int64_t lhsPos = -1, rhsPos = -1; |
| 840 | auto stopCondition = [&](Value v, std::optional<int64_t> dim, |
| 841 | ValueBoundsConstraintSet &cstr) { |
| 842 | // Keep processing as long as lhs/rhs were not processed. |
| 843 | if (size_t(lhsPos) >= cstr.positionToValueDim.size() || |
| 844 | size_t(rhsPos) >= cstr.positionToValueDim.size()) |
| 845 | return false; |
| 846 | // Keep processing as long as the relation cannot be proven. |
| 847 | return cstr.comparePos(lhsPos, cmp, rhsPos); |
| 848 | }; |
| 849 | ValueBoundsConstraintSet cstr(lhs.getContext(), stopCondition); |
| 850 | return cstr.populateAndCompare(lhs, cmp, rhs); |
| 851 | } |
| 852 | |
| 853 | FailureOr<bool> ValueBoundsConstraintSet::strongCompare(const Variable &lhs, |
| 854 | ComparisonOperator cmp, |
| 855 | const Variable &rhs) { |
| 856 | int64_t lhsPos = -1, rhsPos = -1; |
| 857 | auto stopCondition = [&](Value v, std::optional<int64_t> dim, |
| 858 | ValueBoundsConstraintSet &cstr) { |
| 859 | // Keep processing as long as lhs/rhs were not processed. |
| 860 | if (size_t(lhsPos) >= cstr.positionToValueDim.size() || |
| 861 | size_t(rhsPos) >= cstr.positionToValueDim.size()) |
| 862 | return false; |
| 863 | // Keep processing as long as the strong relation cannot be proven. |
| 864 | FailureOr<bool> ordered = cstr.strongComparePos(lhsPos, cmp, rhsPos); |
| 865 | return failed(Result: ordered); |
| 866 | }; |
| 867 | ValueBoundsConstraintSet cstr(lhs.getContext(), stopCondition); |
| 868 | lhsPos = cstr.populateConstraints(map: lhs.map, operands: lhs.mapOperands); |
| 869 | rhsPos = cstr.populateConstraints(map: rhs.map, operands: rhs.mapOperands); |
| 870 | return cstr.strongComparePos(lhsPos, cmp, rhsPos); |
| 871 | } |
| 872 | |
| 873 | FailureOr<bool> ValueBoundsConstraintSet::areEqual(const Variable &var1, |
| 874 | const Variable &var2) { |
| 875 | // Avoid constructing a constraint set for variables that are already known |
| 876 | // to be identical. |
| 877 | if (var1.map == var2.map && var1.mapOperands == var2.mapOperands) |
| 878 | return true; |
| 879 | return strongCompare(lhs: var1, cmp: ComparisonOperator::EQ, rhs: var2); |
| 880 | } |
| 881 | |
| 882 | FailureOr<bool> ValueBoundsConstraintSet::areOverlappingSlices( |
| 883 | MLIRContext *ctx, const HyperrectangularSlice &slice1, |
| 884 | const HyperrectangularSlice &slice2) { |
| 885 | assert(slice1.getMixedOffsets().size() == slice2.getMixedOffsets().size() && |
| 886 | "expected slices of same rank" ); |
| 887 | assert(slice1.getMixedSizes().size() == slice2.getMixedSizes().size() && |
| 888 | "expected slices of same rank" ); |
| 889 | assert(slice1.getMixedStrides().size() == slice2.getMixedStrides().size() && |
| 890 | "expected slices of same rank" ); |
| 891 | |
| 892 | Builder b(ctx); |
| 893 | bool foundUnknownBound = false; |
| 894 | for (int64_t i = 0, e = slice1.getMixedOffsets().size(); i < e; ++i) { |
| 895 | AffineMap map = |
| 896 | AffineMap::get(/*dimCount=*/0, /*symbolCount=*/4, |
| 897 | result: b.getAffineSymbolExpr(position: 0) + |
| 898 | b.getAffineSymbolExpr(position: 1) * b.getAffineSymbolExpr(position: 2) - |
| 899 | b.getAffineSymbolExpr(position: 3)); |
| 900 | { |
| 901 | // Case 1: Slices are guaranteed to be non-overlapping if |
| 902 | // offset1 + size1 * stride1 <= offset2 (for at least one dimension). |
| 903 | SmallVector<OpFoldResult> ofrOperands; |
| 904 | ofrOperands.push_back(Elt: slice1.getMixedOffsets()[i]); |
| 905 | ofrOperands.push_back(Elt: slice1.getMixedSizes()[i]); |
| 906 | ofrOperands.push_back(Elt: slice1.getMixedStrides()[i]); |
| 907 | ofrOperands.push_back(Elt: slice2.getMixedOffsets()[i]); |
| 908 | SmallVector<Value> valueOperands; |
| 909 | AffineMap foldedMap = |
| 910 | foldAttributesIntoMap(b, map, operands: ofrOperands, remainingValues&: valueOperands); |
| 911 | FailureOr<int64_t> constBound = computeConstantBound( |
| 912 | type: presburger::BoundType::EQ, var: Variable(foldedMap, valueOperands)); |
| 913 | foundUnknownBound |= failed(Result: constBound); |
| 914 | if (succeeded(Result: constBound) && *constBound <= 0) |
| 915 | return false; |
| 916 | } |
| 917 | { |
| 918 | // Case 2: Slices are guaranteed to be non-overlapping if |
| 919 | // offset2 + size2 * stride2 <= offset1 (for at least one dimension). |
| 920 | SmallVector<OpFoldResult> ofrOperands; |
| 921 | ofrOperands.push_back(Elt: slice2.getMixedOffsets()[i]); |
| 922 | ofrOperands.push_back(Elt: slice2.getMixedSizes()[i]); |
| 923 | ofrOperands.push_back(Elt: slice2.getMixedStrides()[i]); |
| 924 | ofrOperands.push_back(Elt: slice1.getMixedOffsets()[i]); |
| 925 | SmallVector<Value> valueOperands; |
| 926 | AffineMap foldedMap = |
| 927 | foldAttributesIntoMap(b, map, operands: ofrOperands, remainingValues&: valueOperands); |
| 928 | FailureOr<int64_t> constBound = computeConstantBound( |
| 929 | type: presburger::BoundType::EQ, var: Variable(foldedMap, valueOperands)); |
| 930 | foundUnknownBound |= failed(Result: constBound); |
| 931 | if (succeeded(Result: constBound) && *constBound <= 0) |
| 932 | return false; |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | // If at least one bound could not be computed, we cannot be certain that the |
| 937 | // slices are really overlapping. |
| 938 | if (foundUnknownBound) |
| 939 | return failure(); |
| 940 | |
| 941 | // All bounds could be computed and none of the above cases applied. |
| 942 | // Therefore, the slices are guaranteed to overlap. |
| 943 | return true; |
| 944 | } |
| 945 | |
| 946 | FailureOr<bool> ValueBoundsConstraintSet::areEquivalentSlices( |
| 947 | MLIRContext *ctx, const HyperrectangularSlice &slice1, |
| 948 | const HyperrectangularSlice &slice2) { |
| 949 | assert(slice1.getMixedOffsets().size() == slice2.getMixedOffsets().size() && |
| 950 | "expected slices of same rank" ); |
| 951 | assert(slice1.getMixedSizes().size() == slice2.getMixedSizes().size() && |
| 952 | "expected slices of same rank" ); |
| 953 | assert(slice1.getMixedStrides().size() == slice2.getMixedStrides().size() && |
| 954 | "expected slices of same rank" ); |
| 955 | |
| 956 | // The two slices are equivalent if all of their offsets, sizes and strides |
| 957 | // are equal. If equality cannot be determined for at least one of those |
| 958 | // values, equivalence cannot be determined and this function returns |
| 959 | // "failure". |
| 960 | for (auto [offset1, offset2] : |
| 961 | llvm::zip_equal(t: slice1.getMixedOffsets(), u: slice2.getMixedOffsets())) { |
| 962 | FailureOr<bool> equal = areEqual(var1: offset1, var2: offset2); |
| 963 | if (failed(Result: equal)) |
| 964 | return failure(); |
| 965 | if (!equal.value()) |
| 966 | return false; |
| 967 | } |
| 968 | for (auto [size1, size2] : |
| 969 | llvm::zip_equal(t: slice1.getMixedSizes(), u: slice2.getMixedSizes())) { |
| 970 | FailureOr<bool> equal = areEqual(var1: size1, var2: size2); |
| 971 | if (failed(Result: equal)) |
| 972 | return failure(); |
| 973 | if (!equal.value()) |
| 974 | return false; |
| 975 | } |
| 976 | for (auto [stride1, stride2] : |
| 977 | llvm::zip_equal(t: slice1.getMixedStrides(), u: slice2.getMixedStrides())) { |
| 978 | FailureOr<bool> equal = areEqual(var1: stride1, var2: stride2); |
| 979 | if (failed(Result: equal)) |
| 980 | return failure(); |
| 981 | if (!equal.value()) |
| 982 | return false; |
| 983 | } |
| 984 | return true; |
| 985 | } |
| 986 | |
| 987 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 988 | void ValueBoundsConstraintSet::dump() const { |
| 989 | llvm::errs() << "==========\nColumns:\n" ; |
| 990 | llvm::errs() << "(column\tdim\tvalue)\n" ; |
| 991 | for (auto [index, valueDim] : llvm::enumerate(positionToValueDim)) { |
| 992 | llvm::errs() << " " << index << "\t" ; |
| 993 | if (valueDim) { |
| 994 | if (valueDim->second == kIndexValue) { |
| 995 | llvm::errs() << "n/a\t" ; |
| 996 | } else { |
| 997 | llvm::errs() << valueDim->second << "\t" ; |
| 998 | } |
| 999 | llvm::errs() << getOwnerOfValue(valueDim->first)->getName() << " " ; |
| 1000 | if (OpResult result = dyn_cast<OpResult>(valueDim->first)) { |
| 1001 | llvm::errs() << "(result " << result.getResultNumber() << ")" ; |
| 1002 | } else { |
| 1003 | llvm::errs() << "(bbarg " |
| 1004 | << cast<BlockArgument>(valueDim->first).getArgNumber() |
| 1005 | << ")" ; |
| 1006 | } |
| 1007 | llvm::errs() << "\n" ; |
| 1008 | } else { |
| 1009 | llvm::errs() << "n/a\tn/a\n" ; |
| 1010 | } |
| 1011 | } |
| 1012 | llvm::errs() << "\nConstraint set:\n" ; |
| 1013 | cstr.dump(); |
| 1014 | llvm::errs() << "==========\n" ; |
| 1015 | } |
| 1016 | #endif |
| 1017 | |
| 1018 | ValueBoundsConstraintSet::BoundBuilder & |
| 1019 | ValueBoundsConstraintSet::BoundBuilder::operator[](int64_t dim) { |
| 1020 | assert(!this->dim.has_value() && "dim was already set" ); |
| 1021 | this->dim = dim; |
| 1022 | #ifndef NDEBUG |
| 1023 | assertValidValueDim(value, this->dim, cstr.options); |
| 1024 | #endif // NDEBUG |
| 1025 | return *this; |
| 1026 | } |
| 1027 | |
| 1028 | void ValueBoundsConstraintSet::BoundBuilder::operator<(AffineExpr expr) { |
| 1029 | #ifndef NDEBUG |
| 1030 | assertValidValueDim(value, this->dim, cstr.options); |
| 1031 | #endif // NDEBUG |
| 1032 | cstr.addBound(type: BoundType::UB, pos: cstr.getPos(value, dim: this->dim), expr); |
| 1033 | } |
| 1034 | |
| 1035 | void ValueBoundsConstraintSet::BoundBuilder::operator<=(AffineExpr expr) { |
| 1036 | operator<(expr: expr + 1); |
| 1037 | } |
| 1038 | |
| 1039 | void ValueBoundsConstraintSet::BoundBuilder::operator>(AffineExpr expr) { |
| 1040 | operator>=(expr: expr + 1); |
| 1041 | } |
| 1042 | |
| 1043 | void ValueBoundsConstraintSet::BoundBuilder::operator>=(AffineExpr expr) { |
| 1044 | #ifndef NDEBUG |
| 1045 | assertValidValueDim(value, this->dim, cstr.options); |
| 1046 | #endif // NDEBUG |
| 1047 | cstr.addBound(type: BoundType::LB, pos: cstr.getPos(value, dim: this->dim), expr); |
| 1048 | } |
| 1049 | |
| 1050 | void ValueBoundsConstraintSet::BoundBuilder::operator==(AffineExpr expr) { |
| 1051 | #ifndef NDEBUG |
| 1052 | assertValidValueDim(value, this->dim, cstr.options); |
| 1053 | #endif // NDEBUG |
| 1054 | cstr.addBound(type: BoundType::EQ, pos: cstr.getPos(value, dim: this->dim), expr); |
| 1055 | } |
| 1056 | |
| 1057 | void ValueBoundsConstraintSet::BoundBuilder::operator<(OpFoldResult ofr) { |
| 1058 | operator<(expr: cstr.getExpr(ofr)); |
| 1059 | } |
| 1060 | |
| 1061 | void ValueBoundsConstraintSet::BoundBuilder::operator<=(OpFoldResult ofr) { |
| 1062 | operator<=(expr: cstr.getExpr(ofr)); |
| 1063 | } |
| 1064 | |
| 1065 | void ValueBoundsConstraintSet::BoundBuilder::operator>(OpFoldResult ofr) { |
| 1066 | operator>(expr: cstr.getExpr(ofr)); |
| 1067 | } |
| 1068 | |
| 1069 | void ValueBoundsConstraintSet::BoundBuilder::operator>=(OpFoldResult ofr) { |
| 1070 | operator>=(expr: cstr.getExpr(ofr)); |
| 1071 | } |
| 1072 | |
| 1073 | void ValueBoundsConstraintSet::BoundBuilder::operator==(OpFoldResult ofr) { |
| 1074 | operator==(expr: cstr.getExpr(ofr)); |
| 1075 | } |
| 1076 | |
| 1077 | void ValueBoundsConstraintSet::BoundBuilder::operator<(int64_t i) { |
| 1078 | operator<(expr: cstr.getExpr(constant: i)); |
| 1079 | } |
| 1080 | |
| 1081 | void ValueBoundsConstraintSet::BoundBuilder::operator<=(int64_t i) { |
| 1082 | operator<=(expr: cstr.getExpr(constant: i)); |
| 1083 | } |
| 1084 | |
| 1085 | void ValueBoundsConstraintSet::BoundBuilder::operator>(int64_t i) { |
| 1086 | operator>(expr: cstr.getExpr(constant: i)); |
| 1087 | } |
| 1088 | |
| 1089 | void ValueBoundsConstraintSet::BoundBuilder::operator>=(int64_t i) { |
| 1090 | operator>=(expr: cstr.getExpr(constant: i)); |
| 1091 | } |
| 1092 | |
| 1093 | void ValueBoundsConstraintSet::BoundBuilder::operator==(int64_t i) { |
| 1094 | operator==(expr: cstr.getExpr(constant: i)); |
| 1095 | } |
| 1096 | |