-
Notifications
You must be signed in to change notification settings - Fork 10
/
sair_attributes.cc
1764 lines (1501 loc) · 63.8 KB
/
sair_attributes.cc
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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "sair_attributes.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TypeSwitch.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/AttributeSupport.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/OpDefinition.h"
#include "mlir/IR/Types.h"
#include "sair_dialect.h"
namespace sair {
#include "sair_attr_interfaces.cc.inc"
mlir::InFlightDiagnostic AttrLocation::EmitError() const {
if (name_ == nullptr) {
return mlir::emitError(loc_) << "in " << kind_ << ": ";
}
return mlir::emitError(location()) << "in " << kind_ << " " << name() << ": ";
}
mlir::Diagnostic &operator<<(mlir::Diagnostic &diag, const AttrLocation &loc) {
diag << loc.kind_;
if (loc.name_ == nullptr) return diag;
return diag << " " << loc.name_;
}
//===----------------------------------------------------------------------===//
// MappingExpr
//===----------------------------------------------------------------------===//
MappingExpr MappingExpr::SubstituteDims(
mlir::ArrayRef<MappingExpr> exprs) const {
return Map([&](MappingExpr sub_expr) -> MappingExpr {
auto dim_expr = sub_expr.dyn_cast<MappingDimExpr>();
if (dim_expr == nullptr) return sub_expr;
if (dim_expr.dimension() >= exprs.size()) {
return MappingNoneExpr::get(getContext());
}
return exprs[dim_expr.dimension()];
});
}
llvm::SmallBitVector MappingExpr::DependencyMask(int domain_size) const {
llvm::SmallBitVector mask(domain_size);
SetDependenciesInMask(mask);
return mask;
}
bool MappingExpr::HasNoneExprs() const {
bool has_none_exprs = false;
Walk([&](MappingExpr sub_expr) {
has_none_exprs |= sub_expr.isa<MappingNoneExpr>();
});
return has_none_exprs;
}
bool MappingExpr::HasUnknownExprs() const {
bool has_unknown_exprs = false;
Walk([&](MappingExpr sub_expr) {
has_unknown_exprs |= sub_expr.isa<MappingUnknownExpr>();
});
return has_unknown_exprs;
}
void MappingExpr::SetDependenciesInMask(llvm::SmallBitVector &mask) const {
Walk([&](MappingExpr sub_expr) {
auto dim_expr = sub_expr.dyn_cast<MappingDimExpr>();
if (dim_expr == nullptr) return;
mask.set(dim_expr.dimension());
});
}
int MappingExpr::MinDomainSize() const {
int min_domain_size = 0;
Walk([&](MappingExpr sub_expr) {
auto dim_expr = sub_expr.dyn_cast<MappingDimExpr>();
if (dim_expr == nullptr) return;
min_domain_size = std::max(min_domain_size, dim_expr.dimension() + 1);
});
return min_domain_size;
}
// Resolves unification of `lhs` and `rhs` for the case where one of the
// expression is `?` or `none`. Returns `nullptr` if unification fails.
static MappingExpr ResolveNoneAndUnknownUnification(MappingExpr lhs,
MappingExpr rhs) {
if (lhs.isa<MappingNoneExpr>()) return rhs;
if (rhs.isa<MappingNoneExpr>()) return lhs;
if (lhs.isa<MappingUnknownExpr>()) return rhs;
if (rhs.isa<MappingUnknownExpr>()) return lhs;
return MappingExpr();
}
MappingExpr Unify(MappingExpr lhs, MappingExpr rhs) {
return lhs.Unify(rhs, ResolveNoneAndUnknownUnification);
}
mlir::LogicalResult UnificationConstraints(
MappingAttr lhs, MappingAttr rhs,
llvm::MutableArrayRef<MappingExpr> constraints) {
assert(lhs.size() == rhs.size());
// Shift lhs so that all its dimensions are distinct from rhs.
int shift = rhs.UseDomainSize();
lhs = lhs.ShiftRight(shift);
for (auto [lhs_expr, rhs_expr] : llvm::zip(lhs, rhs)) {
MappingExpr result =
lhs_expr.Unify(rhs_expr, [&](MappingExpr sub_lhs, MappingExpr sub_rhs) {
auto trivial_resolve =
ResolveNoneAndUnknownUnification(sub_lhs, sub_rhs);
if (trivial_resolve != nullptr) return trivial_resolve;
auto dim_expr = sub_lhs.dyn_cast<MappingDimExpr>();
if (dim_expr == nullptr) return MappingExpr();
MappingExpr &constraint = constraints[dim_expr.dimension() - shift];
constraint = Unify(constraint, sub_rhs);
if (constraint == nullptr) return MappingExpr();
return sub_lhs;
});
if (result == nullptr) return mlir::failure();
}
return mlir::success();
}
//===----------------------------------------------------------------------===//
// MappingDimExpr
//===----------------------------------------------------------------------===//
// Private implementation/storage class for sair::MappingDimExpr.
// Instances of this class are allocate by MLIR type system in a dedicated
// arena. Not intended for direct use.
class impl::MappingDimExprStorage : public mlir::AttributeStorage {
public:
// Key type uniquely identifies MappingDimExpr for MLIR attribute
// unique-ing. This specific name is required by mlir::AttributeUniquer.
using KeyTy = int;
// Creates a MappingDimExprStorage using the provided allocator. Hook
// for MLIR attribute system.
static MappingDimExprStorage *construct(
mlir::AttributeStorageAllocator &allocator, const KeyTy &key) {
return new (allocator.allocate<MappingDimExprStorage>())
MappingDimExprStorage(key);
}
// Compares the MappingDimExprStorage identification key with this
// object.
bool operator==(const KeyTy &key) const { return key == dimension_; }
// Returns the dimension represented by the operation.
int dimension() const { return dimension_; }
private:
// Constructs a storage object for the provided key. such objects must not be
// constructed directly but rather created by MLIR's type system within an
// arena allocator by calling ::construct.
explicit MappingDimExprStorage(KeyTy key) : dimension_(key) {}
int dimension_;
};
MappingDimExpr MappingDimExpr::get(int dimension, mlir::MLIRContext *context) {
return Base::get(context, dimension);
}
int MappingDimExpr::dimension() const { return getImpl()->dimension(); }
MappingExpr MappingDimExpr::Map(
llvm::function_ref<MappingExpr(MappingExpr)> function) const {
return function(*this);
}
void MappingDimExpr::Walk(
llvm::function_ref<void(MappingExpr)> function) const {
function(*this);
}
mlir::LogicalResult MappingDimExpr::SetInverse(
MappingExpr context_inverse,
llvm::MutableArrayRef<MappingExpr> inverses) const {
MappingExpr inverse = sair::Unify(inverses[dimension()], context_inverse);
if (inverse == nullptr) return mlir::failure();
inverses[dimension()] = inverse;
return mlir::success();
}
MappingExpr MappingDimExpr::Unify(
MappingExpr other_expr,
llvm::function_ref<MappingExpr(MappingExpr, MappingExpr)> on_mismatch)
const {
if (other_expr == *this) return *this;
return on_mismatch(*this, other_expr);
}
mlir::AffineExpr MappingDimExpr::AsAffineExpr() const {
return mlir::getAffineDimExpr(dimension(), getContext());
}
//===----------------------------------------------------------------------===//
// MappingNoneExpr
//===----------------------------------------------------------------------===//
MappingNoneExpr MappingNoneExpr::get(mlir::MLIRContext *context) {
return Base::get(context);
}
MappingExpr MappingNoneExpr::Map(
llvm::function_ref<MappingExpr(MappingExpr)> function) const {
return function(*this);
}
void MappingNoneExpr::Walk(
llvm::function_ref<void(MappingExpr)> function) const {
function(*this);
}
MappingExpr MappingNoneExpr::Unify(
MappingExpr other_expr,
llvm::function_ref<MappingExpr(MappingExpr, MappingExpr)> on_mismatch)
const {
if (other_expr == *this) return *this;
return on_mismatch(*this, other_expr);
}
//===----------------------------------------------------------------------===//
// MappingUnknownExpr
//===----------------------------------------------------------------------===//
MappingUnknownExpr MappingUnknownExpr::get(mlir::MLIRContext *context) {
return Base::get(context);
}
MappingExpr MappingUnknownExpr::Map(
llvm::function_ref<MappingExpr(MappingExpr)> function) const {
return function(*this);
}
void MappingUnknownExpr::Walk(
llvm::function_ref<void(MappingExpr)> function) const {
function(*this);
}
MappingExpr MappingUnknownExpr::Unify(
MappingExpr other_expr,
llvm::function_ref<MappingExpr(MappingExpr, MappingExpr)> on_mismatch)
const {
if (other_expr == *this) return *this;
return on_mismatch(*this, other_expr);
}
//===----------------------------------------------------------------------===//
// MappingStripeExpr
//===----------------------------------------------------------------------===//
// Private implementation/storage class for sair::MappingStripeExpr.
// Instances of this class are allocate by MLIR type system in a dedicated
// arena. Not intended for direct use.
class impl::MappingStripeExprStorage : public mlir::AttributeStorage {
public:
// Key type uniquely identifies MappingStripeExpr for MLIR attribute
// unique-ing. This specific name is required by mlir::AttributeUniquer.
using KeyTy = std::pair<mlir::Attribute, llvm::ArrayRef<int>>;
// Creates a MappingStripeExprStorage using the provided allocator. Hook
// for MLIR attribute system.
static MappingStripeExprStorage *construct(
mlir::AttributeStorageAllocator &allocator, const KeyTy &key) {
return new (allocator.allocate<MappingStripeExprStorage>())
MappingStripeExprStorage(cast<MappingExpr>(key.first),
allocator.copyInto(key.second));
}
// Compares the MappingStripeExpr identification key with this object.
bool operator==(const KeyTy &key) const {
return key.first == operand_ && key.second == factors_;
}
// The striped expression.
MappingExpr operand() const { return operand_; }
// Stripe factors.
llvm::ArrayRef<int> factors() const { return factors_; }
private:
// Constructs a storage object for the provided key. such objects must not be
// constructed directly but rather created by MLIR's type system within an
// arena allocator by calling ::construct.
explicit MappingStripeExprStorage(MappingExpr operand,
llvm::ArrayRef<int> factors)
: operand_(operand), factors_(factors) {}
MappingExpr operand_;
llvm::ArrayRef<int> factors_;
};
MappingStripeExpr MappingStripeExpr::get(MappingExpr operand,
llvm::ArrayRef<int> factors) {
assert(operand != nullptr);
assert(!factors.empty());
return Base::get(operand.getContext(), std::make_tuple(operand, factors));
}
MappingExpr MappingStripeExpr::operand() const { return getImpl()->operand(); }
llvm::ArrayRef<int> MappingStripeExpr::factors() const {
return getImpl()->factors();
}
MappingExpr MappingStripeExpr::Map(
llvm::function_ref<MappingExpr(MappingExpr)> function) const {
MappingExpr new_operand = operand().Map(function);
return function(MappingStripeExpr::get(new_operand, factors()));
}
void MappingStripeExpr::Walk(
llvm::function_ref<void(MappingExpr)> function) const {
operand().Walk(function);
function(*this);
}
MappingExpr MappingStripeExpr::Unify(
MappingExpr other_expr,
llvm::function_ref<MappingExpr(MappingExpr, MappingExpr)> on_mismatch)
const {
MappingStripeExpr other_stripe = other_expr.dyn_cast<MappingStripeExpr>();
if (other_stripe == nullptr || factors() != other_stripe.factors()) {
return on_mismatch(*this, other_expr);
}
MappingExpr unified_operand =
operand().Unify(other_stripe.operand(), on_mismatch);
if (unified_operand == nullptr) return MappingExpr();
return MappingStripeExpr::get(unified_operand, factors());
}
mlir::LogicalResult MappingStripeExpr::SetInverse(
MappingExpr context_inverse,
llvm::MutableArrayRef<MappingExpr> inverses) const {
MappingExpr none = MappingNoneExpr::get(getContext());
// Prefix unstripe operands by none for outer stripes.
llvm::SmallVector<MappingExpr, 3> unstripe_operands(factors().size() - 1,
none);
unstripe_operands.push_back(context_inverse);
llvm::SmallVector<int, 2> unstripe_factors;
llvm::append_range(unstripe_factors, factors());
// Add a `none` operand for inner stripes.
if (unstripe_factors.back() != 1) {
unstripe_factors.push_back(1);
unstripe_operands.push_back(none);
}
auto unstripe = MappingUnStripeExpr::get(unstripe_operands, unstripe_factors);
return operand().SetInverse(unstripe, inverses);
}
MappingExpr MappingStripeExpr::FindInInverse(
llvm::ArrayRef<MappingExpr> inverse) const {
auto operand_inverse = operand().FindInInverse(inverse);
if (operand_inverse.isa<MappingUnknownExpr, MappingNoneExpr>()) {
return operand_inverse;
}
auto unstripe_expr = operand_inverse.cast<MappingUnStripeExpr>();
return unstripe_expr.operands()[factors().size() - 1];
}
mlir::AffineExpr MappingStripeExpr::AsAffineExpr() const {
int step = factors().back();
return step * operand().AsAffineExpr().floorDiv(step);
}
static MappingExpr GetCanonicalStripe(MappingExpr canonical_operand,
llvm::ArrayRef<int> factors) {
if (factors.size() == 1 && factors.back() == 1) return canonical_operand;
auto unstripe = canonical_operand.dyn_cast<MappingUnStripeExpr>();
if (unstripe == nullptr) {
return MappingStripeExpr::get(canonical_operand, factors);
}
auto it = std::mismatch(factors.begin(), factors.end(),
unstripe.factors().begin(), unstripe.factors().end());
// If all factors match, stripe(unstripe) is the identity function.
if (it.first == factors.end()) {
return unstripe.operands()[factors.size() - 1];
}
// Otherwise, we trip common factors.
int num_common = std::distance(factors.begin(), it.first);
auto new_unstripe =
MappingUnStripeExpr::get(unstripe.operands().drop_front(num_common),
unstripe.factors().drop_front(num_common));
return MappingStripeExpr::get(new_unstripe, factors.drop_front(num_common));
}
MappingExpr MappingStripeExpr::Canonicalize() const {
return GetCanonicalStripe(operand().Canonicalize(), factors());
}
//===----------------------------------------------------------------------===//
// MappingUnStripeExpr
//===----------------------------------------------------------------------===//
// Private implementation/storage class for sair::MappingUnStripeExpr.
// Instances of this class are allocate by MLIR type system in a dedicated
// arena. Not intended for direct use.
class impl::MappingUnStripeExprStorage : public mlir::AttributeStorage {
public:
// Key type uniquely identifies MappingUnStripeExpr for MLIR attribute
// unique-ing. This specific name is required by mlir::AttributeUniquer.
using KeyTy = std::pair<llvm::ArrayRef<MappingExpr>, llvm::ArrayRef<int>>;
// Creates a MappingUnStripeExprStorage using the provided allocator.
// Hook for MLIR attribute system.
static MappingUnStripeExprStorage *construct(
mlir::AttributeStorageAllocator &allocator, const KeyTy &key) {
return new (allocator.allocate<MappingUnStripeExprStorage>())
MappingUnStripeExprStorage(allocator.copyInto(key.first),
allocator.copyInto(key.second));
}
// Compares the MappingUnStripeExprStorage identification key with this
// object.
bool operator==(const KeyTy &key) const {
return key.first == operands_ && key.second == factors_;
}
// Stripe expressions that are combined to obtain the unstriped expression.
llvm::ArrayRef<MappingExpr> operands() const { return operands_; }
// Stripe expression sizes.
llvm::ArrayRef<int> factors() const { return factors_; }
private:
// Constructs a storage object for the provided key. such objects must not be
// constructed directly but rather created by MLIR's type system within an
// arena allocator by calling ::construct.
explicit MappingUnStripeExprStorage(llvm::ArrayRef<MappingExpr> operands,
llvm::ArrayRef<int> factors)
: operands_(operands), factors_(factors) {}
llvm::ArrayRef<MappingExpr> operands_;
llvm::ArrayRef<int> factors_;
};
MappingUnStripeExpr MappingUnStripeExpr::get(
llvm::ArrayRef<MappingExpr> stripes, llvm::ArrayRef<int> factors) {
assert(stripes.size() == factors.size());
assert(factors.back() == 1);
#ifndef NDEBUG
for (int i = 0; i + 1 < factors.size(); ++i) {
assert(factors[i] > factors[i + 1]);
}
#endif
return Base::get(stripes[0].getContext(), std::make_pair(stripes, factors));
}
llvm::ArrayRef<MappingExpr> MappingUnStripeExpr::operands() const {
return getImpl()->operands();
}
llvm::ArrayRef<int> MappingUnStripeExpr::factors() const {
return getImpl()->factors();
}
MappingExpr MappingUnStripeExpr::Map(
llvm::function_ref<MappingExpr(MappingExpr)> function) const {
auto new_operands = llvm::to_vector<4>(llvm::map_range(
operands(), [&](MappingExpr expr) { return expr.Map(function); }));
return function(MappingUnStripeExpr::get(new_operands, factors()));
}
void MappingUnStripeExpr::Walk(
llvm::function_ref<void(MappingExpr)> function) const {
for (MappingExpr operand : operands()) operand.Walk(function);
function(*this);
}
mlir::LogicalResult MappingUnStripeExpr::SetInverse(
MappingExpr context_inverse,
llvm::MutableArrayRef<MappingExpr> inverses) const {
for (int i = 0, e = factors().size(); i < e; ++i) {
MappingExpr stripe_expr =
MappingStripeExpr::get(context_inverse, factors().take_front(i + 1));
if (mlir::failed(operands()[i].SetInverse(stripe_expr, inverses))) {
return mlir::failure();
}
}
return mlir::success();
}
MappingExpr MappingUnStripeExpr::Unify(
MappingExpr other_expr,
llvm::function_ref<MappingExpr(MappingExpr, MappingExpr)> on_mismatch)
const {
MappingUnStripeExpr other_unstripe =
other_expr.dyn_cast<MappingUnStripeExpr>();
if (other_unstripe == nullptr) return on_mismatch(*this, other_expr);
llvm::SmallVector<MappingExpr> new_operands;
llvm::ArrayRef<int> new_factors;
// Operands and factors of the expression with a minimal number of factors
// among this and other.
llvm::ArrayRef<MappingExpr> min_operands;
llvm::ArrayRef<int> min_factors;
if (factors().size() >= other_unstripe.factors().size()) {
llvm::append_range(new_operands, operands());
new_factors = factors();
min_operands = other_unstripe.operands();
min_factors = other_unstripe.factors();
} else {
llvm::append_range(new_operands, other_unstripe.operands());
new_factors = other_unstripe.factors();
min_operands = operands();
min_factors = factors();
}
// If the last operand is `none` or `?`, we can replace it by an arbitrary
// number of operands.
if (min_operands.back().isa<MappingNoneExpr, MappingUnknownExpr>()) {
min_operands = min_operands.drop_back();
min_factors = min_factors.drop_back();
}
// Ensure that the factors of one are a prefix of the factors of the other.
if (min_factors != new_factors.take_front(min_factors.size())) {
return on_mismatch(*this, other_expr);
}
for (int i = 0, e = min_operands.size(); i < e; ++i) {
new_operands[i] = new_operands[i].Unify(min_operands[i], on_mismatch);
if (new_operands[i] == nullptr) return MappingExpr();
}
return MappingUnStripeExpr::get(new_operands, new_factors);
}
MappingExpr MappingUnStripeExpr::FindInInverse(
llvm::ArrayRef<MappingExpr> inverse) const {
MappingExpr operand_inverse;
for (int i = 0, e = operands().size(); i < e; ++i) {
operand_inverse = operands()[i].FindInInverse(inverse);
if (operand_inverse.isa<MappingUnknownExpr, MappingNoneExpr>()) continue;
return operand_inverse.cast<MappingStripeExpr>().operand();
}
// Unstripe has at least one operand.
return operand_inverse;
}
mlir::AffineExpr MappingUnStripeExpr::AsAffineExpr() const {
return operands().back().AsAffineExpr();
}
MappingExpr MappingUnStripeExpr::Canonicalize() const {
llvm::SmallVector<MappingExpr> new_operands;
new_operands.reserve(operands().size());
for (MappingExpr operand : operands()) {
new_operands.push_back(operand.Canonicalize());
}
llvm::SmallVector<int> new_factors;
llvm::append_range(new_factors, factors());
// Use lambdas to break the control flow. Each lambda returns true if the
// corresponding canonicalization rule was applied.
// If the last argument is an unstripe, it can be collapsed in the current
// expression.
auto collapse_unstripes = [&]() {
auto unstripe = new_operands.back().dyn_cast<MappingUnStripeExpr>();
if (unstripe == nullptr) return false;
// Stripe factors must be strictly decreasing.
if (new_factors.size() > 1 &&
new_factors[new_factors.size() - 2] <= unstripe.factors().front()) {
return false;
}
new_operands.pop_back();
new_factors.pop_back();
llvm::append_range(new_operands, unstripe.operands());
llvm::append_range(new_factors, unstripe.factors());
return true;
};
// Stiches stripe expressions that have the same operand.
auto stiche_stripes = [&]() {
auto stripe = new_operands.back().dyn_cast<MappingStripeExpr>();
if (stripe == nullptr) return false;
int min_num_factors = std::min(new_factors.size(), stripe.factors().size());
// Ensure factors are the same.
if (llvm::ArrayRef(new_factors).take_back(min_num_factors) !=
stripe.factors().take_back(min_num_factors)) {
return false;
}
// Find how many stripes we can stich together.
int first_stripe = new_operands.size() - 1;
for (; first_stripe > 0; --first_stripe) {
auto other_stripe =
new_operands[first_stripe - 1].dyn_cast<MappingStripeExpr>();
if (other_stripe == nullptr ||
other_stripe.operand() != stripe.operand()) {
break;
}
}
// Only one stripe, we can't stich anything.
if (first_stripe == new_operands.size() - 1) return false;
llvm::SmallVector<int> new_stripe_factors;
llvm::append_range(
new_stripe_factors,
stripe.factors().drop_back(new_operands.size() - first_stripe));
new_stripe_factors.push_back(1);
new_operands.resize(first_stripe);
new_factors.resize(first_stripe);
new_operands.push_back(
GetCanonicalStripe(stripe.operand(), new_stripe_factors));
new_factors.push_back(1);
return true;
};
// Apply canonicalization rules.
while (collapse_unstripes() || stiche_stripes()) {
}
if (new_factors.size() == 1 && new_factors.back() == 1)
return new_operands[0];
return MappingUnStripeExpr::get(new_operands, new_factors);
}
//===----------------------------------------------------------------------===//
// MappingAttr
//===----------------------------------------------------------------------===//
// Private implementation/storage class for sair::MappingAttr. Instances
// of this class are allocated by MLIR type system in a dedicated arena. Not
// intended for direct use.
class impl::MappingAttrStorage : public mlir::AttributeStorage {
public:
// Key type uniquely identifying MappingAttrStorage for MLIR attribute
// unique-ing. This specific name is required by mlir::AttributeUniquer.
using KeyTy = std::pair<int, llvm::ArrayRef<MappingExpr>>;
// Creates an MappingAttrStorage using the provided allocator. Hook for
// MLIR attribute system.
static MappingAttrStorage *construct(
mlir::AttributeStorageAllocator &allocator, const KeyTy &key) {
return new (allocator.allocate<MappingAttrStorage>()) MappingAttrStorage(
std::make_pair(key.first, allocator.copyInto(key.second)));
}
// Compares the MappingAttrStorage identification key with this object.
bool operator==(const KeyTy &key) const {
return key.first == use_domain_size_ && key.second == mapping_;
}
// Returns the number of dimensions in the use domain.
int use_domain_size() const { return use_domain_size_; }
// Returns the list of dimensions along which a variable is accessed.
// Dimensions are identified by their position in the domain definition.
llvm::ArrayRef<MappingExpr> mapping() const { return mapping_; }
private:
// Constructs a storage object from the provided key. Such objects must not be
// constructed directly but rather created by MLIR's type system within an
// arena allocator by calling ::construct.
explicit MappingAttrStorage(KeyTy key)
: use_domain_size_(key.first), mapping_(key.second) {}
int use_domain_size_;
// The list of dimensions along which a Sair variable is accessed.
llvm::ArrayRef<MappingExpr> mapping_;
};
// Verifies that the expressions form a valid access mapping.
static mlir::LogicalResult VerifyMappingExprs(
mlir::MLIRContext *context, int use_domain_size,
llvm::ArrayRef<MappingExpr> mapping_exprs) {
llvm::SmallVector<MappingExpr, 4> inverted_exprs(
use_domain_size, MappingNoneExpr::get(context));
for (int i = 0, e = mapping_exprs.size(); i < e; ++i) {
MappingExpr dim_expr = MappingDimExpr::get(i, context);
if (mlir::failed(mapping_exprs[i].SetInverse(dim_expr, inverted_exprs))) {
return mlir::failure();
}
}
return mlir::success();
}
MappingAttr MappingAttr::get(mlir::MLIRContext *context, int use_domain_size,
llvm::ArrayRef<MappingExpr> mapping) {
assert(
mlir::succeeded(VerifyMappingExprs(context, use_domain_size, mapping)));
return Base::get(context, std::make_pair(use_domain_size, mapping));
}
MappingAttr MappingAttr::getChecked(mlir::MLIRContext *context,
int use_domain_size,
llvm::ArrayRef<MappingExpr> mapping) {
if (mlir::failed(VerifyMappingExprs(context, use_domain_size, mapping))) {
return nullptr;
}
return Base::get(context, std::make_pair(use_domain_size, mapping));
}
MappingAttr MappingAttr::GetIdentity(mlir::MLIRContext *context,
int num_dimensions, int use_domain_size) {
if (use_domain_size == -1) use_domain_size = num_dimensions;
assert(use_domain_size >= num_dimensions);
llvm::SmallVector<MappingExpr, 4> mapping;
mapping.reserve(num_dimensions);
for (int i = 0; i < num_dimensions; ++i) {
mapping.push_back(MappingDimExpr::get(i, context));
}
return MappingAttr::get(context, use_domain_size, mapping);
}
MappingAttr MappingAttr::FromAffineMap(mlir::AffineMap map) {
assert(map.isProjectedPermutation());
llvm::SmallVector<MappingExpr, 8> dimensions;
dimensions.reserve(map.getNumResults());
for (mlir::AffineExpr expr : map.getResults()) {
dimensions.push_back(MappingDimExpr::get(
expr.cast<mlir::AffineDimExpr>().getPosition(), map.getContext()));
}
return get(map.getContext(), map.getNumDims(), dimensions);
}
llvm::ArrayRef<MappingExpr> MappingAttr::Dimensions() const {
return getImpl()->mapping();
}
int MappingAttr::UseDomainSize() const { return getImpl()->use_domain_size(); }
MappingAttr MappingAttr::Compose(MappingAttr other) const {
llvm::SmallVector<MappingExpr, 4> new_mapping_dims;
new_mapping_dims.reserve(other.size());
for (MappingExpr other_expr : other) {
new_mapping_dims.push_back(other_expr.SubstituteDims(Dimensions()));
}
return MappingAttr::get(getContext(), UseDomainSize(), new_mapping_dims);
}
mlir::AffineMap MappingAttr::AsAffineMap() const {
llvm::SmallVector<mlir::AffineExpr, 4> affine_exprs;
affine_exprs.reserve(Dimensions().size());
for (MappingExpr expr : *this) {
affine_exprs.push_back(expr.AsAffineExpr());
}
return mlir::AffineMap::get(UseDomainSize(), 0, affine_exprs, getContext());
}
bool MappingAttr::HasNoneExprs() const {
return llvm::any_of(getImpl()->mapping(),
[](MappingExpr expr) { return expr.HasNoneExprs(); });
}
bool MappingAttr::HasUnknownExprs() const {
return llvm::any_of(getImpl()->mapping(),
[](MappingExpr expr) { return expr.HasUnknownExprs(); });
}
MappingAttr MappingAttr::MakeSurjective() const {
int num_dimensions = UseDomainSize();
llvm::SmallVector<MappingExpr, 4> new_exprs;
new_exprs.reserve(size());
for (MappingExpr expr : Dimensions()) {
MappingExpr new_expr = expr.Map([&](MappingExpr sub_expr) -> MappingExpr {
if (!sub_expr.isa<MappingNoneExpr>()) return sub_expr;
return MappingDimExpr::get(num_dimensions++, getContext());
});
new_exprs.push_back(new_expr);
}
return MappingAttr::get(getContext(), num_dimensions, new_exprs);
}
MappingAttr MappingAttr::MakeFullySpecified() const {
auto none = MappingNoneExpr::get(getContext());
auto new_exprs =
llvm::to_vector<4>(llvm::map_range(Dimensions(), [&](auto expr) {
return expr.Map([&](MappingExpr sub_expr) -> MappingExpr {
return sub_expr.isa<MappingUnknownExpr>() ? none : sub_expr;
});
}));
return MappingAttr::get(getContext(), UseDomainSize(), new_exprs);
}
bool MappingAttr::IsIdentity() const {
for (auto en : llvm::enumerate(getImpl()->mapping())) {
auto dim_expr = en.value().dyn_cast<MappingDimExpr>();
if (dim_expr == nullptr || dim_expr.dimension() != en.index()) return false;
}
return true;
}
llvm::SmallBitVector MappingAttr::DependencyMask() const {
llvm::SmallBitVector mask(UseDomainSize());
for (MappingExpr expr : *this) {
expr.SetDependenciesInMask(mask);
}
return mask;
}
bool MappingAttr::IsInjective(int num_dimensions) const {
llvm::SmallBitVector mask = DependencyMask();
mask.resize(num_dimensions);
return mask.all();
}
MappingAttr MappingAttr::ResizeUseDomain(int new_size) const {
int old_size = UseDomainSize();
if (new_size == old_size) return *this;
if (new_size >= old_size) {
return MappingAttr::get(getContext(), new_size, Dimensions());
}
mlir::MLIRContext *context = getContext();
MappingExpr none = MappingNoneExpr::get(context);
llvm::SmallVector<MappingExpr, 4> substitutions(old_size, none);
substitutions.reserve(old_size);
for (int i = 0; i < new_size; ++i) {
substitutions[i] = MappingDimExpr::get(i, context);
}
llvm::SmallVector<MappingExpr, 4> new_exprs;
new_exprs.reserve(size());
for (MappingExpr expr : *this) {
new_exprs.push_back(expr.SubstituteDims(substitutions));
}
return MappingAttr::get(getContext(), new_size, new_exprs);
}
MappingAttr MappingAttr::Resize(int new_size) const {
int current_size = Dimensions().size();
if (new_size == current_size) return *this;
if (new_size < current_size) {
return MappingAttr::get(getContext(), UseDomainSize(),
Dimensions().take_front(new_size));
}
llvm::SmallVector<MappingExpr, 4> dimensions(Dimensions().begin(),
Dimensions().end());
dimensions.resize(new_size, MappingNoneExpr::get(getContext()));
return MappingAttr::get(getContext(), UseDomainSize(), dimensions);
}
MappingAttr MappingAttr::ShiftRight(int offset, int start_from) const {
mlir::MLIRContext *context = getContext();
llvm::SmallVector<MappingExpr, 4> substitutions;
substitutions.reserve(UseDomainSize());
for (int i = 0; i < start_from; ++i) {
substitutions.push_back(MappingDimExpr::get(i, context));
}
for (int i = start_from, e = UseDomainSize(); i < e; ++i) {
substitutions.push_back(MappingDimExpr::get(i + offset, context));
}
llvm::SmallVector<MappingExpr, 8> new_dimensions;
new_dimensions.reserve(Dimensions().size());
for (MappingExpr dim : Dimensions()) {
new_dimensions.push_back(dim.SubstituteDims(substitutions));
}
return MappingAttr::get(context, UseDomainSize() + offset, new_dimensions);
}
MappingAttr MappingAttr::Inverse() const {
mlir::MLIRContext *context = getContext();
llvm::SmallVector<MappingExpr, 4> inverted_exprs(
UseDomainSize(), MappingNoneExpr::get(context));
for (int i = 0, e = size(); i < e; ++i) {
MappingExpr dim_expr = MappingDimExpr::get(i, context);
auto status = Dimension(i).SetInverse(dim_expr, inverted_exprs);
assert(mlir::succeeded(status));
(void)status;
}
return MappingAttr::get(context, size(), inverted_exprs);
}
MappingAttr MappingAttr::Canonicalize() const {
llvm::SmallVector<MappingExpr, 4> exprs;
exprs.reserve(size());
for (MappingExpr expr : Dimensions()) {
exprs.push_back(expr.Canonicalize());
}
return MappingAttr::get(getContext(), UseDomainSize(), exprs);
}
int MappingAttr::MinDomainSize() const {
int min = 0;
for (MappingExpr expr : Dimensions()) {
min = std::max(min, expr.MinDomainSize());
}
return min;
}
MappingAttr MappingAttr::Unify(MappingAttr other) const {
assert(size() == other.size());
assert(UseDomainSize() == other.UseDomainSize());
llvm::SmallVector<MappingExpr> exprs;
exprs.reserve(size());
for (auto [x, y] : llvm::zip(Dimensions(), other.Dimensions())) {
exprs.push_back(sair::Unify(x, y));
if (exprs.back() == nullptr) return nullptr;
}
return MappingAttr::get(getContext(), UseDomainSize(), exprs);
}
MappingAttr MappingAttr::UnifyUnknownExprs(MappingAttr other) const {
assert(size() == other.size());
assert(UseDomainSize() == other.UseDomainSize());
llvm::SmallVector<MappingExpr> exprs;
exprs.reserve(size());
for (auto [lhs, rhs] : llvm::zip(Dimensions(), other.Dimensions())) {
MappingExpr unified =
lhs.Unify(rhs, [](MappingExpr sub_lhs, MappingExpr sub_rhs) {
if (sub_lhs.isa<MappingUnknownExpr>()) return sub_rhs;
if (sub_rhs.isa<MappingUnknownExpr>()) return sub_lhs;
return MappingExpr();
});
if (unified == nullptr) return nullptr;
exprs.push_back(unified);
}
return MappingAttr::get(getContext(), UseDomainSize(), exprs);
}
MappingAttr MappingAttr::AddPrefix(llvm::ArrayRef<MappingExpr> exprs) const {
llvm::SmallVector<MappingExpr> new_exprs;
new_exprs.reserve(exprs.size() + size());
llvm::append_range(new_exprs, exprs);
llvm::append_range(new_exprs, Dimensions());
return MappingAttr::get(getContext(), UseDomainSize(), new_exprs);
}
MappingAttr MappingAttr::AddSuffix(llvm::ArrayRef<MappingExpr> exprs) const {
llvm::SmallVector<MappingExpr> new_exprs;
new_exprs.reserve(exprs.size() + size());
llvm::append_range(new_exprs, Dimensions());
llvm::append_range(new_exprs, exprs);
return MappingAttr::get(getContext(), UseDomainSize(), new_exprs);
}
MappingAttr MappingAttr::Slice(int begin, int new_size) const {
assert(begin >= 0);
assert(new_size >= 0);
assert(begin + new_size <= size());
return MappingAttr::get(getContext(), UseDomainSize(),
Dimensions().slice(begin, new_size));
}
MappingAttr MappingAttr::DropFront(int num_drop) const {
return Slice(num_drop, size() - num_drop);
}
//===----------------------------------------------------------------------===//
// NamedMappingAttr
//===----------------------------------------------------------------------===//
// Private implementation/storage class for sair::NamedMappingAttr. Instances of
// this class are allocated by MLIR type system in a dedicated arena. Not
// intended for direct use.
class impl::NamedMappingAttrStorage : public mlir::AttributeStorage {
public:
// Key type uniquely identifying MappingAttrStorage for MLIR attribute
// unique-ing. This specific name is required by mlir::AttributeUniquer.
using KeyTy = std::pair<llvm::ArrayRef<mlir::StringAttr>, mlir::Attribute>;
// Creates a NamedMappingAttrStorage using the provided allocator. Hook for
// MLIR attribute system.