MLIR 24.0.0git
AffineAnalysis.cpp
Go to the documentation of this file.
1//===- AffineAnalysis.cpp - Affine structures analysis routines -----------===//
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 implements miscellaneous analysis routines for affine structures
10// (expressions, maps, sets), and other utilities relying on such analysis.
11//
12//===----------------------------------------------------------------------===//
13
25#include "llvm/ADT/TypeSwitch.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/raw_ostream.h"
28#include <optional>
29
30#define DEBUG_TYPE "affine-analysis"
31
32using namespace mlir;
33using namespace affine;
34using namespace presburger;
35
36/// Get the value that is being reduced by `pos`-th reduction in the loop if
37/// such a reduction can be performed by affine parallel loops. This assumes
38/// floating-point operations are commutative. On success, `kind` will be the
39/// reduction kind suitable for use in affine parallel loop builder. If the
40/// reduction is not supported, returns null.
41static Value getSupportedReduction(AffineForOp forOp, unsigned pos,
42 arith::AtomicRMWKind &kind) {
43 SmallVector<Operation *> combinerOps;
44 Value reducedVal =
45 matchReduction(forOp.getRegionIterArgs(), pos, combinerOps);
46 if (!reducedVal)
47 return nullptr;
48
49 // Expected only one combiner operation.
50 if (combinerOps.size() > 1)
51 return nullptr;
52
53 Operation *combinerOp = combinerOps.back();
54 std::optional<arith::AtomicRMWKind> maybeKind =
56 .Case([](arith::AddFOp) { return arith::AtomicRMWKind::addf; })
57 .Case([](arith::MulFOp) { return arith::AtomicRMWKind::mulf; })
58 .Case([](arith::AddIOp) { return arith::AtomicRMWKind::addi; })
59 .Case([](arith::AndIOp) { return arith::AtomicRMWKind::andi; })
60 .Case([](arith::OrIOp) { return arith::AtomicRMWKind::ori; })
61 .Case([](arith::MulIOp) { return arith::AtomicRMWKind::muli; })
62 .Case(
63 [](arith::MinimumFOp) { return arith::AtomicRMWKind::minimumf; })
64 .Case(
65 [](arith::MaximumFOp) { return arith::AtomicRMWKind::maximumf; })
66 .Case([](arith::MinSIOp) { return arith::AtomicRMWKind::mins; })
67 .Case([](arith::MaxSIOp) { return arith::AtomicRMWKind::maxs; })
68 .Case([](arith::MinUIOp) { return arith::AtomicRMWKind::minu; })
69 .Case([](arith::MaxUIOp) { return arith::AtomicRMWKind::maxu; })
70 .Case([](arith::XOrIOp) { return arith::AtomicRMWKind::xori; })
71 .Case([](arith::MaxNumFOp) { return arith::AtomicRMWKind::maxnumf; })
72 .Case([](arith::MinNumFOp) { return arith::AtomicRMWKind::minnumf; })
73 .Default([](Operation *) -> std::optional<arith::AtomicRMWKind> {
74 return std::nullopt;
75 });
76 if (!maybeKind)
77 return nullptr;
78
79 kind = *maybeKind;
80 return reducedVal;
81}
82
83/// Populate `supportedReductions` with descriptors of the supported reductions.
85 AffineForOp forOp, SmallVectorImpl<LoopReduction> &supportedReductions) {
86 unsigned numIterArgs = forOp.getNumIterOperands();
87 if (numIterArgs == 0)
88 return;
89 supportedReductions.reserve(numIterArgs);
90 for (unsigned i = 0; i < numIterArgs; ++i) {
91 arith::AtomicRMWKind kind;
92 if (Value value = getSupportedReduction(forOp, i, kind))
93 supportedReductions.emplace_back(LoopReduction{kind, i, value});
94 }
95}
96
97/// Returns true if `forOp' is a parallel loop. If `parallelReductions` is
98/// provided, populates it with descriptors of the parallelizable reductions and
99/// treats them as not preventing parallelization.
100bool mlir::affine::isLoopParallel(
101 AffineForOp forOp, SmallVectorImpl<LoopReduction> *parallelReductions) {
102 unsigned numIterArgs = forOp.getNumIterOperands();
103
104 // Loop is not parallel if it has SSA loop-carried dependences and reduction
105 // detection is not requested.
106 if (numIterArgs > 0 && !parallelReductions)
107 return false;
108
109 // Find supported reductions of requested.
110 if (parallelReductions) {
111 getSupportedReductions(forOp, *parallelReductions);
112 // Return later to allow for identifying all parallel reductions even if the
113 // loop is not parallel.
114 if (parallelReductions->size() != numIterArgs)
115 return false;
116 }
117
118 // Check memory dependences.
119 return isLoopMemoryParallel(forOp);
120}
121
122/// Returns true if `v` is allocated locally to `enclosingOp` -- i.e., it is
123/// allocated by an operation nested within `enclosingOp`.
124static bool isLocallyDefined(Value v, Operation *enclosingOp) {
125 Operation *defOp = v.getDefiningOp();
126 if (!defOp)
127 return false;
128
130 enclosingOp->isProperAncestor(defOp))
131 return true;
132
133 // Aliasing ops.
134 auto viewOp = dyn_cast<ViewLikeOpInterface>(defOp);
135 return viewOp && isLocallyDefined(viewOp.getViewSource(), enclosingOp);
136}
137
138/// Returns true if all memory effects of `op` free memory that is allocated
139/// locally to `enclosingOp`.
140static bool freesOnlyLocallyDefined(Operation *op, Operation *enclosingOp) {
141 auto memOp = dyn_cast<MemoryEffectOpInterface>(op);
142 if (!memOp)
143 return false;
145 memOp.getEffects(effects);
146 return !effects.empty() &&
147 llvm::all_of(effects, [&](const MemoryEffects::EffectInstance &e) {
148 return isa<MemoryEffects::Free>(e.getEffect()) && e.getValue() &&
149 isLocallyDefined(e.getValue(), enclosingOp);
150 });
151}
152
153bool mlir::affine::isLoopMemoryParallel(AffineForOp forOp) {
154 // Any memref-typed iteration arguments are treated as serializing.
155 if (llvm::any_of(forOp.getResultTypes(), llvm::IsaPred<BaseMemRefType>))
156 return false;
157
158 // Collect all load and store ops in loop nest rooted at 'forOp'.
159 SmallVector<Operation *, 8> loadAndStoreOps;
160 auto walkResult = forOp.walk([&](Operation *op) -> WalkResult {
161 if (auto readOp = dyn_cast<AffineReadOpInterface>(op)) {
162 // Memrefs that are allocated inside `forOp` need not be considered.
163 if (!isLocallyDefined(readOp.getMemRef(), forOp))
164 loadAndStoreOps.push_back(op);
165 } else if (auto writeOp = dyn_cast<AffineWriteOpInterface>(op)) {
166 // Filter out stores the same way as above.
167 if (!isLocallyDefined(writeOp.getMemRef(), forOp))
168 loadAndStoreOps.push_back(op);
169 } else if (!isa<AffineForOp, AffineYieldOp, AffineIfOp>(op) &&
171 !freesOnlyLocallyDefined(op, forOp) && !isMemoryEffectFree(op)) {
172 // Alloc-like ops inside `forOp` are fine (they don't impact parallelism)
173 // as long as they don't escape the loop (which has been checked above).
174 // So are dealloc-like ops freeing such allocations. Freeing other memory
175 // may race with accesses to it from other iterations.
176 return WalkResult::interrupt();
177 }
178
179 return WalkResult::advance();
180 });
181
182 // Stop early if the loop has unknown ops with side effects.
183 if (walkResult.wasInterrupted())
184 return false;
185
186 // Dep check depth would be number of enclosing loops + 1.
187 unsigned depth = getNestingDepth(forOp) + 1;
188
189 // Check dependences between all pairs of ops in 'loadAndStoreOps'.
190 for (auto *srcOp : loadAndStoreOps) {
191 MemRefAccess srcAccess(srcOp);
192 for (auto *dstOp : loadAndStoreOps) {
193 MemRefAccess dstAccess(dstOp);
195 checkMemrefAccessDependence(srcAccess, dstAccess, depth);
197 return false;
198 }
199 }
200 return true;
201}
202
203/// Returns the sequence of AffineApplyOp Operations operation in
204/// 'affineApplyOps', which are reachable via a search starting from 'operands',
205/// and ending at operands which are not defined by AffineApplyOps.
206// TODO: Add a method to AffineApplyOp which forward substitutes the
207// AffineApplyOp into any user AffineApplyOps.
209 ArrayRef<Value> operands, SmallVectorImpl<Operation *> &affineApplyOps) {
210 struct State {
211 // The ssa value for this node in the DFS traversal.
212 Value value;
213 // The operand index of 'value' to explore next during DFS traversal.
214 unsigned operandIndex;
215 };
216 SmallVector<State, 4> worklist;
217 for (auto operand : operands) {
218 worklist.push_back({operand, 0});
219 }
220
221 while (!worklist.empty()) {
222 State &state = worklist.back();
223 auto *opInst = state.value.getDefiningOp();
224 // Note: getDefiningOp will return nullptr if the operand is not an
225 // Operation (i.e. block argument), which is a terminator for the search.
226 if (!isa_and_nonnull<AffineApplyOp>(opInst)) {
227 worklist.pop_back();
228 continue;
229 }
230
231 if (state.operandIndex == 0) {
232 // Pre-Visit: Add 'opInst' to reachable sequence.
233 affineApplyOps.push_back(opInst);
234 }
235 if (state.operandIndex < opInst->getNumOperands()) {
236 // Visit: Add next 'affineApplyOp' operand to worklist.
237 // Get next operand to visit at 'operandIndex'.
238 auto nextOperand = opInst->getOperand(state.operandIndex);
239 // Increment 'operandIndex' in 'state'.
240 ++state.operandIndex;
241 // Add 'nextOperand' to worklist.
242 worklist.push_back({nextOperand, 0});
243 } else {
244 // Post-visit: done visiting operands AffineApplyOp, pop off stack.
245 worklist.pop_back();
246 }
247 }
248}
249
250// Builds a system of constraints with dimensional variables corresponding to
251// the loop IVs of the forOps appearing in that order. Any symbols founds in
252// the bound operands are added as symbols in the system. Returns failure for
253// the yet unimplemented cases.
254// TODO: Handle non-unit steps through local variables or stride information in
255// FlatAffineValueConstraints. (For eg., by using iv - lb % step = 0 and/or by
256// introducing a method in FlatAffineValueConstraints
257// setExprStride(ArrayRef<int64_t> expr, int64_t stride)
262 size_t numDims = 0;
263 for (Operation *op : ops) {
264 if (!isa<AffineForOp, AffineIfOp, AffineParallelOp>(op)) {
265 LLVM_DEBUG(llvm::dbgs() << "getIndexSet only handles affine.for/if/"
266 "parallel ops");
267 return failure();
268 }
269 if (AffineForOp forOp = dyn_cast<AffineForOp>(op)) {
270 loopOps.push_back(forOp);
271 // An AffineForOp retains only 1 induction variable.
272 numDims += 1;
273 } else if (AffineParallelOp parallelOp = dyn_cast<AffineParallelOp>(op)) {
274 loopOps.push_back(parallelOp);
275 numDims += parallelOp.getNumDims();
276 }
277 }
279 // Reset while associating Values in 'indices' to the domain.
280 *domain = FlatAffineValueConstraints(numDims, /*numSymbols=*/0,
281 /*numLocals=*/0, indices);
282 for (Operation *op : ops) {
283 // Add constraints from forOp's bounds.
284 if (AffineForOp forOp = dyn_cast<AffineForOp>(op)) {
285 if (failed(domain->addAffineForOpDomain(forOp)))
286 return failure();
287 } else if (auto ifOp = dyn_cast<AffineIfOp>(op)) {
288 domain->addAffineIfOpDomain(ifOp);
289 } else if (auto parallelOp = dyn_cast<AffineParallelOp>(op))
290 if (failed(domain->addAffineParallelOpDomain(parallelOp)))
291 return failure();
292 }
293 return success();
294}
295
296/// Computes the iteration domain for 'op' and populates 'indexSet', which
297/// encapsulates the constraints involving loops surrounding 'op' and
298/// potentially involving any Function symbols. The dimensional variables in
299/// 'indexSet' correspond to the loops surrounding 'op' from outermost to
300/// innermost.
301static LogicalResult getOpIndexSet(Operation *op,
302 FlatAffineValueConstraints *indexSet) {
304 getEnclosingAffineOps(*op, &ops);
305
306 // getIndexSet(ops, indexSet) will add constraints only for for the then
307 // block, so if op is part of the else block, then the indexSet ends up being
308 // wrong. So instead, any AffineIfOp where op is in the else block is removed.
309 //
310 // TODO: make memory dependence check able to handle the complement of the
311 // AffineIfOp integer set.
312 llvm::erase_if(ops, [&](Operation *affineOp) {
313 auto ifOp = dyn_cast<AffineIfOp>(affineOp);
314 return ifOp && ifOp.hasElse() &&
315 ifOp.getElseRegion().isAncestor(op->getParentRegion());
316 });
317
318 return getIndexSet(ops, indexSet);
319}
320
321// Returns the number of outer loop common to 'src/dstDomain'.
322// Loops common to 'src/dst' domains are added to 'commonLoops' if non-null.
323static unsigned
325 const FlatAffineValueConstraints &dstDomain,
326 SmallVectorImpl<AffineForOp> *commonLoops = nullptr) {
327 // Find the number of common loops shared by src and dst accesses.
328 unsigned minNumLoops =
329 std::min(srcDomain.getNumDimVars(), dstDomain.getNumDimVars());
330 unsigned numCommonLoops = 0;
331 for (unsigned i = 0; i < minNumLoops; ++i) {
332 if ((!isAffineForInductionVar(srcDomain.getValue(i)) &&
333 !isAffineParallelInductionVar(srcDomain.getValue(i))) ||
334 (!isAffineForInductionVar(dstDomain.getValue(i)) &&
335 !isAffineParallelInductionVar(dstDomain.getValue(i))) ||
336 srcDomain.getValue(i) != dstDomain.getValue(i))
337 break;
338 if (commonLoops != nullptr)
339 commonLoops->push_back(getForInductionVarOwner(srcDomain.getValue(i)));
340 ++numCommonLoops;
341 }
342 if (commonLoops != nullptr)
343 assert(commonLoops->size() == numCommonLoops);
344 return numCommonLoops;
345}
346
347/// Returns the closest surrounding block common to `opA` and `opB`. `opA` and
348/// `opB` should be in the same affine scope. Returns nullptr if such a block
349/// does not exist (when the two ops are in different blocks of an op starting
350/// an `AffineScope`).
352 // Get the chain of ancestor blocks for the given `MemRefAccess` instance. The
353 // chain extends up to and includnig an op that starts an affine scope.
354 auto getChainOfAncestorBlocks =
355 [&](Operation *op, SmallVectorImpl<Block *> &ancestorBlocks) {
356 Block *currBlock = op->getBlock();
357 // Loop terminates when the currBlock is nullptr or its parent operation
358 // holds an affine scope.
359 while (currBlock &&
360 !currBlock->getParentOp()->hasTrait<OpTrait::AffineScope>()) {
361 ancestorBlocks.push_back(currBlock);
362 currBlock = currBlock->getParentOp()->getBlock();
363 }
364 assert(currBlock &&
365 "parent op starting an affine scope is always expected");
366 ancestorBlocks.push_back(currBlock);
367 };
368
369 // Find the closest common block.
370 SmallVector<Block *, 4> srcAncestorBlocks, dstAncestorBlocks;
371 getChainOfAncestorBlocks(opA, srcAncestorBlocks);
372 getChainOfAncestorBlocks(opB, dstAncestorBlocks);
373
374 Block *commonBlock = nullptr;
375 for (int i = srcAncestorBlocks.size() - 1, j = dstAncestorBlocks.size() - 1;
376 i >= 0 && j >= 0 && srcAncestorBlocks[i] == dstAncestorBlocks[j];
377 i--, j--)
378 commonBlock = srcAncestorBlocks[i];
379
380 return commonBlock;
381}
382
383/// Returns true if the ancestor operation of 'srcAccess' appears before the
384/// ancestor operation of 'dstAccess' in their common ancestral block. The
385/// operations for `srcAccess` and `dstAccess` are expected to be in the same
386/// affine scope and have a common surrounding block within it.
388 const MemRefAccess &dstAccess) {
389 // Get Block common to 'srcAccess.opInst' and 'dstAccess.opInst'.
390 Block *commonBlock =
391 getCommonBlockInAffineScope(srcAccess.opInst, dstAccess.opInst);
392 assert(commonBlock &&
393 "ops expected to have a common surrounding block in affine scope");
394
395 // Check the dominance relationship between the respective ancestors of the
396 // src and dst in the Block of the innermost among the common loops.
397 Operation *srcOp = commonBlock->findAncestorOpInBlock(*srcAccess.opInst);
398 assert(srcOp && "src access op must lie in common block");
399 Operation *dstOp = commonBlock->findAncestorOpInBlock(*dstAccess.opInst);
400 assert(dstOp && "dest access op must lie in common block");
401
402 // Determine whether dstOp comes after srcOp.
403 return srcOp->isBeforeInBlock(dstOp);
404}
405
406// Adds ordering constraints to 'dependenceDomain' based on number of loops
407// common to 'src/dstDomain' and requested 'loopDepth'.
408// Note that 'loopDepth' cannot exceed the number of common loops plus one.
409// EX: Given a loop nest of depth 2 with IVs 'i' and 'j':
410// *) If 'loopDepth == 1' then one constraint is added: i' >= i + 1
411// *) If 'loopDepth == 2' then two constraints are added: i == i' and j' > j + 1
412// *) If 'loopDepth == 3' then two constraints are added: i == i' and j == j'
414 const FlatAffineValueConstraints &dstDomain,
415 unsigned loopDepth,
416 IntegerRelation *dependenceDomain) {
417 unsigned numCols = dependenceDomain->getNumCols();
418 SmallVector<int64_t, 4> eq(numCols);
419 unsigned numSrcDims = srcDomain.getNumDimVars();
420 unsigned numCommonLoops = getNumCommonLoops(srcDomain, dstDomain);
421 unsigned numCommonLoopConstraints = std::min(numCommonLoops, loopDepth);
422 for (unsigned i = 0; i < numCommonLoopConstraints; ++i) {
423 llvm::fill(eq, 0);
424 eq[i] = -1;
425 eq[i + numSrcDims] = 1;
426 if (i == loopDepth - 1) {
427 eq[numCols - 1] = -1;
428 dependenceDomain->addInequality(eq);
429 } else {
430 dependenceDomain->addEquality(eq);
431 }
432 }
433}
434
435// Computes distance and direction vectors in 'dependences', by adding
436// variables to 'dependenceDomain' which represent the difference of the IVs,
437// eliminating all other variables, and reading off distance vectors from
438// equality constraints (if possible), and direction vectors from inequalities.
440 const FlatAffineValueConstraints &srcDomain,
441 const FlatAffineValueConstraints &dstDomain, unsigned loopDepth,
442 IntegerPolyhedron *dependenceDomain,
443 SmallVector<DependenceComponent, 2> *dependenceComponents) {
444 // Find the number of common loops shared by src and dst accesses.
445 SmallVector<AffineForOp, 4> commonLoops;
446 unsigned numCommonLoops =
447 getNumCommonLoops(srcDomain, dstDomain, &commonLoops);
448 if (numCommonLoops == 0)
449 return;
450 // Compute direction vectors for requested loop depth.
451 unsigned numIdsToEliminate = dependenceDomain->getNumVars();
452 // Add new variables to 'dependenceDomain' to represent the direction
453 // constraints for each shared loop.
454 dependenceDomain->insertVar(VarKind::SetDim, /*pos=*/0,
455 /*num=*/numCommonLoops);
456
457 // Add equality constraints for each common loop, setting newly introduced
458 // variable at column 'j' to the 'dst' IV minus the 'src IV.
460 eq.resize(dependenceDomain->getNumCols());
461 unsigned numSrcDims = srcDomain.getNumDimVars();
462 // Constraint variables format:
463 // [num-common-loops][num-src-dim-ids][num-dst-dim-ids][num-symbols][constant]
464 for (unsigned j = 0; j < numCommonLoops; ++j) {
465 llvm::fill(eq, 0);
466 eq[j] = 1;
467 eq[j + numCommonLoops] = 1;
468 eq[j + numCommonLoops + numSrcDims] = -1;
469 dependenceDomain->addEquality(eq);
470 }
471
472 // Eliminate all variables other than the direction variables just added.
473 dependenceDomain->projectOut(numCommonLoops, numIdsToEliminate);
474
475 // Scan each common loop variable column and set direction vectors based
476 // on eliminated constraint system.
477 dependenceComponents->resize(numCommonLoops);
478 for (unsigned j = 0; j < numCommonLoops; ++j) {
479 (*dependenceComponents)[j].op = commonLoops[j].getOperation();
480 auto lbConst = dependenceDomain->getConstantBound64(BoundType::LB, j);
481 (*dependenceComponents)[j].lb =
482 lbConst.value_or(std::numeric_limits<int64_t>::min());
483 auto ubConst = dependenceDomain->getConstantBound64(BoundType::UB, j);
484 (*dependenceComponents)[j].ub =
485 ubConst.value_or(std::numeric_limits<int64_t>::max());
486 }
487}
488
489LogicalResult
491 const FlatAffineValueConstraints &domain,
492 IntegerRelation &rel) {
493 // Get access relation from access map.
494 if (failed(getRelationFromMap(accessValueMap, rel)))
495 return failure();
496
497 // Merge and align domain ids of `rel` with ids of `domain`. Since the domain
498 // of the access map is a subset of the domain of access, the domain ids of
499 // `rel` are guranteed to be a subset of ids of `domain`.
500 unsigned inserts = 0;
501 for (unsigned i = 0, e = domain.getNumDimVars(); i < e; ++i) {
502 const Identifier domainIdi = Identifier(domain.getValue(i));
503 const Identifier *findBegin = rel.getIds(VarKind::SetDim).begin() + i;
504 const Identifier *findEnd = rel.getIds(VarKind::SetDim).end();
505 const Identifier *itr = std::find(findBegin, findEnd, domainIdi);
506 if (itr != findEnd) {
507 rel.swapVar(i, i + std::distance(findBegin, itr));
508 } else {
509 ++inserts;
510 rel.insertVar(VarKind::SetDim, i);
511 rel.setId(VarKind::SetDim, i, domainIdi);
512 }
513 }
514
515 // Append domain constraints to `rel`.
516 IntegerRelation domainRel = domain;
517 // For 0-d spaces, there will be no IDs. Enable if that's the case.
518 if (!domainRel.getSpace().isUsingIds())
519 domainRel.resetIds();
520 if (!rel.getSpace().isUsingIds())
521 rel.resetIds();
522 domainRel.appendVar(VarKind::Range, accessValueMap.getNumResults());
523 domainRel.mergeAndAlignSymbols(rel);
524 domainRel.mergeLocalVars(rel);
525 rel.append(domainRel);
526
527 rel.convertVarKind(VarKind::SetDim, 0, accessValueMap.getNumDims() + inserts,
528 VarKind::Domain);
529
530 return success();
531}
532
534 // Create set corresponding to domain of access.
536 if (failed(getOpIndexSet(opInst, &domain)))
537 return failure();
538
539 AffineValueMap accessValueMap;
540 getAccessMap(&accessValueMap);
541 return mlir::affine::getAccessRelation(accessValueMap, domain, rel);
542}
543
544// Populates 'accessMap' with composition of AffineApplyOps reachable from
545// indices of MemRefAccess.
547 // Get affine map from AffineLoad/Store.
548 AffineMap map;
549 if (auto loadOp = dyn_cast<AffineReadOpInterface>(opInst))
550 map = loadOp.getAffineMap();
551 else
552 map = cast<AffineWriteOpInterface>(opInst).getAffineMap();
553
554 SmallVector<Value, 8> operands(indices.begin(), indices.end());
555 fullyComposeAffineMapAndOperands(&map, &operands);
556 map = simplifyAffineMap(map);
557 canonicalizeMapAndOperands(&map, &operands);
558 accessMap->reset(map, operands);
559}
560
561// Builds a flat affine constraint system to check if there exists a dependence
562// between memref accesses 'srcAccess' and 'dstAccess'.
563// Returns 'NoDependence' if the accesses can be definitively shown not to
564// access the same element.
565// Returns 'HasDependence' if the accesses do access the same element.
566// Returns 'Failure' if an error or unsupported case was encountered.
567// If a dependence exists, returns in 'dependenceComponents' a direction
568// vector for the dependence, with a component for each loop IV in loops
569// common to both accesses (see Dependence in AffineAnalysis.h for details).
570//
571// The memref access dependence check is comprised of the following steps:
572// *) Build access relation for each access. An access relation maps elements
573// of an iteration domain to the element(s) of an array domain accessed by
574// that iteration of the associated statement through some array reference.
575// *) Compute the dependence relation by composing access relation of
576// `srcAccess` with the inverse of access relation of `dstAccess`.
577// Doing this builds a relation between iteration domain of `srcAccess`
578// to the iteration domain of `dstAccess` which access the same memory
579// location.
580// *) Add ordering constraints for `srcAccess` to be accessed before
581// `dstAccess`.
582//
583// This method builds a constraint system with the following column format:
584//
585// [src-dim-variables, dst-dim-variables, symbols, constant]
586//
587// For example, given the following MLIR code with "source" and "destination"
588// accesses to the same memref label, and symbols %M, %N, %K:
589//
590// affine.for %i0 = 0 to 100 {
591// affine.for %i1 = 0 to 50 {
592// %a0 = affine.apply
593// (d0, d1) -> (d0 * 2 - d1 * 4 + s1, d1 * 3 - s0) (%i0, %i1)[%M, %N]
594// // Source memref access.
595// store %v0, %m[%a0#0, %a0#1] : memref<4x4xf32>
596// }
597// }
598//
599// affine.for %i2 = 0 to 100 {
600// affine.for %i3 = 0 to 50 {
601// %a1 = affine.apply
602// (d0, d1) -> (d0 * 7 + d1 * 9 - s1, d1 * 11 + s0) (%i2, %i3)[%K, %M]
603// // Destination memref access.
604// %v1 = load %m[%a1#0, %a1#1] : memref<4x4xf32>
605// }
606// }
607//
608// The access relation for `srcAccess` would be the following:
609//
610// [src_dim0, src_dim1, mem_dim0, mem_dim1, %N, %M, const]
611// 2 -4 -1 0 1 0 0 = 0
612// 0 3 0 -1 0 -1 0 = 0
613// 1 0 0 0 0 0 0 >= 0
614// -1 0 0 0 0 0 100 >= 0
615// 0 1 0 0 0 0 0 >= 0
616// 0 -1 0 0 0 0 50 >= 0
617//
618// The access relation for `dstAccess` would be the following:
619//
620// [dst_dim0, dst_dim1, mem_dim0, mem_dim1, %M, %K, const]
621// 7 9 -1 0 -1 0 0 = 0
622// 0 11 0 -1 0 -1 0 = 0
623// 1 0 0 0 0 0 0 >= 0
624// -1 0 0 0 0 0 100 >= 0
625// 0 1 0 0 0 0 0 >= 0
626// 0 -1 0 0 0 0 50 >= 0
627//
628// The equalities in the above relations correspond to the access maps while
629// the inequalities corresspond to the iteration domain constraints.
630//
631// The dependence relation formed:
632//
633// [src_dim0, src_dim1, dst_dim0, dst_dim1, %M, %N, %K, const]
634// 2 -4 -7 -9 1 1 0 0 = 0
635// 0 3 0 -11 -1 0 1 0 = 0
636// 1 0 0 0 0 0 0 0 >= 0
637// -1 0 0 0 0 0 0 100 >= 0
638// 0 1 0 0 0 0 0 0 >= 0
639// 0 -1 0 0 0 0 0 50 >= 0
640// 0 0 1 0 0 0 0 0 >= 0
641// 0 0 -1 0 0 0 0 100 >= 0
642// 0 0 0 1 0 0 0 0 >= 0
643// 0 0 0 -1 0 0 0 50 >= 0
644//
645//
646// TODO: Support AffineExprs mod/floordiv/ceildiv.
648 const MemRefAccess &srcAccess, const MemRefAccess &dstAccess,
649 unsigned loopDepth, FlatAffineValueConstraints *dependenceConstraints,
650 SmallVector<DependenceComponent, 2> *dependenceComponents, bool allowRAR) {
651 LLVM_DEBUG(llvm::dbgs() << "Checking for dependence at depth: "
652 << Twine(loopDepth) << " between:\n";);
653 LLVM_DEBUG(srcAccess.opInst->dump());
654 LLVM_DEBUG(dstAccess.opInst->dump());
655
656 // Return 'NoDependence' if these accesses do not access the same memref.
657 if (srcAccess.memref != dstAccess.memref)
659
660 // Return 'NoDependence' if one of these accesses is not an
661 // AffineWriteOpInterface.
662 if (!allowRAR && !isa<AffineWriteOpInterface>(srcAccess.opInst) &&
663 !isa<AffineWriteOpInterface>(dstAccess.opInst))
665
666 // We can't analyze further if the ops lie in different affine scopes or have
667 // no common block in an affine scope.
668 if (getAffineAnalysisScope(srcAccess.opInst) !=
671 if (!getCommonBlockInAffineScope(srcAccess.opInst, dstAccess.opInst))
673
674 // Create access relation from each MemRefAccess.
676 IntegerRelation srcRel(space), dstRel(space);
677 if (failed(srcAccess.getAccessRelation(srcRel)))
679 if (failed(dstAccess.getAccessRelation(dstRel)))
681
682 FlatAffineValueConstraints srcDomain(srcRel.getDomainSet());
683 FlatAffineValueConstraints dstDomain(dstRel.getDomainSet());
684
685 // Return 'NoDependence' if loopDepth > numCommonLoops and if the ancestor
686 // operation of 'srcAccess' does not properly dominate the ancestor
687 // operation of 'dstAccess' in the same common operation block.
688 // Note: this check is skipped if 'allowRAR' is true, because RAR deps
689 // can exist irrespective of lexicographic ordering b/w src and dst.
690 unsigned numCommonLoops = getNumCommonLoops(srcDomain, dstDomain);
691 assert(loopDepth <= numCommonLoops + 1 && "Invalid depth");
692 if (!allowRAR && loopDepth > numCommonLoops &&
693 !srcAppearsBeforeDstInAncestralBlock(srcAccess, dstAccess)) {
695 }
696
697 return checkAccessDependence(std::move(srcRel), std::move(dstRel), loopDepth,
698 dependenceConstraints, dependenceComponents);
699}
700
702 IntegerRelation &&srcRel, IntegerRelation &&dstRel, unsigned loopDepth,
703 FlatAffineValueConstraints *dependenceConstraints,
704 SmallVector<DependenceComponent, 2> *dependenceComponents) {
705 FlatAffineValueConstraints srcDomain(srcRel.getDomainSet());
706 FlatAffineValueConstraints dstDomain(dstRel.getDomainSet());
707 assert(loopDepth <= getNumCommonLoops(srcDomain, dstDomain) + 1 &&
708 "Invalid depth");
709
710 // Compute the dependence relation by composing `srcRel` with the inverse of
711 // `dstRel`. Doing this builds a relation between the iteration domain of the
712 // source access to the iteration domain of the destination access which
713 // access the same memory locations.
714 dstRel.inverse();
715 // For 0-d spaces, there will be no IDs. Enable if that's the case.
716 if (!dstRel.getSpace().isUsingIds())
717 dstRel.resetIds();
718 if (!srcRel.getSpace().isUsingIds())
719 srcRel.resetIds();
720 dstRel.mergeAndCompose(srcRel);
721 dstRel.convertVarKind(VarKind::Domain, 0, dstRel.getNumDomainVars(),
722 VarKind::Range, 0);
723 IntegerPolyhedron dependenceDomain(dstRel);
724
725 // Add 'src' happens before 'dst' ordering constraints.
726 addOrderingConstraints(srcDomain, dstDomain, loopDepth, &dependenceDomain);
727
728 // Return 'NoDependence' if the solution space is empty: no dependence.
729 if (dependenceDomain.isEmpty())
731
732 // Compute dependence direction vector and return true.
733 if (dependenceComponents != nullptr)
734 computeDirectionVector(srcDomain, dstDomain, loopDepth, &dependenceDomain,
735 dependenceComponents);
736
737 LLVM_DEBUG(llvm::dbgs() << "Dependence polyhedron:\n");
738 LLVM_DEBUG(dependenceDomain.dump());
739
740 if (dependenceConstraints)
741 *dependenceConstraints = FlatAffineValueConstraints(dependenceDomain);
743}
744
745/// Gathers dependence components for dependences between all ops in loop nest
746/// rooted at 'forOp' at loop depths in range [1, maxLoopDepth].
748 AffineForOp forOp, unsigned maxLoopDepth,
749 std::vector<SmallVector<DependenceComponent, 2>> *depCompsVec) {
750 // Collect all load and store ops in loop nest rooted at 'forOp'.
751 SmallVector<Operation *, 8> loadAndStoreOps;
752 forOp->walk([&](Operation *op) {
753 if (isa<AffineReadOpInterface, AffineWriteOpInterface>(op))
754 loadAndStoreOps.push_back(op);
755 });
756
757 unsigned numOps = loadAndStoreOps.size();
758 for (unsigned d = 1; d <= maxLoopDepth; ++d) {
759 for (unsigned i = 0; i < numOps; ++i) {
760 auto *srcOp = loadAndStoreOps[i];
761 MemRefAccess srcAccess(srcOp);
762 for (unsigned j = 0; j < numOps; ++j) {
763 auto *dstOp = loadAndStoreOps[j];
764 MemRefAccess dstAccess(dstOp);
765
767 // TODO: Explore whether it would be profitable to pre-compute and store
768 // deps instead of repeatedly checking.
770 srcAccess, dstAccess, d, /*dependenceConstraints=*/nullptr,
771 &depComps);
773 depCompsVec->push_back(std::move(depComps));
774 }
775 }
776 }
777}
static LogicalResult getOpIndexSet(Operation *op, FlatAffineValueConstraints *indexSet)
Computes the iteration domain for 'op' and populates 'indexSet', which encapsulates the constraints i...
static Value getSupportedReduction(AffineForOp forOp, unsigned pos, arith::AtomicRMWKind &kind)
Get the value that is being reduced by pos-th reduction in the loop if such a reduction can be perfor...
static void computeDirectionVector(const FlatAffineValueConstraints &srcDomain, const FlatAffineValueConstraints &dstDomain, unsigned loopDepth, IntegerPolyhedron *dependenceDomain, SmallVector< DependenceComponent, 2 > *dependenceComponents)
static unsigned getNumCommonLoops(const FlatAffineValueConstraints &srcDomain, const FlatAffineValueConstraints &dstDomain, SmallVectorImpl< AffineForOp > *commonLoops=nullptr)
static bool srcAppearsBeforeDstInAncestralBlock(const MemRefAccess &srcAccess, const MemRefAccess &dstAccess)
Returns true if the ancestor operation of 'srcAccess' appears before the ancestor operation of 'dstAc...
return success()
static Block * getCommonBlockInAffineScope(Operation *opA, Operation *opB)
Returns the closest surrounding block common to opA and opB. opA and opB should be in the same affine...
static void addOrderingConstraints(const FlatAffineValueConstraints &srcDomain, const FlatAffineValueConstraints &dstDomain, unsigned loopDepth, IntegerRelation *dependenceDomain)
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
Block represents an ordered list of Operations.
Definition Block.h:34
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
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
Value getValue(unsigned pos) const
Returns the Value associated with the pos^th variable.
A trait of region holding operations that defines a new scope for polyhedral optimization purposes.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
LLVM_DUMP_METHOD void dump()
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
bool isProperAncestor(Operation *other)
Return true if this operation is a proper ancestor of the other operation.
EffectT * getEffect() const
Return the effect being applied.
Value getValue() const
Return the value the effect is applied on, or nullptr if there isn't a known value being affected.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
An AffineValueMap is an affine map plus its ML value operands and results for analysis purposes.
void reset(AffineMap map, ValueRange operands, ValueRange results={})
FlatAffineValueConstraints is an extension of FlatLinearValueConstraints with helper functions for Af...
void addAffineIfOpDomain(AffineIfOp ifOp)
Adds constraints imposed by the affine.if operation.
LogicalResult addAffineParallelOpDomain(AffineParallelOp parallelOp)
Add constraints (lower and upper bounds) for the specified 'affine.parallel' operation's Value using ...
LogicalResult addAffineForOpDomain(AffineForOp forOp)
Adds constraints (lower and upper bounds) for the specified 'affine.for' operation's Value using IR i...
An Identifier stores a pointer to an object, such as a Value or an Operation.
An IntegerPolyhedron represents the set of points from a PresburgerSpace that satisfy a list of affin...
unsigned insertVar(VarKind kind, unsigned pos, unsigned num=1) override
Insert num variables of the specified kind at position pos.
An IntegerRelation represents the set of points from a PresburgerSpace that satisfy a list of affine ...
void setId(VarKind kind, unsigned i, Identifier id)
Set the identifier for the ith variable of the specified kind of the IntegerRelation's PresburgerSpac...
virtual void swapVar(unsigned posA, unsigned posB)
Swap the posA^th variable with the posB^th variable.
ArrayRef< Identifier > getIds(VarKind kind)
Get the identifiers for the variables of specified varKind.
void convertVarKind(VarKind srcKind, unsigned varStart, unsigned varLimit, VarKind dstKind, unsigned pos)
Converts variables of kind srcKind in the range [varStart, varLimit) to variables of kind dstKind.
unsigned appendVar(VarKind kind, unsigned num=1)
Append num variables of the specified kind after the last variable of that kind.
virtual unsigned insertVar(VarKind kind, unsigned pos, unsigned num=1)
Insert num variables of the specified kind at position pos.
LLVM_DUMP_METHOD void dump() const
const PresburgerSpace & getSpace() const
Returns a reference to the underlying space.
void append(const IntegerRelation &other)
Appends constraints from other into this.
void addEquality(ArrayRef< DynamicAPInt > eq)
Adds an equality from the coefficients specified in eq.
bool isEmpty() const
Checks for emptiness by performing variable elimination on all variables, running the GCD test on eac...
unsigned getNumCols() const
Returns the number of columns in the constraint system.
IntegerPolyhedron getDomainSet() const
Return a set corresponding to all points in the domain of the relation.
void projectOut(unsigned pos, unsigned num)
Projects out (aka eliminates) num variables starting at position pos.
void addInequality(ArrayRef< DynamicAPInt > inEq)
Adds an inequality (>= 0) from the coefficients specified in inEq.
void mergeAndAlignSymbols(IntegerRelation &other)
Merge and align symbol variables of this and other with respect to identifiers.
unsigned mergeLocalVars(IntegerRelation &other)
Adds additional local vars to the sets such that they both have the union of the local vars in each s...
std::optional< int64_t > getConstantBound64(BoundType type, unsigned pos) const
The same, but casts to int64_t.
PresburgerSpace is the space of all possible values of a tuple of integer valued variables/variables.
bool isUsingIds() const
Returns if identifiers are being used.
static PresburgerSpace getRelationSpace(unsigned numDomain=0, unsigned numRange=0, unsigned numSymbols=0, unsigned numLocals=0)
SideEffects::EffectInstance< Effect > EffectInstance
LogicalResult getAccessRelation(const AffineValueMap &accessValueMap, const FlatAffineValueConstraints &domain, presburger::IntegerRelation &rel)
Builds in rel the access relation of an access that reads or writes accessValueMap over the iteration...
void getEnclosingAffineOps(Operation &op, SmallVectorImpl< Operation * > *ops)
Populates 'ops' with affine operations enclosing op ordered from outermost to innermost while stoppin...
Definition Utils.cpp:880
LogicalResult getIndexSet(MutableArrayRef< Operation * > ops, FlatAffineValueConstraints *domain)
Builds a system of constraints with dimensional variables corresponding to the loop IVs of the forOps...
AffineForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
void getSupportedReductions(AffineForOp forOp, SmallVectorImpl< LoopReduction > &supportedReductions)
Populate supportedReductions with descriptors of the supported reductions.
DependenceResult checkMemrefAccessDependence(const MemRefAccess &srcAccess, const MemRefAccess &dstAccess, unsigned loopDepth, FlatAffineValueConstraints *dependenceConstraints=nullptr, SmallVector< DependenceComponent, 2 > *dependenceComponents=nullptr, bool allowRAR=false)
void canonicalizeMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands)
Modifies both map and operands in-place so as to:
void getReachableAffineApplyOps(ArrayRef< Value > operands, SmallVectorImpl< Operation * > &affineApplyOps)
Returns in affineApplyOps, the sequence of those AffineApplyOp Operations that are reachable via a se...
DependenceResult checkAccessDependence(presburger::IntegerRelation &&srcRel, presburger::IntegerRelation &&dstRel, unsigned loopDepth, FlatAffineValueConstraints *dependenceConstraints=nullptr, SmallVector< DependenceComponent, 2 > *dependenceComponents=nullptr)
Checks whether the accesses two relations describe touch the same element, i.e.
bool isAffineForInductionVar(Value val)
Returns true if the provided value is the induction variable of an AffineForOp.
void getDependenceComponents(AffineForOp forOp, unsigned maxLoopDepth, std::vector< SmallVector< DependenceComponent, 2 > > *depCompsVec)
Returns in 'depCompsVec', dependence components for dependences between all load and store ops in loo...
bool isLoopMemoryParallel(AffineForOp forOp)
Returns true if ‘forOp’ is a parallel loop.
Region * getAffineAnalysisScope(Operation *op)
Returns the closest region enclosing op that is held by a non-affine operation; nullptr if there is n...
void fullyComposeAffineMapAndOperands(AffineMap *map, SmallVectorImpl< Value > *operands, bool composeAffineMin=false)
Given an affine map map and its input operands, this method composes into map, maps of AffineApplyOps...
LogicalResult getRelationFromMap(AffineMap &map, presburger::IntegerRelation &rel)
Builds a relation from the given AffineMap/AffineValueMap map, containing all pairs of the form opera...
void extractInductionVars(ArrayRef< Operation * > affineOps, SmallVectorImpl< Value > &ivs)
Extracts the induction variables from a list of either AffineForOp or AffineParallelOp and places the...
bool hasDependence(DependenceResult result)
Utility function that returns true if the provided DependenceResult corresponds to a dependence resul...
unsigned getNestingDepth(Operation *op)
Returns the nesting depth of this operation, i.e., the number of loops surrounding this operation.
Definition Utils.cpp:2093
bool isAffineParallelInductionVar(Value val)
Returns true if val is the induction variable of an AffineParallelOp.
Include the generated interface declarations.
AffineMap simplifyAffineMap(AffineMap map)
Simplifies an affine map by simplifying its underlying AffineExpr results.
bool hasSingleEffect(Operation *op)
Returns "true" if op has only an effect of type EffectTy.
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
Value matchReduction(ArrayRef< BlockArgument > iterCarriedArgs, unsigned redPos, SmallVectorImpl< Operation * > &combinerOps)
Utility to match a generic reduction given a list of iteration-carried arguments, iterCarriedArgs and...
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
Checks whether two accesses to the same memref access the same element.
A description of a (parallelizable) reduction in an affine loop.
Encapsulates a memref load or store access information.
SmallVector< Value, 4 > indices
LogicalResult getAccessRelation(presburger::IntegerRelation &accessRel) const
Creates an access relation for the access.
void getAccessMap(AffineValueMap *accessMap) const
Populates 'accessMap' with composition of AffineApplyOps reachable from 'indices'.
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.