/
Utils.cpp
1896 lines (1710 loc) · 76.7 KB
/
Utils.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- Utils.cpp ---- Utilities for affine dialect transformation ---------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements miscellaneous transformation utilities for the Affine
// dialect.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Affine/Utils.h"
#include "mlir/Dialect/Affine/Analysis/Utils.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Affine/IR/AffineValueMap.h"
#include "mlir/Dialect/Affine/LoopUtils.h"
#include "mlir/Dialect/Arith/Utils/Utils.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/Utils/IndexingUtils.h"
#include "mlir/IR/AffineExprVisitor.h"
#include "mlir/IR/Dominance.h"
#include "mlir/IR/IRMapping.h"
#include "mlir/IR/ImplicitLocOpBuilder.h"
#include "mlir/IR/IntegerSet.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include <optional>
#define DEBUG_TYPE "affine-utils"
using namespace mlir;
using namespace affine;
using namespace presburger;
namespace {
/// Visit affine expressions recursively and build the sequence of operations
/// that correspond to it. Visitation functions return an Value of the
/// expression subtree they visited or `nullptr` on error.
class AffineApplyExpander
: public AffineExprVisitor<AffineApplyExpander, Value> {
public:
/// This internal class expects arguments to be non-null, checks must be
/// performed at the call site.
AffineApplyExpander(OpBuilder &builder, ValueRange dimValues,
ValueRange symbolValues, Location loc)
: builder(builder), dimValues(dimValues), symbolValues(symbolValues),
loc(loc) {}
template <typename OpTy>
Value buildBinaryExpr(AffineBinaryOpExpr expr) {
auto lhs = visit(expr.getLHS());
auto rhs = visit(expr.getRHS());
if (!lhs || !rhs)
return nullptr;
auto op = builder.create<OpTy>(loc, lhs, rhs);
return op.getResult();
}
Value visitAddExpr(AffineBinaryOpExpr expr) {
return buildBinaryExpr<arith::AddIOp>(expr);
}
Value visitMulExpr(AffineBinaryOpExpr expr) {
return buildBinaryExpr<arith::MulIOp>(expr);
}
/// Euclidean modulo operation: negative RHS is not allowed.
/// Remainder of the euclidean integer division is always non-negative.
///
/// Implemented as
///
/// a mod b =
/// let remainder = srem a, b;
/// negative = a < 0 in
/// select negative, remainder + b, remainder.
Value visitModExpr(AffineBinaryOpExpr expr) {
if (auto rhsConst = dyn_cast<AffineConstantExpr>(expr.getRHS())) {
if (rhsConst.getValue() <= 0) {
emitError(loc, "modulo by non-positive value is not supported");
return nullptr;
}
}
auto lhs = visit(expr.getLHS());
auto rhs = visit(expr.getRHS());
assert(lhs && rhs && "unexpected affine expr lowering failure");
Value remainder = builder.create<arith::RemSIOp>(loc, lhs, rhs);
Value zeroCst = builder.create<arith::ConstantIndexOp>(loc, 0);
Value isRemainderNegative = builder.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::slt, remainder, zeroCst);
Value correctedRemainder =
builder.create<arith::AddIOp>(loc, remainder, rhs);
Value result = builder.create<arith::SelectOp>(
loc, isRemainderNegative, correctedRemainder, remainder);
return result;
}
/// Floor division operation (rounds towards negative infinity).
///
/// For positive divisors, it can be implemented without branching and with a
/// single division operation as
///
/// a floordiv b =
/// let negative = a < 0 in
/// let absolute = negative ? -a - 1 : a in
/// let quotient = absolute / b in
/// negative ? -quotient - 1 : quotient
///
/// Note: this lowering does not use arith.floordivsi because the lowering of
/// that to arith.divsi (see populateCeilFloorDivExpandOpsPatterns) generates
/// not one but two arith.divsi. That could be changed to one divsi, but one
/// way or another, going through arith.floordivsi will result in more complex
/// IR because arith.floordivsi is more general than affine floordiv in that
/// it supports negative RHS.
Value visitFloorDivExpr(AffineBinaryOpExpr expr) {
if (auto rhsConst = dyn_cast<AffineConstantExpr>(expr.getRHS())) {
if (rhsConst.getValue() <= 0) {
emitError(loc, "division by non-positive value is not supported");
return nullptr;
}
}
auto lhs = visit(expr.getLHS());
auto rhs = visit(expr.getRHS());
assert(lhs && rhs && "unexpected affine expr lowering failure");
Value zeroCst = builder.create<arith::ConstantIndexOp>(loc, 0);
Value noneCst = builder.create<arith::ConstantIndexOp>(loc, -1);
Value negative = builder.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::slt, lhs, zeroCst);
Value negatedDecremented = builder.create<arith::SubIOp>(loc, noneCst, lhs);
Value dividend =
builder.create<arith::SelectOp>(loc, negative, negatedDecremented, lhs);
Value quotient = builder.create<arith::DivSIOp>(loc, dividend, rhs);
Value correctedQuotient =
builder.create<arith::SubIOp>(loc, noneCst, quotient);
Value result = builder.create<arith::SelectOp>(loc, negative,
correctedQuotient, quotient);
return result;
}
/// Ceiling division operation (rounds towards positive infinity).
///
/// For positive divisors, it can be implemented without branching and with a
/// single division operation as
///
/// a ceildiv b =
/// let negative = a <= 0 in
/// let absolute = negative ? -a : a - 1 in
/// let quotient = absolute / b in
/// negative ? -quotient : quotient + 1
///
/// Note: not using arith.ceildivsi for the same reason as explained in the
/// visitFloorDivExpr comment.
Value visitCeilDivExpr(AffineBinaryOpExpr expr) {
if (auto rhsConst = dyn_cast<AffineConstantExpr>(expr.getRHS())) {
if (rhsConst.getValue() <= 0) {
emitError(loc, "division by non-positive value is not supported");
return nullptr;
}
}
auto lhs = visit(expr.getLHS());
auto rhs = visit(expr.getRHS());
assert(lhs && rhs && "unexpected affine expr lowering failure");
Value zeroCst = builder.create<arith::ConstantIndexOp>(loc, 0);
Value oneCst = builder.create<arith::ConstantIndexOp>(loc, 1);
Value nonPositive = builder.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::sle, lhs, zeroCst);
Value negated = builder.create<arith::SubIOp>(loc, zeroCst, lhs);
Value decremented = builder.create<arith::SubIOp>(loc, lhs, oneCst);
Value dividend =
builder.create<arith::SelectOp>(loc, nonPositive, negated, decremented);
Value quotient = builder.create<arith::DivSIOp>(loc, dividend, rhs);
Value negatedQuotient =
builder.create<arith::SubIOp>(loc, zeroCst, quotient);
Value incrementedQuotient =
builder.create<arith::AddIOp>(loc, quotient, oneCst);
Value result = builder.create<arith::SelectOp>(
loc, nonPositive, negatedQuotient, incrementedQuotient);
return result;
}
Value visitConstantExpr(AffineConstantExpr expr) {
auto op = builder.create<arith::ConstantIndexOp>(loc, expr.getValue());
return op.getResult();
}
Value visitDimExpr(AffineDimExpr expr) {
assert(expr.getPosition() < dimValues.size() &&
"affine dim position out of range");
return dimValues[expr.getPosition()];
}
Value visitSymbolExpr(AffineSymbolExpr expr) {
assert(expr.getPosition() < symbolValues.size() &&
"symbol dim position out of range");
return symbolValues[expr.getPosition()];
}
private:
OpBuilder &builder;
ValueRange dimValues;
ValueRange symbolValues;
Location loc;
};
} // namespace
/// Create a sequence of operations that implement the `expr` applied to the
/// given dimension and symbol values.
mlir::Value mlir::affine::expandAffineExpr(OpBuilder &builder, Location loc,
AffineExpr expr,
ValueRange dimValues,
ValueRange symbolValues) {
return AffineApplyExpander(builder, dimValues, symbolValues, loc).visit(expr);
}
/// Create a sequence of operations that implement the `affineMap` applied to
/// the given `operands` (as it it were an AffineApplyOp).
std::optional<SmallVector<Value, 8>>
mlir::affine::expandAffineMap(OpBuilder &builder, Location loc,
AffineMap affineMap, ValueRange operands) {
auto numDims = affineMap.getNumDims();
auto expanded = llvm::to_vector<8>(
llvm::map_range(affineMap.getResults(),
[numDims, &builder, loc, operands](AffineExpr expr) {
return expandAffineExpr(builder, loc, expr,
operands.take_front(numDims),
operands.drop_front(numDims));
}));
if (llvm::all_of(expanded, [](Value v) { return v; }))
return expanded;
return std::nullopt;
}
/// Promotes the `then` or the `else` block of `ifOp` (depending on whether
/// `elseBlock` is false or true) into `ifOp`'s containing block, and discards
/// the rest of the op.
static void promoteIfBlock(AffineIfOp ifOp, bool elseBlock) {
if (elseBlock)
assert(ifOp.hasElse() && "else block expected");
Block *destBlock = ifOp->getBlock();
Block *srcBlock = elseBlock ? ifOp.getElseBlock() : ifOp.getThenBlock();
destBlock->getOperations().splice(
Block::iterator(ifOp), srcBlock->getOperations(), srcBlock->begin(),
std::prev(srcBlock->end()));
ifOp.erase();
}
/// Returns the outermost affine.for/parallel op that the `ifOp` is invariant
/// on. The `ifOp` could be hoisted and placed right before such an operation.
/// This method assumes that the ifOp has been canonicalized (to be correct and
/// effective).
static Operation *getOutermostInvariantForOp(AffineIfOp ifOp) {
// Walk up the parents past all for op that this conditional is invariant on.
auto ifOperands = ifOp.getOperands();
auto *res = ifOp.getOperation();
while (!isa<func::FuncOp>(res->getParentOp())) {
auto *parentOp = res->getParentOp();
if (auto forOp = dyn_cast<AffineForOp>(parentOp)) {
if (llvm::is_contained(ifOperands, forOp.getInductionVar()))
break;
} else if (auto parallelOp = dyn_cast<AffineParallelOp>(parentOp)) {
for (auto iv : parallelOp.getIVs())
if (llvm::is_contained(ifOperands, iv))
break;
} else if (!isa<AffineIfOp>(parentOp)) {
// Won't walk up past anything other than affine.for/if ops.
break;
}
// You can always hoist up past any affine.if ops.
res = parentOp;
}
return res;
}
/// A helper for the mechanics of mlir::hoistAffineIfOp. Hoists `ifOp` just over
/// `hoistOverOp`. Returns the new hoisted op if any hoisting happened,
/// otherwise the same `ifOp`.
static AffineIfOp hoistAffineIfOp(AffineIfOp ifOp, Operation *hoistOverOp) {
// No hoisting to do.
if (hoistOverOp == ifOp)
return ifOp;
// Create the hoisted 'if' first. Then, clone the op we are hoisting over for
// the else block. Then drop the else block of the original 'if' in the 'then'
// branch while promoting its then block, and analogously drop the 'then'
// block of the original 'if' from the 'else' branch while promoting its else
// block.
IRMapping operandMap;
OpBuilder b(hoistOverOp);
auto hoistedIfOp = b.create<AffineIfOp>(ifOp.getLoc(), ifOp.getIntegerSet(),
ifOp.getOperands(),
/*elseBlock=*/true);
// Create a clone of hoistOverOp to use for the else branch of the hoisted
// conditional. The else block may get optimized away if empty.
Operation *hoistOverOpClone = nullptr;
// We use this unique name to identify/find `ifOp`'s clone in the else
// version.
StringAttr idForIfOp = b.getStringAttr("__mlir_if_hoisting");
operandMap.clear();
b.setInsertionPointAfter(hoistOverOp);
// We'll set an attribute to identify this op in a clone of this sub-tree.
ifOp->setAttr(idForIfOp, b.getBoolAttr(true));
hoistOverOpClone = b.clone(*hoistOverOp, operandMap);
// Promote the 'then' block of the original affine.if in the then version.
promoteIfBlock(ifOp, /*elseBlock=*/false);
// Move the then version to the hoisted if op's 'then' block.
auto *thenBlock = hoistedIfOp.getThenBlock();
thenBlock->getOperations().splice(thenBlock->begin(),
hoistOverOp->getBlock()->getOperations(),
Block::iterator(hoistOverOp));
// Find the clone of the original affine.if op in the else version.
AffineIfOp ifCloneInElse;
hoistOverOpClone->walk([&](AffineIfOp ifClone) {
if (!ifClone->getAttr(idForIfOp))
return WalkResult::advance();
ifCloneInElse = ifClone;
return WalkResult::interrupt();
});
assert(ifCloneInElse && "if op clone should exist");
// For the else block, promote the else block of the original 'if' if it had
// one; otherwise, the op itself is to be erased.
if (!ifCloneInElse.hasElse())
ifCloneInElse.erase();
else
promoteIfBlock(ifCloneInElse, /*elseBlock=*/true);
// Move the else version into the else block of the hoisted if op.
auto *elseBlock = hoistedIfOp.getElseBlock();
elseBlock->getOperations().splice(
elseBlock->begin(), hoistOverOpClone->getBlock()->getOperations(),
Block::iterator(hoistOverOpClone));
return hoistedIfOp;
}
LogicalResult
mlir::affine::affineParallelize(AffineForOp forOp,
ArrayRef<LoopReduction> parallelReductions,
AffineParallelOp *resOp) {
// Fail early if there are iter arguments that are not reductions.
unsigned numReductions = parallelReductions.size();
if (numReductions != forOp.getNumIterOperands())
return failure();
Location loc = forOp.getLoc();
OpBuilder outsideBuilder(forOp);
AffineMap lowerBoundMap = forOp.getLowerBoundMap();
ValueRange lowerBoundOperands = forOp.getLowerBoundOperands();
AffineMap upperBoundMap = forOp.getUpperBoundMap();
ValueRange upperBoundOperands = forOp.getUpperBoundOperands();
// Creating empty 1-D affine.parallel op.
auto reducedValues = llvm::to_vector<4>(llvm::map_range(
parallelReductions, [](const LoopReduction &red) { return red.value; }));
auto reductionKinds = llvm::to_vector<4>(llvm::map_range(
parallelReductions, [](const LoopReduction &red) { return red.kind; }));
AffineParallelOp newPloop = outsideBuilder.create<AffineParallelOp>(
loc, ValueRange(reducedValues).getTypes(), reductionKinds,
llvm::ArrayRef(lowerBoundMap), lowerBoundOperands,
llvm::ArrayRef(upperBoundMap), upperBoundOperands,
llvm::ArrayRef(forOp.getStepAsInt()));
// Steal the body of the old affine for op.
newPloop.getRegion().takeBody(forOp.getRegion());
Operation *yieldOp = &newPloop.getBody()->back();
// Handle the initial values of reductions because the parallel loop always
// starts from the neutral value.
SmallVector<Value> newResults;
newResults.reserve(numReductions);
for (unsigned i = 0; i < numReductions; ++i) {
Value init = forOp.getInits()[i];
// This works because we are only handling single-op reductions at the
// moment. A switch on reduction kind or a mechanism to collect operations
// participating in the reduction will be necessary for multi-op reductions.
Operation *reductionOp = yieldOp->getOperand(i).getDefiningOp();
assert(reductionOp && "yielded value is expected to be produced by an op");
outsideBuilder.getInsertionBlock()->getOperations().splice(
outsideBuilder.getInsertionPoint(), newPloop.getBody()->getOperations(),
reductionOp);
reductionOp->setOperands({init, newPloop->getResult(i)});
forOp->getResult(i).replaceAllUsesWith(reductionOp->getResult(0));
}
// Update the loop terminator to yield reduced values bypassing the reduction
// operation itself (now moved outside of the loop) and erase the block
// arguments that correspond to reductions. Note that the loop always has one
// "main" induction variable whenc coming from a non-parallel for.
unsigned numIVs = 1;
yieldOp->setOperands(reducedValues);
newPloop.getBody()->eraseArguments(numIVs, numReductions);
forOp.erase();
if (resOp)
*resOp = newPloop;
return success();
}
// Returns success if any hoisting happened.
LogicalResult mlir::affine::hoistAffineIfOp(AffineIfOp ifOp, bool *folded) {
// Bail out early if the ifOp returns a result. TODO: Consider how to
// properly support this case.
if (ifOp.getNumResults() != 0)
return failure();
// Apply canonicalization patterns and folding - this is necessary for the
// hoisting check to be correct (operands should be composed), and to be more
// effective (no unused operands). Since the pattern rewriter's folding is
// entangled with application of patterns, we may fold/end up erasing the op,
// in which case we return with `folded` being set.
RewritePatternSet patterns(ifOp.getContext());
AffineIfOp::getCanonicalizationPatterns(patterns, ifOp.getContext());
FrozenRewritePatternSet frozenPatterns(std::move(patterns));
GreedyRewriteConfig config;
config.strictMode = GreedyRewriteStrictness::ExistingOps;
bool erased;
(void)applyOpPatternsAndFold(ifOp.getOperation(), frozenPatterns, config,
/*changed=*/nullptr, &erased);
if (erased) {
if (folded)
*folded = true;
return failure();
}
if (folded)
*folded = false;
// The folding above should have ensured this, but the affine.if's
// canonicalization is missing composition of affine.applys into it.
assert(llvm::all_of(ifOp.getOperands(),
[](Value v) {
return isTopLevelValue(v) || isAffineForInductionVar(v);
}) &&
"operands not composed");
// We are going hoist as high as possible.
// TODO: this could be customized in the future.
auto *hoistOverOp = getOutermostInvariantForOp(ifOp);
AffineIfOp hoistedIfOp = ::hoistAffineIfOp(ifOp, hoistOverOp);
// Nothing to hoist over.
if (hoistedIfOp == ifOp)
return failure();
// Canonicalize to remove dead else blocks (happens whenever an 'if' moves up
// a sequence of affine.fors that are all perfectly nested).
(void)applyPatternsAndFoldGreedily(
hoistedIfOp->getParentWithTrait<OpTrait::IsIsolatedFromAbove>(),
frozenPatterns);
return success();
}
// Return the min expr after replacing the given dim.
AffineExpr mlir::affine::substWithMin(AffineExpr e, AffineExpr dim,
AffineExpr min, AffineExpr max,
bool positivePath) {
if (e == dim)
return positivePath ? min : max;
if (auto bin = dyn_cast<AffineBinaryOpExpr>(e)) {
AffineExpr lhs = bin.getLHS();
AffineExpr rhs = bin.getRHS();
if (bin.getKind() == mlir::AffineExprKind::Add)
return substWithMin(lhs, dim, min, max, positivePath) +
substWithMin(rhs, dim, min, max, positivePath);
auto c1 = dyn_cast<AffineConstantExpr>(bin.getLHS());
auto c2 = dyn_cast<AffineConstantExpr>(bin.getRHS());
if (c1 && c1.getValue() < 0)
return getAffineBinaryOpExpr(
bin.getKind(), c1, substWithMin(rhs, dim, min, max, !positivePath));
if (c2 && c2.getValue() < 0)
return getAffineBinaryOpExpr(
bin.getKind(), substWithMin(lhs, dim, min, max, !positivePath), c2);
return getAffineBinaryOpExpr(
bin.getKind(), substWithMin(lhs, dim, min, max, positivePath),
substWithMin(rhs, dim, min, max, positivePath));
}
return e;
}
void mlir::affine::normalizeAffineParallel(AffineParallelOp op) {
// Loops with min/max in bounds are not normalized at the moment.
if (op.hasMinMaxBounds())
return;
AffineMap lbMap = op.getLowerBoundsMap();
SmallVector<int64_t, 8> steps = op.getSteps();
// No need to do any work if the parallel op is already normalized.
bool isAlreadyNormalized =
llvm::all_of(llvm::zip(steps, lbMap.getResults()), [](auto tuple) {
int64_t step = std::get<0>(tuple);
auto lbExpr = dyn_cast<AffineConstantExpr>(std::get<1>(tuple));
return lbExpr && lbExpr.getValue() == 0 && step == 1;
});
if (isAlreadyNormalized)
return;
AffineValueMap ranges;
AffineValueMap::difference(op.getUpperBoundsValueMap(),
op.getLowerBoundsValueMap(), &ranges);
auto builder = OpBuilder::atBlockBegin(op.getBody());
auto zeroExpr = builder.getAffineConstantExpr(0);
SmallVector<AffineExpr, 8> lbExprs;
SmallVector<AffineExpr, 8> ubExprs;
for (unsigned i = 0, e = steps.size(); i < e; ++i) {
int64_t step = steps[i];
// Adjust the lower bound to be 0.
lbExprs.push_back(zeroExpr);
// Adjust the upper bound expression: 'range / step'.
AffineExpr ubExpr = ranges.getResult(i).ceilDiv(step);
ubExprs.push_back(ubExpr);
// Adjust the corresponding IV: 'lb + i * step'.
BlockArgument iv = op.getBody()->getArgument(i);
AffineExpr lbExpr = lbMap.getResult(i);
unsigned nDims = lbMap.getNumDims();
auto expr = lbExpr + builder.getAffineDimExpr(nDims) * step;
auto map = AffineMap::get(/*dimCount=*/nDims + 1,
/*symbolCount=*/lbMap.getNumSymbols(), expr);
// Use an 'affine.apply' op that will be simplified later in subsequent
// canonicalizations.
OperandRange lbOperands = op.getLowerBoundsOperands();
OperandRange dimOperands = lbOperands.take_front(nDims);
OperandRange symbolOperands = lbOperands.drop_front(nDims);
SmallVector<Value, 8> applyOperands{dimOperands};
applyOperands.push_back(iv);
applyOperands.append(symbolOperands.begin(), symbolOperands.end());
auto apply = builder.create<AffineApplyOp>(op.getLoc(), map, applyOperands);
iv.replaceAllUsesExcept(apply, apply);
}
SmallVector<int64_t, 8> newSteps(op.getNumDims(), 1);
op.setSteps(newSteps);
auto newLowerMap = AffineMap::get(
/*dimCount=*/0, /*symbolCount=*/0, lbExprs, op.getContext());
op.setLowerBounds({}, newLowerMap);
auto newUpperMap = AffineMap::get(ranges.getNumDims(), ranges.getNumSymbols(),
ubExprs, op.getContext());
op.setUpperBounds(ranges.getOperands(), newUpperMap);
}
LogicalResult mlir::affine::normalizeAffineFor(AffineForOp op,
bool promoteSingleIter) {
if (promoteSingleIter && succeeded(promoteIfSingleIteration(op)))
return success();
// Check if the forop is already normalized.
if (op.hasConstantLowerBound() && (op.getConstantLowerBound() == 0) &&
(op.getStep() == 1))
return success();
// Check if the lower bound has a single result only. Loops with a max lower
// bound can't be normalized without additional support like
// affine.execute_region's. If the lower bound does not have a single result
// then skip this op.
if (op.getLowerBoundMap().getNumResults() != 1)
return failure();
Location loc = op.getLoc();
OpBuilder opBuilder(op);
int64_t origLoopStep = op.getStepAsInt();
// Construct the new upper bound value map.
AffineMap oldLbMap = op.getLowerBoundMap();
// The upper bound can have multiple results. To use
// AffineValueMap::difference, we need to have the same number of results in
// both lower and upper bound maps. So, we just create a value map for the
// lower bound with the only available lower bound result repeated to pad up
// to the number of upper bound results.
SmallVector<AffineExpr> lbExprs(op.getUpperBoundMap().getNumResults(),
op.getLowerBoundMap().getResult(0));
AffineValueMap lbMap(oldLbMap, op.getLowerBoundOperands());
AffineMap paddedLbMap =
AffineMap::get(oldLbMap.getNumDims(), oldLbMap.getNumSymbols(), lbExprs,
op.getContext());
AffineValueMap paddedLbValueMap(paddedLbMap, op.getLowerBoundOperands());
AffineValueMap ubValueMap(op.getUpperBoundMap(), op.getUpperBoundOperands());
AffineValueMap newUbValueMap;
// Compute the `upper bound - lower bound`.
AffineValueMap::difference(ubValueMap, paddedLbValueMap, &newUbValueMap);
(void)newUbValueMap.canonicalize();
// Scale down the upper bound value map by the loop step.
unsigned numResult = newUbValueMap.getNumResults();
SmallVector<AffineExpr> scaleDownExprs(numResult);
for (unsigned i = 0; i < numResult; ++i)
scaleDownExprs[i] = opBuilder.getAffineDimExpr(i).ceilDiv(origLoopStep);
// `scaleDownMap` is (d0, d1, ..., d_n) -> (d0 / step, d1 / step, ..., d_n /
// step). Where `n` is the number of results in the upper bound map.
AffineMap scaleDownMap =
AffineMap::get(numResult, 0, scaleDownExprs, op.getContext());
AffineMap newUbMap = scaleDownMap.compose(newUbValueMap.getAffineMap());
// Set the newly create upper bound map and operands.
op.setUpperBound(newUbValueMap.getOperands(), newUbMap);
op.setLowerBound({}, opBuilder.getConstantAffineMap(0));
op.setStep(1);
// Calculate the Value of new loopIV. Create affine.apply for the value of
// the loopIV in normalized loop.
opBuilder.setInsertionPointToStart(op.getBody());
// Construct an affine.apply op mapping the new IV to the old IV.
AffineMap scaleIvMap =
AffineMap::get(1, 0, -opBuilder.getAffineDimExpr(0) * origLoopStep);
AffineValueMap scaleIvValueMap(scaleIvMap, ValueRange{op.getInductionVar()});
AffineValueMap newIvToOldIvMap;
AffineValueMap::difference(lbMap, scaleIvValueMap, &newIvToOldIvMap);
(void)newIvToOldIvMap.canonicalize();
auto newIV = opBuilder.create<AffineApplyOp>(
loc, newIvToOldIvMap.getAffineMap(), newIvToOldIvMap.getOperands());
op.getInductionVar().replaceAllUsesExcept(newIV->getResult(0), newIV);
return success();
}
/// Returns true if the memory operation of `destAccess` depends on `srcAccess`
/// inside of the innermost common surrounding affine loop between the two
/// accesses.
static bool mustReachAtInnermost(const MemRefAccess &srcAccess,
const MemRefAccess &destAccess) {
// Affine dependence analysis is possible only if both ops in the same
// AffineScope.
if (getAffineScope(srcAccess.opInst) != getAffineScope(destAccess.opInst))
return false;
unsigned nsLoops =
getNumCommonSurroundingLoops(*srcAccess.opInst, *destAccess.opInst);
DependenceResult result =
checkMemrefAccessDependence(srcAccess, destAccess, nsLoops + 1);
return hasDependence(result);
}
/// Returns true if `srcMemOp` may have an effect on `destMemOp` within the
/// scope of the outermost `minSurroundingLoops` loops that surround them.
/// `srcMemOp` and `destMemOp` are expected to be affine read/write ops.
static bool mayHaveEffect(Operation *srcMemOp, Operation *destMemOp,
unsigned minSurroundingLoops) {
MemRefAccess srcAccess(srcMemOp);
MemRefAccess destAccess(destMemOp);
// Affine dependence analysis here is applicable only if both ops operate on
// the same memref and if `srcMemOp` and `destMemOp` are in the same
// AffineScope. Also, we can only check if our affine scope is isolated from
// above; otherwise, values can from outside of the affine scope that the
// check below cannot analyze.
Region *srcScope = getAffineScope(srcMemOp);
if (srcAccess.memref == destAccess.memref &&
srcScope == getAffineScope(destMemOp)) {
unsigned nsLoops = getNumCommonSurroundingLoops(*srcMemOp, *destMemOp);
FlatAffineValueConstraints dependenceConstraints;
for (unsigned d = nsLoops + 1; d > minSurroundingLoops; d--) {
DependenceResult result = checkMemrefAccessDependence(
srcAccess, destAccess, d, &dependenceConstraints,
/*dependenceComponents=*/nullptr);
// A dependence failure or the presence of a dependence implies a
// side effect.
if (!noDependence(result))
return true;
}
// No side effect was seen.
return false;
}
// TODO: Check here if the memrefs alias: there is no side effect if
// `srcAccess.memref` and `destAccess.memref` don't alias.
return true;
}
template <typename EffectType, typename T>
bool mlir::affine::hasNoInterveningEffect(Operation *start, T memOp) {
auto isLocallyAllocated = [](Value memref) {
auto *defOp = memref.getDefiningOp();
return defOp && hasSingleEffect<MemoryEffects::Allocate>(defOp, memref);
};
// A boolean representing whether an intervening operation could have impacted
// memOp.
bool hasSideEffect = false;
// Check whether the effect on memOp can be caused by a given operation op.
Value memref = memOp.getMemRef();
std::function<void(Operation *)> checkOperation = [&](Operation *op) {
// If the effect has alreay been found, early exit,
if (hasSideEffect)
return;
if (auto memEffect = dyn_cast<MemoryEffectOpInterface>(op)) {
SmallVector<MemoryEffects::EffectInstance, 1> effects;
memEffect.getEffects(effects);
bool opMayHaveEffect = false;
for (auto effect : effects) {
// If op causes EffectType on a potentially aliasing location for
// memOp, mark as having the effect.
if (isa<EffectType>(effect.getEffect())) {
// TODO: This should be replaced with a check for no aliasing.
// Aliasing information should be passed to this method.
if (effect.getValue() && effect.getValue() != memref &&
isLocallyAllocated(memref) &&
isLocallyAllocated(effect.getValue()))
continue;
opMayHaveEffect = true;
break;
}
}
if (!opMayHaveEffect)
return;
// If the side effect comes from an affine read or write, try to
// prove the side effecting `op` cannot reach `memOp`.
if (isa<AffineReadOpInterface, AffineWriteOpInterface>(op)) {
// For ease, let's consider the case that `op` is a store and
// we're looking for other potential stores that overwrite memory after
// `start`, and before being read in `memOp`. In this case, we only
// need to consider other potential stores with depth >
// minSurroundingLoops since `start` would overwrite any store with a
// smaller number of surrounding loops before.
unsigned minSurroundingLoops =
getNumCommonSurroundingLoops(*start, *memOp);
if (mayHaveEffect(op, memOp, minSurroundingLoops))
hasSideEffect = true;
return;
}
// We have an op with a memory effect and we cannot prove if it
// intervenes.
hasSideEffect = true;
return;
}
if (op->hasTrait<OpTrait::HasRecursiveMemoryEffects>()) {
// Recurse into the regions for this op and check whether the internal
// operations may have the side effect `EffectType` on memOp.
for (Region ®ion : op->getRegions())
for (Block &block : region)
for (Operation &op : block)
checkOperation(&op);
return;
}
// Otherwise, conservatively assume generic operations have the effect
// on the operation
hasSideEffect = true;
};
// Check all paths from ancestor op `parent` to the operation `to` for the
// effect. It is known that `to` must be contained within `parent`.
auto until = [&](Operation *parent, Operation *to) {
// TODO check only the paths from `parent` to `to`.
// Currently we fallback and check the entire parent op, rather than
// just the paths from the parent path, stopping after reaching `to`.
// This is conservatively correct, but could be made more aggressive.
assert(parent->isAncestor(to));
checkOperation(parent);
};
// Check for all paths from operation `from` to operation `untilOp` for the
// given memory effect.
std::function<void(Operation *, Operation *)> recur =
[&](Operation *from, Operation *untilOp) {
assert(
from->getParentRegion()->isAncestor(untilOp->getParentRegion()) &&
"Checking for side effect between two operations without a common "
"ancestor");
// If the operations are in different regions, recursively consider all
// path from `from` to the parent of `to` and all paths from the parent
// of `to` to `to`.
if (from->getParentRegion() != untilOp->getParentRegion()) {
recur(from, untilOp->getParentOp());
until(untilOp->getParentOp(), untilOp);
return;
}
// Now, assuming that `from` and `to` exist in the same region, perform
// a CFG traversal to check all the relevant operations.
// Additional blocks to consider.
SmallVector<Block *, 2> todoBlocks;
{
// First consider the parent block of `from` an check all operations
// after `from`.
for (auto iter = ++from->getIterator(), end = from->getBlock()->end();
iter != end && &*iter != untilOp; ++iter) {
checkOperation(&*iter);
}
// If the parent of `from` doesn't contain `to`, add the successors
// to the list of blocks to check.
if (untilOp->getBlock() != from->getBlock())
for (Block *succ : from->getBlock()->getSuccessors())
todoBlocks.push_back(succ);
}
SmallPtrSet<Block *, 4> done;
// Traverse the CFG until hitting `to`.
while (!todoBlocks.empty()) {
Block *blk = todoBlocks.pop_back_val();
if (done.count(blk))
continue;
done.insert(blk);
for (auto &op : *blk) {
if (&op == untilOp)
break;
checkOperation(&op);
if (&op == blk->getTerminator())
for (Block *succ : blk->getSuccessors())
todoBlocks.push_back(succ);
}
}
};
recur(start, memOp);
return !hasSideEffect;
}
/// Attempt to eliminate loadOp by replacing it with a value stored into memory
/// which the load is guaranteed to retrieve. This check involves three
/// components: 1) The store and load must be on the same location 2) The store
/// must dominate (and therefore must always occur prior to) the load 3) No
/// other operations will overwrite the memory loaded between the given load
/// and store. If such a value exists, the replaced `loadOp` will be added to
/// `loadOpsToErase` and its memref will be added to `memrefsToErase`.
static void forwardStoreToLoad(AffineReadOpInterface loadOp,
SmallVectorImpl<Operation *> &loadOpsToErase,
SmallPtrSetImpl<Value> &memrefsToErase,
DominanceInfo &domInfo) {
// The store op candidate for forwarding that satisfies all conditions
// to replace the load, if any.
Operation *lastWriteStoreOp = nullptr;
for (auto *user : loadOp.getMemRef().getUsers()) {
auto storeOp = dyn_cast<AffineWriteOpInterface>(user);
if (!storeOp)
continue;
MemRefAccess srcAccess(storeOp);
MemRefAccess destAccess(loadOp);
// 1. Check if the store and the load have mathematically equivalent
// affine access functions; this implies that they statically refer to the
// same single memref element. As an example this filters out cases like:
// store %A[%i0 + 1]
// load %A[%i0]
// store %A[%M]
// load %A[%N]
// Use the AffineValueMap difference based memref access equality checking.
if (srcAccess != destAccess)
continue;
// 2. The store has to dominate the load op to be candidate.
if (!domInfo.dominates(storeOp, loadOp))
continue;
// 3. The store must reach the load. Access function equivalence only
// guarantees this for accesses in the same block. The load could be in a
// nested block that is unreachable.
if (storeOp->getBlock() != loadOp->getBlock() &&
!mustReachAtInnermost(srcAccess, destAccess))
continue;
// 4. Ensure there is no intermediate operation which could replace the
// value in memory.
if (!affine::hasNoInterveningEffect<MemoryEffects::Write>(storeOp, loadOp))
continue;
// We now have a candidate for forwarding.
assert(lastWriteStoreOp == nullptr &&
"multiple simultaneous replacement stores");
lastWriteStoreOp = storeOp;
}
if (!lastWriteStoreOp)
return;
// Perform the actual store to load forwarding.
Value storeVal =
cast<AffineWriteOpInterface>(lastWriteStoreOp).getValueToStore();
// Check if 2 values have the same shape. This is needed for affine vector
// loads and stores.
if (storeVal.getType() != loadOp.getValue().getType())
return;
loadOp.getValue().replaceAllUsesWith(storeVal);
// Record the memref for a later sweep to optimize away.
memrefsToErase.insert(loadOp.getMemRef());
// Record this to erase later.
loadOpsToErase.push_back(loadOp);
}
template bool
mlir::affine::hasNoInterveningEffect<mlir::MemoryEffects::Read,
affine::AffineReadOpInterface>(
mlir::Operation *, affine::AffineReadOpInterface);
// This attempts to find stores which have no impact on the final result.
// A writing op writeA will be eliminated if there exists an op writeB if
// 1) writeA and writeB have mathematically equivalent affine access functions.
// 2) writeB postdominates writeA.
// 3) There is no potential read between writeA and writeB.
static void findUnusedStore(AffineWriteOpInterface writeA,
SmallVectorImpl<Operation *> &opsToErase,
PostDominanceInfo &postDominanceInfo) {
for (Operation *user : writeA.getMemRef().getUsers()) {
// Only consider writing operations.
auto writeB = dyn_cast<AffineWriteOpInterface>(user);
if (!writeB)
continue;
// The operations must be distinct.
if (writeB == writeA)
continue;
// Both operations must lie in the same region.
if (writeB->getParentRegion() != writeA->getParentRegion())
continue;
// Both operations must write to the same memory.
MemRefAccess srcAccess(writeB);
MemRefAccess destAccess(writeA);
if (srcAccess != destAccess)
continue;
// writeB must postdominate writeA.
if (!postDominanceInfo.postDominates(writeB, writeA))
continue;
// There cannot be an operation which reads from memory between
// the two writes.
if (!affine::hasNoInterveningEffect<MemoryEffects::Read>(writeA, writeB))
continue;
opsToErase.push_back(writeA);
break;
}
}
// The load to load forwarding / redundant load elimination is similar to the
// store to load forwarding.
// loadA will be be replaced with loadB if:
// 1) loadA and loadB have mathematically equivalent affine access functions.
// 2) loadB dominates loadA.
// 3) There is no write between loadA and loadB.
static void loadCSE(AffineReadOpInterface loadA,
SmallVectorImpl<Operation *> &loadOpsToErase,
DominanceInfo &domInfo) {
SmallVector<AffineReadOpInterface, 4> loadCandidates;
for (auto *user : loadA.getMemRef().getUsers()) {
auto loadB = dyn_cast<AffineReadOpInterface>(user);
if (!loadB || loadB == loadA)
continue;
MemRefAccess srcAccess(loadB);
MemRefAccess destAccess(loadA);
// 1. The accesses should be to be to the same location.
if (srcAccess != destAccess) {
continue;
}
// 2. loadB should dominate loadA.
if (!domInfo.dominates(loadB, loadA))
continue;
// 3. There should not be a write between loadA and loadB.
if (!affine::hasNoInterveningEffect<MemoryEffects::Write>(
loadB.getOperation(), loadA))
continue;
// Check if two values have the same shape. This is needed for affine vector
// loads.
if (loadB.getValue().getType() != loadA.getValue().getType())
continue;
loadCandidates.push_back(loadB);
}
// Of the legal load candidates, use the one that dominates all others
// to minimize the subsequent need to loadCSE
Value loadB;
for (AffineReadOpInterface option : loadCandidates) {
if (llvm::all_of(loadCandidates, [&](AffineReadOpInterface depStore) {
return depStore == option ||
domInfo.dominates(option.getOperation(),
depStore.getOperation());
})) {
loadB = option.getValue();
break;