-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathOps.cpp
5881 lines (5274 loc) · 207 KB
/
Ops.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
//===- PolygeistOps.cpp - BFV dialect ops ---------------*- C++ -*-===//
//
// This file is licensed 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
//
//===----------------------------------------------------------------------===//
#include "polygeist/Ops.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/Interfaces/SideEffectInterfaces.h"
#include "polygeist/Dialect.h"
#define GET_OP_CLASSES
#include "polygeist/PolygeistOps.cpp.inc"
#include "mlir/Dialect/Affine/IR/AffineOps.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/OpenMP/OpenMPDialect.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/IR/Dominance.h"
#include "mlir/IR/IRMapping.h"
#include "mlir/IR/IntegerSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/Debug.h"
#include <set>
#define DEBUG_TYPE "polygeist"
using namespace mlir;
using namespace polygeist;
using namespace mlir::arith;
llvm::cl::opt<bool> BarrierOpt("barrier-opt", llvm::cl::init(true),
llvm::cl::desc("Optimize barriers"));
//===----------------------------------------------------------------------===//
// UndefOp
//===----------------------------------------------------------------------===//
class UndefToLLVM final : public OpRewritePattern<UndefOp> {
public:
using OpRewritePattern<UndefOp>::OpRewritePattern;
LogicalResult matchAndRewrite(UndefOp uop,
PatternRewriter &rewriter) const override {
auto ty = uop.getResult().getType();
if (!LLVM::isCompatibleType(ty))
return failure();
rewriter.replaceOpWithNewOp<LLVM::UndefOp>(uop, ty);
return success();
}
};
void UndefOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results.insert<UndefToLLVM>(context);
}
//===----------------------------------------------------------------------===//
// NoopOp
//===----------------------------------------------------------------------===//
struct NoopResource : public SideEffects::Resource::Base<NoopResource> {
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(NoopResource)
StringRef getName() final { return "<NoopResource>"; }
};
void NoopOp::build(OpBuilder &builder, OperationState &result,
ValueRange indices) {
result.addOperands(indices);
}
void NoopOp::getEffects(
SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
// TODO CHECK is it okay to ::get() a new resource every time?
SideEffects::Resource *resource = NoopResource::get();
MemoryEffects::Effect *effect =
MemoryEffects::Effect::get<MemoryEffects::Write>();
effects.emplace_back(effect, resource);
}
//===----------------------------------------------------------------------===//
// GetDeviceGlobalOp
//===----------------------------------------------------------------------===//
void GetDeviceGlobalOp::getEffects(
SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
// TODO CHECK is it okay to ::get() a new resource every time?
SideEffects::Resource *resource = NoopResource::get();
MemoryEffects::Effect *effect =
MemoryEffects::Effect::get<MemoryEffects::Write>();
effects.emplace_back(effect, resource);
effect = MemoryEffects::Effect::get<MemoryEffects::Read>();
effects.emplace_back(effect, resource);
}
LogicalResult
GetDeviceGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
// Verify that the result type is same as the type of the referenced
// memref.global op.
auto global = symbolTable.lookupNearestSymbolFrom<memref::GlobalOp>(
*this, getNameAttr());
if (!global)
return emitOpError("'")
<< getName() << "' does not reference a valid global memref";
Type resultType = getResult().getType();
if (global.getType() != resultType)
return emitOpError("result type ")
<< resultType << " does not match type " << global.getType()
<< " of the global memref @" << getName();
return success();
}
//===----------------------------------------------------------------------===//
// GPUErrorOp
//===----------------------------------------------------------------------===//
void GPUErrorOp::build(OpBuilder &builder, OperationState &result) {
result.addTypes(builder.getIndexType());
OpBuilder::InsertionGuard g(builder);
Region *bodyRegion = result.addRegion();
builder.createBlock(bodyRegion);
GPUErrorOp::ensureTerminator(*bodyRegion, builder, result.location);
}
//===----------------------------------------------------------------------===//
// AlternativesOp
//===----------------------------------------------------------------------===//
void AlternativesOp::build(OpBuilder &builder, OperationState &result,
int regionNum) {
OpBuilder::InsertionGuard g(builder);
for (int i = 0; i < regionNum; i++) {
Region *bodyRegion = result.addRegion();
Block *block = builder.createBlock(bodyRegion);
builder.setInsertionPointToEnd(block);
builder.create<PolygeistYieldOp>(result.location);
}
}
class HoistSingleAlternative final : public OpRewritePattern<AlternativesOp> {
public:
using OpRewritePattern<AlternativesOp>::OpRewritePattern;
LogicalResult matchAndRewrite(AlternativesOp aop,
PatternRewriter &rewriter) const override {
assert(aop->getNumRegions() > 0);
if (aop->getNumRegions() > 1) {
return failure();
}
auto block = &*aop->getRegions()[0].begin();
rewriter.eraseOp(block->getTerminator());
rewriter.inlineBlockBefore(block, aop);
rewriter.eraseOp(aop);
return success();
}
};
class FlattenAlternatives final : public OpRewritePattern<AlternativesOp> {
public:
using OpRewritePattern<AlternativesOp>::OpRewritePattern;
LogicalResult matchAndRewrite(AlternativesOp aop,
PatternRewriter &rewriter) const override {
// Ignore nested alternatives ops
if (aop->getParentOfType<AlternativesOp>())
return failure();
AlternativesOp innerAop = nullptr;
unsigned regionId = 0;
for (auto ®ion : aop->getRegions()) {
for (auto &op : region.getOps()) {
if (auto aop = dyn_cast<AlternativesOp>(&op)) {
innerAop = aop;
break;
}
}
if (innerAop)
break;
regionId++;
}
if (!innerAop)
return failure();
// TODO use block insertion etc for better performance
auto newAop = rewriter.create<polygeist::AlternativesOp>(
aop->getLoc(), innerAop->getNumRegions() + aop->getNumRegions() - 1);
newAop->setAttrs(aop->getAttrs());
auto outerDescs = aop->getAttrOfType<ArrayAttr>("alternatives.descs");
auto innerDescs = innerAop->getAttrOfType<ArrayAttr>("alternatives.descs");
std::vector<Attribute> configs;
unsigned curRegion = 0;
for (; curRegion < innerAop->getNumRegions(); curRegion++) {
IRMapping mapping;
auto block = &*newAop->getRegion(curRegion).begin();
rewriter.setInsertionPointToStart(block);
for (auto &op : *innerAop->getBlock()) {
if (&op == innerAop.getOperation()) {
for (auto &op : innerAop->getRegion(curRegion).getOps())
if (!isa<PolygeistYieldOp>(&op))
rewriter.clone(op, mapping);
} else {
if (!isa<PolygeistYieldOp>(&op))
rewriter.clone(op, mapping);
}
}
configs.push_back(rewriter.getStringAttr(
outerDescs[regionId].cast<StringAttr>().str() +
innerDescs[curRegion].cast<StringAttr>().str()));
}
unsigned oldRegion = 0;
for (; oldRegion < aop->getNumRegions(); oldRegion++) {
auto &srcRegion = aop->getRegion(oldRegion);
if (innerAop->getBlock()->getParent() == &srcRegion) {
assert(oldRegion == regionId);
continue;
}
auto block = &*newAop->getRegion(curRegion).begin();
rewriter.setInsertionPointToStart(block);
IRMapping mapping;
for (auto &op : srcRegion.getOps())
if (!isa<PolygeistYieldOp>(&op))
rewriter.clone(op, mapping);
configs.push_back(rewriter.getStringAttr(
outerDescs[oldRegion].cast<StringAttr>().str()));
curRegion++;
}
newAop->setAttr("alternatives.descs", rewriter.getArrayAttr(configs));
rewriter.eraseOp(aop);
return success();
}
};
void AlternativesOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results.insert<HoistSingleAlternative, FlattenAlternatives>(context);
}
//===----------------------------------------------------------------------===//
// GPUBlockOp
//===----------------------------------------------------------------------===//
void GPUBlockOp::build(OpBuilder &builder, OperationState &result,
Value blockIndexX, Value blockIndexY,
Value blockIndexZ) {
result.addOperands({blockIndexX, blockIndexY, blockIndexZ});
OpBuilder::InsertionGuard g(builder);
Region *bodyRegion = result.addRegion();
builder.createBlock(bodyRegion);
GPUBlockOp::ensureTerminator(*bodyRegion, builder, result.location);
}
//===----------------------------------------------------------------------===//
// GPUThreadOp
//===----------------------------------------------------------------------===//
void GPUThreadOp::build(OpBuilder &builder, OperationState &result,
Value blockIndexX, Value blockIndexY,
Value blockIndexZ) {
result.addOperands({blockIndexX, blockIndexY, blockIndexZ});
OpBuilder::InsertionGuard g(builder);
Region *bodyRegion = result.addRegion();
builder.createBlock(bodyRegion);
GPUThreadOp::ensureTerminator(*bodyRegion, builder, result.location);
}
//===----------------------------------------------------------------------===//
// GPUWrapperOp
//===----------------------------------------------------------------------===//
void GPUWrapperOp::build(OpBuilder &builder, OperationState &result,
ValueRange blockSizes) {
result.addTypes(builder.getIndexType());
result.addOperands(blockSizes);
OpBuilder::InsertionGuard g(builder);
Region *bodyRegion = result.addRegion();
builder.createBlock(bodyRegion);
GPUWrapperOp::ensureTerminator(*bodyRegion, builder, result.location);
}
void GPUWrapperOp::build(OpBuilder &builder, OperationState &result) {
result.addTypes(builder.getIndexType());
OpBuilder::InsertionGuard g(builder);
Region *bodyRegion = result.addRegion();
builder.createBlock(bodyRegion);
GPUWrapperOp::ensureTerminator(*bodyRegion, builder, result.location);
}
//===----------------------------------------------------------------------===//
// BarrierOp
//===----------------------------------------------------------------------===//
LogicalResult verify(BarrierOp) { return success(); }
/// Collect the memory effects of the given op in 'effects'. Returns 'true' it
/// could extract the effect information from the op, otherwise returns 'false'
/// and conservatively populates the list with all possible effects.
bool collectEffects(Operation *op,
SmallVectorImpl<MemoryEffects::EffectInstance> &effects,
bool ignoreBarriers) {
// Skip over barriers to avoid infinite recursion (those barriers would ask
// this barrier again).
if (ignoreBarriers && isa<BarrierOp>(op))
return true;
// Ignore CacheLoads as they are already guaranteed to not have side effects
// in the context of a parallel op, these only exist while we are in the
// CPUifyPass
if (isa<CacheLoad>(op))
return true;
// Collect effect instances the operation. Note that the implementation of
// getEffects erases all effect instances that have the type other than the
// template parameter so we collect them first in a local buffer and then
// copy.
if (auto iface = dyn_cast<MemoryEffectOpInterface>(op)) {
SmallVector<MemoryEffects::EffectInstance> localEffects;
iface.getEffects(localEffects);
llvm::append_range(effects, localEffects);
return true;
}
if (op->hasTrait<OpTrait::HasRecursiveMemoryEffects>()) {
for (auto ®ion : op->getRegions()) {
for (auto &block : region) {
for (auto &innerOp : block)
if (!collectEffects(&innerOp, effects, ignoreBarriers))
return false;
}
}
return true;
}
if (auto cop = dyn_cast<LLVM::CallOp>(op)) {
if (auto callee = cop.getCallee()) {
if (*callee == "scanf" || *callee == "__isoc99_scanf") {
// Global read
effects.emplace_back(MemoryEffects::Effect::get<MemoryEffects::Read>());
bool first = true;
for (auto arg : cop.getArgOperands()) {
if (first)
effects.emplace_back(::mlir::MemoryEffects::Read::get(), arg,
::mlir::SideEffects::DefaultResource::get());
else
effects.emplace_back(::mlir::MemoryEffects::Write::get(), arg,
::mlir::SideEffects::DefaultResource::get());
first = false;
}
return true;
}
if (*callee == "fscanf" || *callee == "__isoc99_fscanf") {
// Global read
effects.emplace_back(MemoryEffects::Effect::get<MemoryEffects::Read>());
for (auto argp : llvm::enumerate(cop.getArgOperands())) {
auto arg = argp.value();
auto idx = argp.index();
if (idx == 0) {
effects.emplace_back(::mlir::MemoryEffects::Read::get(), arg,
::mlir::SideEffects::DefaultResource::get());
effects.emplace_back(::mlir::MemoryEffects::Write::get(), arg,
::mlir::SideEffects::DefaultResource::get());
} else if (idx == 1) {
effects.emplace_back(::mlir::MemoryEffects::Read::get(), arg,
::mlir::SideEffects::DefaultResource::get());
} else
effects.emplace_back(::mlir::MemoryEffects::Write::get(), arg,
::mlir::SideEffects::DefaultResource::get());
}
return true;
}
if (*callee == "printf") {
// Global read
effects.emplace_back(
MemoryEffects::Effect::get<MemoryEffects::Write>());
for (auto arg : cop.getArgOperands()) {
effects.emplace_back(::mlir::MemoryEffects::Read::get(), arg,
::mlir::SideEffects::DefaultResource::get());
}
return true;
}
if (*callee == "free") {
for (auto arg : cop.getArgOperands()) {
effects.emplace_back(::mlir::MemoryEffects::Free::get(), arg,
::mlir::SideEffects::DefaultResource::get());
}
return true;
}
if (*callee == "strlen") {
for (auto arg : cop.getArgOperands()) {
effects.emplace_back(::mlir::MemoryEffects::Read::get(), arg,
::mlir::SideEffects::DefaultResource::get());
}
return true;
}
}
}
// We need to be conservative here in case the op doesn't have the interface
// and assume it can have any possible effect.
effects.emplace_back(MemoryEffects::Effect::get<MemoryEffects::Read>());
effects.emplace_back(MemoryEffects::Effect::get<MemoryEffects::Write>());
effects.emplace_back(MemoryEffects::Effect::get<MemoryEffects::Allocate>());
effects.emplace_back(MemoryEffects::Effect::get<MemoryEffects::Free>());
return false;
}
// Rethrns if we are non-conservative whether we have filled with all possible
// effects.
bool getEffectsBefore(Operation *op,
SmallVectorImpl<MemoryEffects::EffectInstance> &effects,
bool stopAtBarrier) {
if (op != &op->getBlock()->front())
for (Operation *it = op->getPrevNode(); it != nullptr;
it = it->getPrevNode()) {
if (isa<BarrierOp>(it)) {
if (stopAtBarrier)
return true;
else
continue;
}
if (!collectEffects(it, effects, /* ignoreBarriers */ true))
return false;
}
bool conservative = false;
if (isa<scf::ParallelOp, affine::AffineParallelOp>(op->getParentOp()))
return true;
// As we didn't hit another barrier, we must check the predecessors of this
// operation.
if (!getEffectsBefore(op->getParentOp(), effects, stopAtBarrier))
return false;
// If the parent operation is not guaranteed to execute its (single-block)
// region once, walk the block.
if (!isa<scf::IfOp, affine::AffineIfOp, memref::AllocaScopeOp>(
op->getParentOp()))
op->getParentOp()->walk([&](Operation *in) {
if (conservative)
return WalkResult::interrupt();
if (!collectEffects(in, effects, /* ignoreBarriers */ true)) {
conservative = true;
return WalkResult::interrupt();
}
return WalkResult::advance();
});
return !conservative;
}
bool getEffectsAfter(Operation *op,
SmallVectorImpl<MemoryEffects::EffectInstance> &effects,
bool stopAtBarrier) {
if (op != &op->getBlock()->back())
for (Operation *it = op->getNextNode(); it != nullptr;
it = it->getNextNode()) {
if (isa<BarrierOp>(it)) {
if (stopAtBarrier)
return true;
continue;
}
if (!collectEffects(it, effects, /* ignoreBarriers */ true))
return false;
}
bool conservative = false;
if (isa<scf::ParallelOp, affine::AffineParallelOp>(op->getParentOp()))
return true;
// As we didn't hit another barrier, we must check the predecessors of this
// operation.
if (!getEffectsAfter(op->getParentOp(), effects, stopAtBarrier))
return false;
// If the parent operation is not guaranteed to execute its (single-block)
// region once, walk the block.
if (!isa<scf::IfOp, affine::AffineIfOp, memref::AllocaScopeOp>(
op->getParentOp()))
op->getParentOp()->walk([&](Operation *in) {
if (conservative)
return WalkResult::interrupt();
if (!collectEffects(in, effects, /* ignoreBarriers */ true)) {
conservative = true;
return WalkResult::interrupt();
}
return WalkResult::advance();
});
return !conservative;
}
void BarrierOp::getEffects(
SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
// If this doesn't synchronize any values, it has no effects.
if (llvm::all_of(getOperands(), [](Value v) {
IntegerAttr constValue;
return matchPattern(v, m_Constant(&constValue));
}))
return;
Operation *op = getOperation();
if (!getEffectsBefore(op, effects, /*stopAtBarrier*/ true))
return;
if (!getEffectsAfter(op, effects, /*stopAtBarrier*/ true))
return;
}
bool isReadOnly(Operation *op) {
bool hasRecursiveEffects = op->hasTrait<OpTrait::HasRecursiveMemoryEffects>();
if (hasRecursiveEffects) {
for (Region ®ion : op->getRegions()) {
for (auto &block : region) {
for (auto &nestedOp : block)
if (!isReadOnly(&nestedOp))
return false;
}
}
return true;
}
// If the op has memory effects, try to characterize them to see if the op
// is trivially dead here.
if (auto effectInterface = dyn_cast<MemoryEffectOpInterface>(op)) {
// Check to see if this op either has no effects, or only allocates/reads
// memory.
SmallVector<MemoryEffects::EffectInstance, 1> effects;
effectInterface.getEffects(effects);
if (!llvm::all_of(effects, [op](const MemoryEffects::EffectInstance &it) {
return isa<MemoryEffects::Read>(it.getEffect());
})) {
return false;
}
return true;
}
return false;
}
bool isReadNone(Operation *op) {
bool hasRecursiveEffects = op->hasTrait<OpTrait::HasRecursiveMemoryEffects>();
if (hasRecursiveEffects) {
for (Region ®ion : op->getRegions()) {
for (auto &block : region) {
for (auto &nestedOp : block)
if (!isReadNone(&nestedOp))
return false;
}
}
return true;
}
// If the op has memory effects, try to characterize them to see if the op
// is trivially dead here.
if (auto effectInterface = dyn_cast<MemoryEffectOpInterface>(op)) {
// Check to see if this op either has no effects, or only allocates/reads
// memory.
SmallVector<MemoryEffects::EffectInstance, 1> effects;
effectInterface.getEffects(effects);
if (llvm::any_of(effects, [op](const MemoryEffects::EffectInstance &it) {
return isa<MemoryEffects::Read>(it.getEffect()) ||
isa<MemoryEffects::Write>(it.getEffect());
})) {
return false;
}
return true;
}
return false;
}
class BarrierHoist final : public OpRewritePattern<BarrierOp> {
public:
using OpRewritePattern<BarrierOp>::OpRewritePattern;
LogicalResult matchAndRewrite(BarrierOp barrier,
PatternRewriter &rewriter) const override {
if (!BarrierOpt)
return failure();
if (isa<scf::IfOp, affine::AffineIfOp>(barrier->getParentOp())) {
bool below = true;
for (Operation *it = barrier->getNextNode(); it != nullptr;
it = it->getNextNode()) {
if (!isReadNone(it)) {
below = false;
break;
}
}
if (below) {
rewriter.setInsertionPoint(barrier->getParentOp()->getNextNode());
rewriter.create<BarrierOp>(barrier.getLoc(), barrier.getOperands());
rewriter.eraseOp(barrier);
return success();
}
bool above = true;
for (Operation *it = barrier->getPrevNode(); it != nullptr;
it = it->getPrevNode()) {
if (!isReadNone(it)) {
above = false;
break;
}
}
if (above) {
rewriter.setInsertionPoint(barrier->getParentOp());
rewriter.create<BarrierOp>(barrier.getLoc(), barrier.getOperands());
rewriter.eraseOp(barrier);
return success();
}
}
// Move barrier into after region and after loop, if possible
if (auto whileOp = dyn_cast<scf::WhileOp>(barrier->getParentOp())) {
if (barrier->getParentRegion() == &whileOp.getBefore()) {
auto cond = whileOp.getBefore().front().getTerminator();
bool above = true;
for (Operation *it = cond; it != nullptr; it = it->getPrevNode()) {
if (it == barrier)
break;
if (!isReadNone(it)) {
above = false;
break;
}
}
if (above) {
rewriter.setInsertionPointToStart(&whileOp.getAfter().front());
rewriter.create<BarrierOp>(barrier.getLoc(), barrier.getOperands());
rewriter.setInsertionPoint(whileOp->getNextNode());
rewriter.create<BarrierOp>(barrier.getLoc(), barrier.getOperands());
rewriter.eraseOp(barrier);
return success();
}
}
}
return failure();
}
};
const std::set<std::string> &getNonCapturingFunctions() {
static std::set<std::string> NonCapturingFunctions = {
"free", "printf", "fprintf", "scanf",
"fscanf", "gettimeofday", "clock_gettime", "getenv",
"strrchr", "strlen", "sprintf", "sscanf",
"mkdir", "fwrite", "fread", "memcpy",
"cudaMemcpy", "memset", "cudaMemset", "__isoc99_scanf",
"__isoc99_fscanf"};
return NonCapturingFunctions;
}
bool isCaptured(Value v, Operation *potentialUser = nullptr,
bool *seenuse = nullptr) {
SmallVector<Value> todo = {v};
while (todo.size()) {
Value v = todo.pop_back_val();
for (auto u : v.getUsers()) {
if (seenuse && u == potentialUser)
*seenuse = true;
if (isa<memref::LoadOp, LLVM::LoadOp, affine::AffineLoadOp,
polygeist::CacheLoad>(u))
continue;
if (auto s = dyn_cast<memref::StoreOp>(u)) {
if (s.getValue() == v)
return true;
continue;
}
if (auto s = dyn_cast<affine::AffineStoreOp>(u)) {
if (s.getValue() == v)
return true;
continue;
}
if (auto s = dyn_cast<LLVM::StoreOp>(u)) {
if (s.getValue() == v)
return true;
continue;
}
if (auto sub = dyn_cast<LLVM::GEPOp>(u)) {
todo.push_back(sub);
}
if (auto sub = dyn_cast<LLVM::BitcastOp>(u)) {
todo.push_back(sub);
}
if (auto sub = dyn_cast<LLVM::AddrSpaceCastOp>(u)) {
todo.push_back(sub);
}
if (auto sub = dyn_cast<func::ReturnOp>(u)) {
continue;
}
if (auto sub = dyn_cast<LLVM::MemsetOp>(u)) {
continue;
}
if (auto sub = dyn_cast<LLVM::MemcpyOp>(u)) {
continue;
}
if (auto sub = dyn_cast<LLVM::MemmoveOp>(u)) {
continue;
}
if (auto sub = dyn_cast<memref::CastOp>(u)) {
todo.push_back(sub);
}
if (auto sub = dyn_cast<memref::DeallocOp>(u)) {
continue;
}
if (auto sub = dyn_cast<polygeist::SubIndexOp>(u)) {
todo.push_back(sub);
}
if (auto sub = dyn_cast<polygeist::Memref2PointerOp>(u)) {
todo.push_back(sub);
}
if (auto sub = dyn_cast<polygeist::Pointer2MemrefOp>(u)) {
todo.push_back(sub);
}
if (auto cop = dyn_cast<LLVM::CallOp>(u)) {
if (auto callee = cop.getCallee()) {
if (getNonCapturingFunctions().count(callee->str()))
continue;
}
}
if (auto cop = dyn_cast<func::CallOp>(u)) {
if (getNonCapturingFunctions().count(cop.getCallee().str()))
continue;
}
return true;
}
}
return false;
}
Value getBase(Value v) {
while (true) {
if (auto s = v.getDefiningOp<SubIndexOp>()) {
v = s.getSource();
continue;
}
if (auto s = v.getDefiningOp<Memref2PointerOp>()) {
v = s.getSource();
continue;
}
if (auto s = v.getDefiningOp<Pointer2MemrefOp>()) {
v = s.getSource();
continue;
}
if (auto s = v.getDefiningOp<LLVM::GEPOp>()) {
v = s.getBase();
continue;
}
if (auto s = v.getDefiningOp<LLVM::BitcastOp>()) {
v = s.getArg();
continue;
}
if (auto s = v.getDefiningOp<LLVM::AddrSpaceCastOp>()) {
v = s.getArg();
continue;
}
if (auto s = v.getDefiningOp<memref::CastOp>()) {
v = s.getSource();
continue;
}
break;
}
return v;
}
bool isStackAlloca(Value v) {
return v.getDefiningOp<memref::AllocaOp>() ||
v.getDefiningOp<memref::AllocOp>() ||
v.getDefiningOp<LLVM::AllocaOp>();
}
static bool mayAlias(Value v, Value v2) {
v = getBase(v);
v2 = getBase(v2);
if (v == v2)
return true;
// We may now assume neither v1 nor v2 are subindices
if (auto glob = v.getDefiningOp<memref::GetGlobalOp>()) {
if (auto Aglob = v2.getDefiningOp<memref::GetGlobalOp>()) {
return glob.getName() == Aglob.getName();
}
}
if (auto glob = v.getDefiningOp<LLVM::AddressOfOp>()) {
if (auto Aglob = v2.getDefiningOp<LLVM::AddressOfOp>()) {
return glob.getGlobalName() == Aglob.getGlobalName();
}
}
bool isAlloca[2];
bool isGlobal[2];
isAlloca[0] = isStackAlloca(v);
isGlobal[0] = v.getDefiningOp<memref::GetGlobalOp>() ||
v.getDefiningOp<LLVM::AddressOfOp>();
isAlloca[1] = isStackAlloca(v2);
isGlobal[1] = v2.getDefiningOp<memref::GetGlobalOp>() ||
v2.getDefiningOp<LLVM::AddressOfOp>();
// Non-equivalent allocas/global's cannot conflict with each other
if ((isAlloca[0] || isGlobal[0]) && (isAlloca[1] || isGlobal[1]))
return false;
bool isArg[2];
isArg[0] = v.isa<BlockArgument>() &&
isa<FunctionOpInterface>(
v.cast<BlockArgument>().getOwner()->getParentOp());
isArg[1] = v.isa<BlockArgument>() &&
isa<FunctionOpInterface>(
v.cast<BlockArgument>().getOwner()->getParentOp());
// Stack allocations cannot have been passed as an argument.
if ((isAlloca[0] && isArg[1]) || (isAlloca[1] && isArg[0]))
return false;
// Non captured base allocas cannot conflict with another base value.
if (isAlloca[0] && !isCaptured(v))
return false;
if (isAlloca[1] && !isCaptured(v2))
return false;
return true;
}
bool mayAlias(MemoryEffects::EffectInstance a,
MemoryEffects::EffectInstance b) {
if (a.getResource()->getResourceID() != b.getResource()->getResourceID())
return false;
if (Value v2 = b.getValue()) {
return mayAlias(a, v2);
} else if (Value v = a.getValue()) {
return mayAlias(b, v);
}
return true;
}
bool mayAlias(MemoryEffects::EffectInstance a, Value v2) {
if (Value v = a.getValue()) {
return mayAlias(v, v2);
}
return true;
}
void BarrierOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results.insert<BarrierHoist, BarrierElim</*TopLevelOnly*/ false>>(context);
}
/// Replace cast(subindex(x, InterimType), FinalType) with subindex(x,
/// FinalType)
class CastOfSubIndex final : public OpRewritePattern<memref::CastOp> {
public:
using OpRewritePattern<memref::CastOp>::OpRewritePattern;
LogicalResult matchAndRewrite(memref::CastOp castOp,
PatternRewriter &rewriter) const override {
auto subindexOp = castOp.getSource().getDefiningOp<SubIndexOp>();
if (!subindexOp)
return failure();
if (castOp.getType().cast<MemRefType>().getShape().size() !=
subindexOp.getType().cast<MemRefType>().getShape().size())
return failure();
if (castOp.getType().cast<MemRefType>().getElementType() !=
subindexOp.getResult().getType().cast<MemRefType>().getElementType())
return failure();
rewriter.replaceOpWithNewOp<SubIndexOp>(castOp, castOp.getType(),
subindexOp.getSource(),
subindexOp.getIndex());
return success();
}
};
// Replace subindex(subindex(x)) with subindex(x) with appropriate
// indexing.
class SubIndex2 final : public OpRewritePattern<SubIndexOp> {
public:
using OpRewritePattern<SubIndexOp>::OpRewritePattern;
LogicalResult matchAndRewrite(SubIndexOp subViewOp,
PatternRewriter &rewriter) const override {
auto prevOp = subViewOp.getSource().getDefiningOp<SubIndexOp>();
if (!prevOp)
return failure();
auto mt0 = prevOp.getSource().getType().cast<MemRefType>();
auto mt1 = prevOp.getType().cast<MemRefType>();
auto mt2 = subViewOp.getType().cast<MemRefType>();
if (mt0.getShape().size() == mt2.getShape().size() &&
mt1.getShape().size() == mt0.getShape().size() + 1) {
rewriter.replaceOpWithNewOp<SubIndexOp>(
subViewOp, mt2, prevOp.getSource(), subViewOp.getIndex());
return success();
}
if (mt0.getShape().size() == mt2.getShape().size() &&
mt1.getShape().size() == mt0.getShape().size()) {
rewriter.replaceOpWithNewOp<SubIndexOp>(
subViewOp, mt2, prevOp.getSource(),
rewriter.create<AddIOp>(prevOp.getLoc(), subViewOp.getIndex(),
prevOp.getIndex()));
return success();
}
return failure();
}
};
// When possible, simplify subindex(x) to cast(x)
class SubToCast final : public OpRewritePattern<SubIndexOp> {
public:
using OpRewritePattern<SubIndexOp>::OpRewritePattern;
LogicalResult matchAndRewrite(SubIndexOp subViewOp,
PatternRewriter &rewriter) const override {
auto prev = subViewOp.getSource().getType().cast<MemRefType>();
auto post = subViewOp.getType().cast<MemRefType>();
bool legal = prev.getShape().size() == post.getShape().size();
if (legal) {
auto cidx = subViewOp.getIndex().getDefiningOp<ConstantIndexOp>();
if (!cidx)
return failure();
if (cidx.getValue() != 0)
return failure();
rewriter.replaceOpWithNewOp<memref::CastOp>(subViewOp, post,
subViewOp.getSource());
return success();
}
return failure();
}
};
// Simplify polygeist.subindex to memref.subview.
class SubToSubView final : public OpRewritePattern<SubIndexOp> {
public:
using OpRewritePattern<SubIndexOp>::OpRewritePattern;
LogicalResult matchAndRewrite(SubIndexOp op,
PatternRewriter &rewriter) const override {
auto srcMemRefType = op.getSource().getType().cast<MemRefType>();
auto resMemRefType = op.getResult().getType().cast<MemRefType>();
auto dims = srcMemRefType.getShape().size();
// For now, restrict subview lowering to statically defined memref's
if (!srcMemRefType.hasStaticShape() | !resMemRefType.hasStaticShape())
return failure();
// For now, restrict to simple rank-reducing indexing
if (srcMemRefType.getShape().size() <= resMemRefType.getShape().size())
return failure();
// Build offset, sizes and strides
SmallVector<OpFoldResult> sizes(dims, rewriter.getIndexAttr(0));
sizes[0] = op.getIndex();
SmallVector<OpFoldResult> offsets(dims);
for (auto dim : llvm::enumerate(srcMemRefType.getShape())) {
if (dim.index() == 0)
offsets[0] = rewriter.getIndexAttr(1);
else
offsets[dim.index()] = rewriter.getIndexAttr(dim.value());
}
SmallVector<OpFoldResult> strides(dims, rewriter.getIndexAttr(1));
// Generate the appropriate return type:
auto subMemRefType = MemRefType::get(srcMemRefType.getShape().drop_front(),
srcMemRefType.getElementType());
rewriter.replaceOpWithNewOp<memref::SubViewOp>(
op, subMemRefType, op.getSource(), sizes, offsets, strides);
return success();
}
};
// Simplify redundant dynamic subindex patterns which tries to represent
// rank-reducing indexing: