1 //===- Utils.cpp ---- Utilities for affine dialect transformation ---------===// 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 transformation utilities for the Affine 10 // dialect. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/Dialect/Affine/Utils.h" 15 #include "mlir/Analysis/Utils.h" 16 #include "mlir/Dialect/Affine/IR/AffineOps.h" 17 #include "mlir/Dialect/Affine/IR/AffineValueMap.h" 18 #include "mlir/IR/BlockAndValueMapping.h" 19 #include "mlir/IR/IntegerSet.h" 20 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 21 #include "mlir/Transforms/LoopUtils.h" 22 23 using namespace mlir; 24 25 /// Promotes the `then` or the `else` block of `ifOp` (depending on whether 26 /// `elseBlock` is false or true) into `ifOp`'s containing block, and discards 27 /// the rest of the op. 28 static void promoteIfBlock(AffineIfOp ifOp, bool elseBlock) { 29 if (elseBlock) 30 assert(ifOp.hasElse() && "else block expected"); 31 32 Block *destBlock = ifOp->getBlock(); 33 Block *srcBlock = elseBlock ? ifOp.getElseBlock() : ifOp.getThenBlock(); 34 destBlock->getOperations().splice( 35 Block::iterator(ifOp), srcBlock->getOperations(), srcBlock->begin(), 36 std::prev(srcBlock->end())); 37 ifOp.erase(); 38 } 39 40 /// Returns the outermost affine.for/parallel op that the `ifOp` is invariant 41 /// on. The `ifOp` could be hoisted and placed right before such an operation. 42 /// This method assumes that the ifOp has been canonicalized (to be correct and 43 /// effective). 44 static Operation *getOutermostInvariantForOp(AffineIfOp ifOp) { 45 // Walk up the parents past all for op that this conditional is invariant on. 46 auto ifOperands = ifOp.getOperands(); 47 auto *res = ifOp.getOperation(); 48 while (!isa<FuncOp>(res->getParentOp())) { 49 auto *parentOp = res->getParentOp(); 50 if (auto forOp = dyn_cast<AffineForOp>(parentOp)) { 51 if (llvm::is_contained(ifOperands, forOp.getInductionVar())) 52 break; 53 } else if (auto parallelOp = dyn_cast<AffineParallelOp>(parentOp)) { 54 for (auto iv : parallelOp.getIVs()) 55 if (llvm::is_contained(ifOperands, iv)) 56 break; 57 } else if (!isa<AffineIfOp>(parentOp)) { 58 // Won't walk up past anything other than affine.for/if ops. 59 break; 60 } 61 // You can always hoist up past any affine.if ops. 62 res = parentOp; 63 } 64 return res; 65 } 66 67 /// A helper for the mechanics of mlir::hoistAffineIfOp. Hoists `ifOp` just over 68 /// `hoistOverOp`. Returns the new hoisted op if any hoisting happened, 69 /// otherwise the same `ifOp`. 70 static AffineIfOp hoistAffineIfOp(AffineIfOp ifOp, Operation *hoistOverOp) { 71 // No hoisting to do. 72 if (hoistOverOp == ifOp) 73 return ifOp; 74 75 // Create the hoisted 'if' first. Then, clone the op we are hoisting over for 76 // the else block. Then drop the else block of the original 'if' in the 'then' 77 // branch while promoting its then block, and analogously drop the 'then' 78 // block of the original 'if' from the 'else' branch while promoting its else 79 // block. 80 BlockAndValueMapping operandMap; 81 OpBuilder b(hoistOverOp); 82 auto hoistedIfOp = b.create<AffineIfOp>(ifOp.getLoc(), ifOp.getIntegerSet(), 83 ifOp.getOperands(), 84 /*elseBlock=*/true); 85 86 // Create a clone of hoistOverOp to use for the else branch of the hoisted 87 // conditional. The else block may get optimized away if empty. 88 Operation *hoistOverOpClone = nullptr; 89 // We use this unique name to identify/find `ifOp`'s clone in the else 90 // version. 91 Identifier idForIfOp = b.getIdentifier("__mlir_if_hoisting"); 92 operandMap.clear(); 93 b.setInsertionPointAfter(hoistOverOp); 94 // We'll set an attribute to identify this op in a clone of this sub-tree. 95 ifOp->setAttr(idForIfOp, b.getBoolAttr(true)); 96 hoistOverOpClone = b.clone(*hoistOverOp, operandMap); 97 98 // Promote the 'then' block of the original affine.if in the then version. 99 promoteIfBlock(ifOp, /*elseBlock=*/false); 100 101 // Move the then version to the hoisted if op's 'then' block. 102 auto *thenBlock = hoistedIfOp.getThenBlock(); 103 thenBlock->getOperations().splice(thenBlock->begin(), 104 hoistOverOp->getBlock()->getOperations(), 105 Block::iterator(hoistOverOp)); 106 107 // Find the clone of the original affine.if op in the else version. 108 AffineIfOp ifCloneInElse; 109 hoistOverOpClone->walk([&](AffineIfOp ifClone) { 110 if (!ifClone->getAttr(idForIfOp)) 111 return WalkResult::advance(); 112 ifCloneInElse = ifClone; 113 return WalkResult::interrupt(); 114 }); 115 assert(ifCloneInElse && "if op clone should exist"); 116 // For the else block, promote the else block of the original 'if' if it had 117 // one; otherwise, the op itself is to be erased. 118 if (!ifCloneInElse.hasElse()) 119 ifCloneInElse.erase(); 120 else 121 promoteIfBlock(ifCloneInElse, /*elseBlock=*/true); 122 123 // Move the else version into the else block of the hoisted if op. 124 auto *elseBlock = hoistedIfOp.getElseBlock(); 125 elseBlock->getOperations().splice( 126 elseBlock->begin(), hoistOverOpClone->getBlock()->getOperations(), 127 Block::iterator(hoistOverOpClone)); 128 129 return hoistedIfOp; 130 } 131 132 LogicalResult 133 mlir::affineParallelize(AffineForOp forOp, 134 ArrayRef<LoopReduction> parallelReductions) { 135 // Fail early if there are iter arguments that are not reductions. 136 unsigned numReductions = parallelReductions.size(); 137 if (numReductions != forOp.getNumIterOperands()) 138 return failure(); 139 140 Location loc = forOp.getLoc(); 141 OpBuilder outsideBuilder(forOp); 142 AffineMap lowerBoundMap = forOp.getLowerBoundMap(); 143 ValueRange lowerBoundOperands = forOp.getLowerBoundOperands(); 144 AffineMap upperBoundMap = forOp.getUpperBoundMap(); 145 ValueRange upperBoundOperands = forOp.getUpperBoundOperands(); 146 147 // Creating empty 1-D affine.parallel op. 148 auto reducedValues = llvm::to_vector<4>(llvm::map_range( 149 parallelReductions, [](const LoopReduction &red) { return red.value; })); 150 auto reductionKinds = llvm::to_vector<4>(llvm::map_range( 151 parallelReductions, [](const LoopReduction &red) { return red.kind; })); 152 AffineParallelOp newPloop = outsideBuilder.create<AffineParallelOp>( 153 loc, ValueRange(reducedValues).getTypes(), reductionKinds, 154 llvm::makeArrayRef(lowerBoundMap), lowerBoundOperands, 155 llvm::makeArrayRef(upperBoundMap), upperBoundOperands, 156 llvm::makeArrayRef(forOp.getStep())); 157 // Steal the body of the old affine for op. 158 newPloop.region().takeBody(forOp.region()); 159 Operation *yieldOp = &newPloop.getBody()->back(); 160 161 // Handle the initial values of reductions because the parallel loop always 162 // starts from the neutral value. 163 SmallVector<Value> newResults; 164 newResults.reserve(numReductions); 165 for (unsigned i = 0; i < numReductions; ++i) { 166 Value init = forOp.getIterOperands()[i]; 167 // This works because we are only handling single-op reductions at the 168 // moment. A switch on reduction kind or a mechanism to collect operations 169 // participating in the reduction will be necessary for multi-op reductions. 170 Operation *reductionOp = yieldOp->getOperand(i).getDefiningOp(); 171 assert(reductionOp && "yielded value is expected to be produced by an op"); 172 outsideBuilder.getInsertionBlock()->getOperations().splice( 173 outsideBuilder.getInsertionPoint(), newPloop.getBody()->getOperations(), 174 reductionOp); 175 reductionOp->setOperands({init, newPloop->getResult(i)}); 176 forOp->getResult(i).replaceAllUsesWith(reductionOp->getResult(0)); 177 } 178 179 // Update the loop terminator to yield reduced values bypassing the reduction 180 // operation itself (now moved outside of the loop) and erase the block 181 // arguments that correspond to reductions. Note that the loop always has one 182 // "main" induction variable whenc coming from a non-parallel for. 183 unsigned numIVs = 1; 184 yieldOp->setOperands(reducedValues); 185 newPloop.getBody()->eraseArguments( 186 llvm::to_vector<4>(llvm::seq<unsigned>(numIVs, numReductions + numIVs))); 187 188 forOp.erase(); 189 return success(); 190 } 191 192 // Returns success if any hoisting happened. 193 LogicalResult mlir::hoistAffineIfOp(AffineIfOp ifOp, bool *folded) { 194 // Bail out early if the ifOp returns a result. TODO: Consider how to 195 // properly support this case. 196 if (ifOp.getNumResults() != 0) 197 return failure(); 198 199 // Apply canonicalization patterns and folding - this is necessary for the 200 // hoisting check to be correct (operands should be composed), and to be more 201 // effective (no unused operands). Since the pattern rewriter's folding is 202 // entangled with application of patterns, we may fold/end up erasing the op, 203 // in which case we return with `folded` being set. 204 RewritePatternSet patterns(ifOp.getContext()); 205 AffineIfOp::getCanonicalizationPatterns(patterns, ifOp.getContext()); 206 bool erased; 207 FrozenRewritePatternSet frozenPatterns(std::move(patterns)); 208 (void)applyOpPatternsAndFold(ifOp, frozenPatterns, &erased); 209 if (erased) { 210 if (folded) 211 *folded = true; 212 return failure(); 213 } 214 if (folded) 215 *folded = false; 216 217 // The folding above should have ensured this, but the affine.if's 218 // canonicalization is missing composition of affine.applys into it. 219 assert(llvm::all_of(ifOp.getOperands(), 220 [](Value v) { 221 return isTopLevelValue(v) || isForInductionVar(v); 222 }) && 223 "operands not composed"); 224 225 // We are going hoist as high as possible. 226 // TODO: this could be customized in the future. 227 auto *hoistOverOp = getOutermostInvariantForOp(ifOp); 228 229 AffineIfOp hoistedIfOp = ::hoistAffineIfOp(ifOp, hoistOverOp); 230 // Nothing to hoist over. 231 if (hoistedIfOp == ifOp) 232 return failure(); 233 234 // Canonicalize to remove dead else blocks (happens whenever an 'if' moves up 235 // a sequence of affine.fors that are all perfectly nested). 236 (void)applyPatternsAndFoldGreedily( 237 hoistedIfOp->getParentWithTrait<OpTrait::IsIsolatedFromAbove>(), 238 frozenPatterns); 239 240 return success(); 241 } 242 243 // Return the min expr after replacing the given dim. 244 AffineExpr mlir::substWithMin(AffineExpr e, AffineExpr dim, AffineExpr min, 245 AffineExpr max, bool positivePath) { 246 if (e == dim) 247 return positivePath ? min : max; 248 if (auto bin = e.dyn_cast<AffineBinaryOpExpr>()) { 249 AffineExpr lhs = bin.getLHS(); 250 AffineExpr rhs = bin.getRHS(); 251 if (bin.getKind() == mlir::AffineExprKind::Add) 252 return substWithMin(lhs, dim, min, max, positivePath) + 253 substWithMin(rhs, dim, min, max, positivePath); 254 255 auto c1 = bin.getLHS().dyn_cast<AffineConstantExpr>(); 256 auto c2 = bin.getRHS().dyn_cast<AffineConstantExpr>(); 257 if (c1 && c1.getValue() < 0) 258 return getAffineBinaryOpExpr( 259 bin.getKind(), c1, substWithMin(rhs, dim, min, max, !positivePath)); 260 if (c2 && c2.getValue() < 0) 261 return getAffineBinaryOpExpr( 262 bin.getKind(), substWithMin(lhs, dim, min, max, !positivePath), c2); 263 return getAffineBinaryOpExpr( 264 bin.getKind(), substWithMin(lhs, dim, min, max, positivePath), 265 substWithMin(rhs, dim, min, max, positivePath)); 266 } 267 return e; 268 } 269 270 void mlir::normalizeAffineParallel(AffineParallelOp op) { 271 // Loops with min/max in bounds are not normalized at the moment. 272 if (op.hasMinMaxBounds()) 273 return; 274 275 AffineMap lbMap = op.lowerBoundsMap(); 276 SmallVector<int64_t, 8> steps = op.getSteps(); 277 // No need to do any work if the parallel op is already normalized. 278 bool isAlreadyNormalized = 279 llvm::all_of(llvm::zip(steps, lbMap.getResults()), [](auto tuple) { 280 int64_t step = std::get<0>(tuple); 281 auto lbExpr = 282 std::get<1>(tuple).template dyn_cast<AffineConstantExpr>(); 283 return lbExpr && lbExpr.getValue() == 0 && step == 1; 284 }); 285 if (isAlreadyNormalized) 286 return; 287 288 AffineValueMap ranges; 289 AffineValueMap::difference(op.getUpperBoundsValueMap(), 290 op.getLowerBoundsValueMap(), &ranges); 291 auto builder = OpBuilder::atBlockBegin(op.getBody()); 292 auto zeroExpr = builder.getAffineConstantExpr(0); 293 SmallVector<AffineExpr, 8> lbExprs; 294 SmallVector<AffineExpr, 8> ubExprs; 295 for (unsigned i = 0, e = steps.size(); i < e; ++i) { 296 int64_t step = steps[i]; 297 298 // Adjust the lower bound to be 0. 299 lbExprs.push_back(zeroExpr); 300 301 // Adjust the upper bound expression: 'range / step'. 302 AffineExpr ubExpr = ranges.getResult(i).ceilDiv(step); 303 ubExprs.push_back(ubExpr); 304 305 // Adjust the corresponding IV: 'lb + i * step'. 306 BlockArgument iv = op.getBody()->getArgument(i); 307 AffineExpr lbExpr = lbMap.getResult(i); 308 unsigned nDims = lbMap.getNumDims(); 309 auto expr = lbExpr + builder.getAffineDimExpr(nDims) * step; 310 auto map = AffineMap::get(/*dimCount=*/nDims + 1, 311 /*symbolCount=*/lbMap.getNumSymbols(), expr); 312 313 // Use an 'affine.apply' op that will be simplified later in subsequent 314 // canonicalizations. 315 OperandRange lbOperands = op.getLowerBoundsOperands(); 316 OperandRange dimOperands = lbOperands.take_front(nDims); 317 OperandRange symbolOperands = lbOperands.drop_front(nDims); 318 SmallVector<Value, 8> applyOperands{dimOperands}; 319 applyOperands.push_back(iv); 320 applyOperands.append(symbolOperands.begin(), symbolOperands.end()); 321 auto apply = builder.create<AffineApplyOp>(op.getLoc(), map, applyOperands); 322 iv.replaceAllUsesExcept(apply, apply); 323 } 324 325 SmallVector<int64_t, 8> newSteps(op.getNumDims(), 1); 326 op.setSteps(newSteps); 327 auto newLowerMap = AffineMap::get( 328 /*dimCount=*/0, /*symbolCount=*/0, lbExprs, op.getContext()); 329 op.setLowerBounds({}, newLowerMap); 330 auto newUpperMap = AffineMap::get(ranges.getNumDims(), ranges.getNumSymbols(), 331 ubExprs, op.getContext()); 332 op.setUpperBounds(ranges.getOperands(), newUpperMap); 333 } 334 335 /// Normalizes affine.for ops. If the affine.for op has only a single iteration 336 /// only then it is simply promoted, else it is normalized in the traditional 337 /// way, by converting the lower bound to zero and loop step to one. The upper 338 /// bound is set to the trip count of the loop. For now, original loops must 339 /// have lower bound with a single result only. There is no such restriction on 340 /// upper bounds. 341 void mlir::normalizeAffineFor(AffineForOp op) { 342 if (succeeded(promoteIfSingleIteration(op))) 343 return; 344 345 // Check if the forop is already normalized. 346 if (op.hasConstantLowerBound() && (op.getConstantLowerBound() == 0) && 347 (op.getStep() == 1)) 348 return; 349 350 // Check if the lower bound has a single result only. Loops with a max lower 351 // bound can't be normalized without additional support like 352 // affine.execute_region's. If the lower bound does not have a single result 353 // then skip this op. 354 if (op.getLowerBoundMap().getNumResults() != 1) 355 return; 356 357 Location loc = op.getLoc(); 358 OpBuilder opBuilder(op); 359 int64_t origLoopStep = op.getStep(); 360 361 // Calculate upperBound for normalized loop. 362 SmallVector<Value, 4> ubOperands; 363 AffineBound lb = op.getLowerBound(); 364 AffineBound ub = op.getUpperBound(); 365 ubOperands.reserve(ub.getNumOperands() + lb.getNumOperands()); 366 AffineMap origLbMap = lb.getMap(); 367 AffineMap origUbMap = ub.getMap(); 368 369 // Add dimension operands from upper/lower bound. 370 for (unsigned j = 0, e = origUbMap.getNumDims(); j < e; ++j) 371 ubOperands.push_back(ub.getOperand(j)); 372 for (unsigned j = 0, e = origLbMap.getNumDims(); j < e; ++j) 373 ubOperands.push_back(lb.getOperand(j)); 374 375 // Add symbol operands from upper/lower bound. 376 for (unsigned j = 0, e = origUbMap.getNumSymbols(); j < e; ++j) 377 ubOperands.push_back(ub.getOperand(origUbMap.getNumDims() + j)); 378 for (unsigned j = 0, e = origLbMap.getNumSymbols(); j < e; ++j) 379 ubOperands.push_back(lb.getOperand(origLbMap.getNumDims() + j)); 380 381 // Add original result expressions from lower/upper bound map. 382 SmallVector<AffineExpr, 1> origLbExprs(origLbMap.getResults().begin(), 383 origLbMap.getResults().end()); 384 SmallVector<AffineExpr, 2> origUbExprs(origUbMap.getResults().begin(), 385 origUbMap.getResults().end()); 386 SmallVector<AffineExpr, 4> newUbExprs; 387 388 // The original upperBound can have more than one result. For the new 389 // upperBound of this loop, take difference of all possible combinations of 390 // the ub results and lb result and ceildiv with the loop step. For e.g., 391 // 392 // affine.for %i1 = 0 to min affine_map<(d0)[] -> (d0 + 32, 1024)>(%i0) 393 // will have an upperBound map as, 394 // affine_map<(d0)[] -> (((d0 + 32) - 0) ceildiv 1, (1024 - 0) ceildiv 395 // 1)>(%i0) 396 // 397 // Insert all combinations of upper/lower bound results. 398 for (unsigned i = 0, e = origUbExprs.size(); i < e; ++i) { 399 newUbExprs.push_back( 400 (origUbExprs[i] - origLbExprs[0]).ceilDiv(origLoopStep)); 401 } 402 403 // Construct newUbMap. 404 AffineMap newUbMap = 405 AffineMap::get(origLbMap.getNumDims() + origUbMap.getNumDims(), 406 origLbMap.getNumSymbols() + origUbMap.getNumSymbols(), 407 newUbExprs, opBuilder.getContext()); 408 409 // Normalize the loop. 410 op.setUpperBound(ubOperands, newUbMap); 411 op.setLowerBound({}, opBuilder.getConstantAffineMap(0)); 412 op.setStep(1); 413 414 // Calculate the Value of new loopIV. Create affine.apply for the value of 415 // the loopIV in normalized loop. 416 opBuilder.setInsertionPointToStart(op.getBody()); 417 SmallVector<Value, 4> lbOperands(lb.getOperands().begin(), 418 lb.getOperands().begin() + 419 lb.getMap().getNumDims()); 420 // Add an extra dim operand for loopIV. 421 lbOperands.push_back(op.getInductionVar()); 422 // Add symbol operands from lower bound. 423 for (unsigned j = 0, e = origLbMap.getNumSymbols(); j < e; ++j) 424 lbOperands.push_back(lb.getOperand(origLbMap.getNumDims() + j)); 425 426 AffineExpr origIVExpr = opBuilder.getAffineDimExpr(lb.getMap().getNumDims()); 427 AffineExpr newIVExpr = origIVExpr * origLoopStep + origLbMap.getResult(0); 428 AffineMap ivMap = AffineMap::get(origLbMap.getNumDims() + 1, 429 origLbMap.getNumSymbols(), newIVExpr); 430 Operation *newIV = opBuilder.create<AffineApplyOp>(loc, ivMap, lbOperands); 431 op.getInductionVar().replaceAllUsesExcept(newIV->getResult(0), newIV); 432 } 433